task_url
stringlengths 30
116
| task_name
stringlengths 2
86
| task_description
stringlengths 0
14.4k
| language_url
stringlengths 2
53
| language_name
stringlengths 1
52
| code
stringlengths 0
61.9k
|
---|---|---|---|---|---|
http://rosettacode.org/wiki/Convert_seconds_to_compound_duration | Convert seconds to compound duration | Task
Write a function or program which:
takes a positive integer representing a duration in seconds as input (e.g., 100), and
returns a string which shows the same duration decomposed into:
weeks,
days,
hours,
minutes, and
seconds.
This is detailed below (e.g., "2 hr, 59 sec").
Demonstrate that it passes the following three test-cases:
Test Cases
input number
output string
7259
2 hr, 59 sec
86400
1 d
6000000
9 wk, 6 d, 10 hr, 40 min
Details
The following five units should be used:
unit
suffix used in output
conversion
week
wk
1 week = 7 days
day
d
1 day = 24 hours
hour
hr
1 hour = 60 minutes
minute
min
1 minute = 60 seconds
second
sec
However, only include quantities with non-zero values in the output (e.g., return "1 d" and not "0 wk, 1 d, 0 hr, 0 min, 0 sec").
Give larger units precedence over smaller ones as much as possible (e.g., return 2 min, 10 sec and not 1 min, 70 sec or 130 sec)
Mimic the formatting shown in the test-cases (quantities sorted from largest unit to smallest and separated by comma+space; value and unit of each quantity separated by space).
| #Haskell | Haskell | import Control.Monad (forM_)
import Data.List (intercalate, mapAccumR)
import System.Environment (getArgs)
import Text.Printf (printf)
import Text.Read (readMaybe)
reduceBy :: Integral a => a -> [a] -> [a]
n `reduceBy` xs = n' : ys where (n', ys) = mapAccumR quotRem n xs
-- Duration/label pairs.
durLabs :: [(Integer, String)]
durLabs = [(undefined, "wk"), (7, "d"), (24, "hr"), (60, "min"), (60, "sec")]
-- Time broken down into non-zero durations and their labels.
compdurs :: Integer -> [(Integer, String)]
compdurs t = let ds = t `reduceBy` (map fst $ tail durLabs)
in filter ((/=0) . fst) $ zip ds (map snd durLabs)
-- Compound duration of t seconds. The argument is assumed to be positive.
compoundDuration :: Integer -> String
compoundDuration = intercalate ", " . map (uncurry $ printf "%d %s") . compdurs
main :: IO ()
main = do
args <- getArgs
forM_ args $ \arg -> case readMaybe arg of
Just n -> printf "%7d seconds = %s\n" n (compoundDuration n)
Nothing -> putStrLn $ "Invalid number of seconds: " ++ arg |
http://rosettacode.org/wiki/Composite_numbers_k_with_no_single_digit_factors_whose_factors_are_all_substrings_of_k | Composite numbers k with no single digit factors whose factors are all substrings of k | Find the composite numbers k in base 10, that have no single digit prime factors and whose prime factors are all a substring of k.
Task
Find and show here, on this page, the first ten elements of the sequence.
Stretch
Find and show the next ten elements.
| #Wren | Wren | import "/math" for Int
import "/seq" for Lst
import "/fmt" for Fmt
var count = 0
var k = 11 * 11
var res = []
while (count < 20) {
if (k % 3 == 0 || k % 5 == 0 || k % 7 == 0) {
k = k + 2
continue
}
var factors = Int.primeFactors(k)
if (factors.count > 1) {
Lst.prune(factors)
var s = k.toString
var includesAll = true
for (f in factors) {
if (s.indexOf(f.toString) == -1) {
includesAll = false
break
}
}
if (includesAll) {
res.add(k)
count = count + 1
}
}
k = k + 2
}
Fmt.print("$,10d", res[0..9])
Fmt.print("$,10d", res[10..19]) |
http://rosettacode.org/wiki/Composite_numbers_k_with_no_single_digit_factors_whose_factors_are_all_substrings_of_k | Composite numbers k with no single digit factors whose factors are all substrings of k | Find the composite numbers k in base 10, that have no single digit prime factors and whose prime factors are all a substring of k.
Task
Find and show here, on this page, the first ten elements of the sequence.
Stretch
Find and show the next ten elements.
| #XPL0 | XPL0 | include xpllib; \for ItoA, StrFind and RlOutC
int K, C;
proc Factor; \Show certain K factors
int L, N, F, Q;
char SA(10), SB(10);
[ItoA(K, SB);
L:= sqrt(K); \limit for speed
N:= K; F:= 3;
if (N&1) = 0 then return; \reject if 2 is a factor
loop [Q:= N/F;
if rem(0) = 0 then \found a factor, F
[if F < 10 then return; \reject if too small (3, 5, 7)
ItoA(F, SA); \reject if not a sub-string
if StrFind(SB, SA) = 0 then return;
N:= Q;
if F>N then quit; \all factors found
]
else [F:= F+2; \try next prime factor
if F>L then
[if N=K then return; \reject prime K
ItoA(N, SA); \ (it's not composite)
if StrFind(SB, SA) = 0 then return;
quit; \passed all restrictions
];
];
];
Format(9, 0);
RlOutC(0, float(K));
C:= C+1;
if rem(C/10) = 0 then CrLf(0);
];
[C:= 0; \initialize element counter
K:= 11*11; \must have at least two 2-digit composites
repeat Factor;
K:= K+2; \must be odd because all factors > 2 are odd primes
until C >= 20;
] |
http://rosettacode.org/wiki/Conjugate_transpose | Conjugate transpose | Suppose that a matrix
M
{\displaystyle M}
contains complex numbers. Then the conjugate transpose of
M
{\displaystyle M}
is a matrix
M
H
{\displaystyle M^{H}}
containing the complex conjugates of the matrix transposition of
M
{\displaystyle M}
.
(
M
H
)
j
i
=
M
i
j
¯
{\displaystyle (M^{H})_{ji}={\overline {M_{ij}}}}
This means that row
j
{\displaystyle j}
, column
i
{\displaystyle i}
of the conjugate transpose equals the
complex conjugate of row
i
{\displaystyle i}
, column
j
{\displaystyle j}
of the original matrix.
In the next list,
M
{\displaystyle M}
must also be a square matrix.
A Hermitian matrix equals its own conjugate transpose:
M
H
=
M
{\displaystyle M^{H}=M}
.
A normal matrix is commutative in multiplication with its conjugate transpose:
M
H
M
=
M
M
H
{\displaystyle M^{H}M=MM^{H}}
.
A unitary matrix has its inverse equal to its conjugate transpose:
M
H
=
M
−
1
{\displaystyle M^{H}=M^{-1}}
.
This is true iff
M
H
M
=
I
n
{\displaystyle M^{H}M=I_{n}}
and iff
M
M
H
=
I
n
{\displaystyle MM^{H}=I_{n}}
, where
I
n
{\displaystyle I_{n}}
is the identity matrix.
Task
Given some matrix of complex numbers, find its conjugate transpose.
Also determine if the matrix is a:
Hermitian matrix,
normal matrix, or
unitary matrix.
See also
MathWorld entry: conjugate transpose
MathWorld entry: Hermitian matrix
MathWorld entry: normal matrix
MathWorld entry: unitary matrix
| #11l | 11l | -V eps = 1e-10
F to_str(m)
V r = ‘’
L(row) m
V i = L.index
r ‘’= I i == 0 {‘[’} E ‘ ’
L(val) row
V j = L.index
I j != 0
r ‘’= ‘ ’
r ‘’= ‘(#2.4, #2.4)’.format(val.real, val.imag)
r ‘’= I i == m.len - 1 {‘]’} E "\n"
R r
F conjugateTransposed(m)
V r = [[0i] * m.len] * m.len
L(i) 0 .< m.len
L(j) 0 .< m.len
r[j][i] = conjugate(m[i][j])
R r
F mmul(m1, m2)
V r = [[0i] * m1.len] * m1.len
L(i) 0 .< m1.len
L(j) 0 .< m1.len
L(k) 0 .< m1.len
r[i][j] += m1[i][k] * m2[k][j]
R r
F isHermitian(m)
L(i) 0 .< m.len
L(j) 0 .< m.len
I m[i][j] != conjugate(m[j][i])
R 0B
R 1B
F isEqual(m1, m2)
L(i) 0 .< m1.len
L(j) 0 .< m1.len
I m1[i][j] != m2[i][j]
R 0B
R 1B
F isNormal(m)
V h = conjugateTransposed(m)
R isEqual(mmul(m, h), mmul(h, m))
F isIdentity(m)
L(i) 0 .< m.len
L(j) 0 .< m.len
I i == j
I abs(m[i][j] - 1.0) > :eps
R 0B
E
I abs(m[i][j]) > :eps
R 0B
R 1B
F isUnitary(m)
V h = conjugateTransposed(m)
R isIdentity(mmul(m, h)) & isIdentity(mmul(h, m))
F test(m)
print(‘Matrix’)
print(‘------’)
print(to_str(m))
print(‘’)
print(‘Conjugate transposed’)
print(‘--------------------’)
print(to_str(conjugateTransposed(m)))
print(‘’)
print(‘Hermitian: ’(I isHermitian(m) {‘true’} E ‘false’))
print(‘Normal: ’(I isNormal(m) {‘true’} E ‘false’))
print(‘Unitary: ’(I isUnitary(m) {‘true’} E ‘false’))
V M2 = [[3.0 + 0.0i, 2.0 + 1.0i],
[2.0 - 1.0i, 1.0 + 0.0i]]
V M3 = [[1.0 + 0.0i, 1.0 + 0.0i, 0.0 + 0.0i],
[0.0 + 0.0i, 1.0 + 0.0i, 1.0 + 0.0i],
[1.0 + 0.0i, 0.0 + 0.0i, 1.0 + 0.0i]]
V SR2 = 1 / sqrt(2.0)
V SR2i = SR2 * 1i
V M4 = [[SR2 + 0.0i, SR2 + 0.0i, 0.0 + 0.0i],
[0.0 + SR2i, 0.0 - SR2i, 0.0 + 0.0i],
[0.0 + 0.0i, 0.0 + 0.0i, 0.0 + 1.0i]]
test(M2)
print("\n")
test(M3)
print("\n")
test(M4) |
http://rosettacode.org/wiki/Continued_fraction | Continued fraction | continued fraction
Mathworld
a
0
+
b
1
a
1
+
b
2
a
2
+
b
3
a
3
+
⋱
{\displaystyle a_{0}+{\cfrac {b_{1}}{a_{1}+{\cfrac {b_{2}}{a_{2}+{\cfrac {b_{3}}{a_{3}+\ddots }}}}}}}
The task is to write a program which generates such a number and prints a real representation of it. The code should be tested by calculating and printing the square root of 2, Napier's Constant, and Pi, using the following coefficients:
For the square root of 2, use
a
0
=
1
{\displaystyle a_{0}=1}
then
a
N
=
2
{\displaystyle a_{N}=2}
.
b
N
{\displaystyle b_{N}}
is always
1
{\displaystyle 1}
.
2
=
1
+
1
2
+
1
2
+
1
2
+
⋱
{\displaystyle {\sqrt {2}}=1+{\cfrac {1}{2+{\cfrac {1}{2+{\cfrac {1}{2+\ddots }}}}}}}
For Napier's Constant, use
a
0
=
2
{\displaystyle a_{0}=2}
, then
a
N
=
N
{\displaystyle a_{N}=N}
.
b
1
=
1
{\displaystyle b_{1}=1}
then
b
N
=
N
−
1
{\displaystyle b_{N}=N-1}
.
e
=
2
+
1
1
+
1
2
+
2
3
+
3
4
+
⋱
{\displaystyle e=2+{\cfrac {1}{1+{\cfrac {1}{2+{\cfrac {2}{3+{\cfrac {3}{4+\ddots }}}}}}}}}
For Pi, use
a
0
=
3
{\displaystyle a_{0}=3}
then
a
N
=
6
{\displaystyle a_{N}=6}
.
b
N
=
(
2
N
−
1
)
2
{\displaystyle b_{N}=(2N-1)^{2}}
.
π
=
3
+
1
6
+
9
6
+
25
6
+
⋱
{\displaystyle \pi =3+{\cfrac {1}{6+{\cfrac {9}{6+{\cfrac {25}{6+\ddots }}}}}}}
See also
Continued fraction/Arithmetic for tasks that do arithmetic over continued fractions.
| #Groovy | Groovy | import java.util.function.Function
import static java.lang.Math.pow
class Test {
static double calc(Function<Integer, Integer[]> f, int n) {
double temp = 0
for (int ni = n; ni >= 1; ni--) {
Integer[] p = f.apply(ni)
temp = p[1] / (double) (p[0] + temp)
}
return f.apply(0)[0] + temp
}
static void main(String[] args) {
List<Function<Integer, Integer[]>> fList = new ArrayList<>()
fList.add({ n -> [n > 0 ? 2 : 1, 1] })
fList.add({ n -> [n > 0 ? n : 2, n > 1 ? (n - 1) : 1] })
fList.add({ n -> [n > 0 ? 6 : 3, (int) pow(2 * n - 1, 2)] })
for (Function<Integer, Integer[]> f : fList)
System.out.println(calc(f, 200))
}
} |
http://rosettacode.org/wiki/Copy_a_string | Copy a string | This task is about copying a string.
Task
Where it is relevant, distinguish between copying the contents of a string
versus making an additional reference to an existing string.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Latitude | Latitude | a := "Hello".
b := a.
c := a clone.
println: a == b. ; True
println: a == c. ; True
println: a === b. ; True
println: a === c. ; False |
http://rosettacode.org/wiki/Copy_a_string | Copy a string | This task is about copying a string.
Task
Where it is relevant, distinguish between copying the contents of a string
versus making an additional reference to an existing string.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #LC3_Assembly | LC3 Assembly | .ORIG 0x3000
LEA R1,SRC
LEA R2,COPY
LOOP LDR R3,R1,0
STR R3,R2,0
BRZ DONE
ADD R1,R1,1
ADD R2,R2,1
BRNZP LOOP
DONE LEA R0,COPY
PUTS
HALT
SRC .STRINGZ "What, has this thing appeared again tonight?"
COPY .BLKW 128
.END |
http://rosettacode.org/wiki/Constrained_random_points_on_a_circle | Constrained random points on a circle | Task
Generate 100 <x,y> coordinate pairs such that x and y are integers sampled from the uniform distribution with the condition that
10
≤
x
2
+
y
2
≤
15
{\displaystyle 10\leq {\sqrt {x^{2}+y^{2}}}\leq 15}
.
Then display/plot them. The outcome should be a "fuzzy" circle. The actual number of points plotted may be less than 100, given that some pairs may be generated more than once.
There are several possible approaches to accomplish this. Here are two possible algorithms.
1) Generate random pairs of integers and filter out those that don't satisfy this condition:
10
≤
x
2
+
y
2
≤
15
{\displaystyle 10\leq {\sqrt {x^{2}+y^{2}}}\leq 15}
.
2) Precalculate the set of all possible points (there are 404 of them) and select randomly from this set.
| #Delphi | Delphi |
unit Main;
interface
uses
Winapi.Windows, System.SysUtils, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.ExtCtrls;
type
TForm1 = class(TForm)
procedure FormCreate(Sender: TObject);
procedure FormPaint(Sender: TObject);
end;
var
Form1: TForm1;
Points: TArray<TPoint>;
implementation
{$R *.dfm}
procedure TForm1.FormCreate(Sender: TObject);
begin
ClientHeight := 600;
ClientWidth := 600;
end;
procedure TForm1.FormPaint(Sender: TObject);
var
i: integer;
p: TPoint;
index: integer;
begin
SetLength(Points, 404);
i := 0;
for var y := -15 to 15 do
for var x := -15 to 15 do
begin
if i >= 404 then
Break;
var c := Sqrt(x * x + y * y);
if (10 <= c) and (c <= 15) then
begin
inc(i);
points[i] := TPoint.Create(x, y);
end;
end;
var bm := TBitmap.create;
bm.SetSize(600, 600);
with bm.Canvas do
begin
Pen.Color := clRed;
Brush.Color := clRed;
Brush.Style := bsSolid;
Randomize;
for var count := 0 to 99 do
begin
repeat
index := Random(404);
p := points[index];
until (not p.IsZero);
points[index] := TPoint.Zero;
var cx := 290 + 19 * p.X;
var cy := 290 + 19 * p.Y;
Ellipse(cx - 5, cy - 5, cx + 5, cy + 5);
end;
end;
Canvas.Draw(0, 0, bm);
bm.Free;
end;
end. |
http://rosettacode.org/wiki/Convex_hull | Convex hull | Find the points which form a convex hull from a set of arbitrary two dimensional points.
For example, given the points (16,3), (12,17), (0,6), (-4,-6), (16,6), (16,-7), (16,-3), (17,-4), (5,19), (19,-8), (3,16), (12,13), (3,-4), (17,5), (-3,15), (-3,-9), (0,11), (-9,-3), (-4,-2) and (12,10) the convex hull would be (-9,-3), (-3,-9), (19,-8), (17,5), (12,17), (5,19) and (-3,15).
See also
Convex Hull (youtube)
http://www.geeksforgeeks.org/convex-hull-set-2-graham-scan/
| #Haskell | Haskell | import Data.List (sortBy, groupBy, maximumBy)
import Data.Ord (comparing)
(x, y) = ((!! 0), (!! 1))
compareFrom
:: (Num a, Ord a)
=> [a] -> [a] -> [a] -> Ordering
compareFrom o l r =
compare ((x l - x o) * (y r - y o)) ((y l - y o) * (x r - x o))
distanceFrom
:: Floating a
=> [a] -> [a] -> a
distanceFrom from to = ((x to - x from) ** 2 + (y to - y from) ** 2) ** (1 / 2)
convexHull
:: (Floating a, Ord a)
=> [[a]] -> [[a]]
convexHull points =
let o = minimum points
presorted = sortBy (compareFrom o) (filter (/= o) points)
collinears = groupBy (((EQ ==) .) . compareFrom o) presorted
outmost = maximumBy (comparing (distanceFrom o)) <$> collinears
in dropConcavities [o] outmost
dropConcavities
:: (Num a, Ord a)
=> [[a]] -> [[a]] -> [[a]]
dropConcavities (left:lefter) (right:righter:rightest) =
case compareFrom left right righter of
LT -> dropConcavities (right : left : lefter) (righter : rightest)
EQ -> dropConcavities (left : lefter) (righter : rightest)
GT -> dropConcavities lefter (left : righter : rightest)
dropConcavities output lastInput = lastInput ++ output
main :: IO ()
main =
mapM_ print $
convexHull
[ [16, 3]
, [12, 17]
, [0, 6]
, [-4, -6]
, [16, 6]
, [16, -7]
, [16, -3]
, [17, -4]
, [5, 19]
, [19, -8]
, [3, 16]
, [12, 13]
, [3, -4]
, [17, 5]
, [-3, 15]
, [-3, -9]
, [0, 11]
, [-9, -3]
, [-4, -2]
, [12, 10]
] |
http://rosettacode.org/wiki/Convert_seconds_to_compound_duration | Convert seconds to compound duration | Task
Write a function or program which:
takes a positive integer representing a duration in seconds as input (e.g., 100), and
returns a string which shows the same duration decomposed into:
weeks,
days,
hours,
minutes, and
seconds.
This is detailed below (e.g., "2 hr, 59 sec").
Demonstrate that it passes the following three test-cases:
Test Cases
input number
output string
7259
2 hr, 59 sec
86400
1 d
6000000
9 wk, 6 d, 10 hr, 40 min
Details
The following five units should be used:
unit
suffix used in output
conversion
week
wk
1 week = 7 days
day
d
1 day = 24 hours
hour
hr
1 hour = 60 minutes
minute
min
1 minute = 60 seconds
second
sec
However, only include quantities with non-zero values in the output (e.g., return "1 d" and not "0 wk, 1 d, 0 hr, 0 min, 0 sec").
Give larger units precedence over smaller ones as much as possible (e.g., return 2 min, 10 sec and not 1 min, 70 sec or 130 sec)
Mimic the formatting shown in the test-cases (quantities sorted from largest unit to smallest and separated by comma+space; value and unit of each quantity separated by space).
| #J | J | fmtsecs=: verb define
seq=. 0 7 24 60 60 #: y
}: ;:inv ,(0 ~: seq) # (8!:0 seq) ,. <;.2'wk,d,hr,min,sec,'
) |
http://rosettacode.org/wiki/Conjugate_transpose | Conjugate transpose | Suppose that a matrix
M
{\displaystyle M}
contains complex numbers. Then the conjugate transpose of
M
{\displaystyle M}
is a matrix
M
H
{\displaystyle M^{H}}
containing the complex conjugates of the matrix transposition of
M
{\displaystyle M}
.
(
M
H
)
j
i
=
M
i
j
¯
{\displaystyle (M^{H})_{ji}={\overline {M_{ij}}}}
This means that row
j
{\displaystyle j}
, column
i
{\displaystyle i}
of the conjugate transpose equals the
complex conjugate of row
i
{\displaystyle i}
, column
j
{\displaystyle j}
of the original matrix.
In the next list,
M
{\displaystyle M}
must also be a square matrix.
A Hermitian matrix equals its own conjugate transpose:
M
H
=
M
{\displaystyle M^{H}=M}
.
A normal matrix is commutative in multiplication with its conjugate transpose:
M
H
M
=
M
M
H
{\displaystyle M^{H}M=MM^{H}}
.
A unitary matrix has its inverse equal to its conjugate transpose:
M
H
=
M
−
1
{\displaystyle M^{H}=M^{-1}}
.
This is true iff
M
H
M
=
I
n
{\displaystyle M^{H}M=I_{n}}
and iff
M
M
H
=
I
n
{\displaystyle MM^{H}=I_{n}}
, where
I
n
{\displaystyle I_{n}}
is the identity matrix.
Task
Given some matrix of complex numbers, find its conjugate transpose.
Also determine if the matrix is a:
Hermitian matrix,
normal matrix, or
unitary matrix.
See also
MathWorld entry: conjugate transpose
MathWorld entry: Hermitian matrix
MathWorld entry: normal matrix
MathWorld entry: unitary matrix
| #Ada | Ada | with Ada.Text_IO; use Ada.Text_IO;
with Ada.Complex_Text_IO; use Ada.Complex_Text_IO;
with Ada.Numerics.Complex_Types; use Ada.Numerics.Complex_Types;
with Ada.Numerics.Complex_Arrays; use Ada.Numerics.Complex_Arrays;
procedure ConTrans is
subtype CM is Complex_Matrix;
S2O2 : constant Float := 0.7071067811865;
procedure Print (mat : CM) is begin
for row in mat'Range(1) loop for col in mat'Range(2) loop
Put(mat(row,col), Exp=>0, Aft=>4);
end loop; New_Line; end loop;
end Print;
function almostzero(mat : CM; tol : Float) return Boolean is begin
for row in mat'Range(1) loop for col in mat'Range(2) loop
if abs(mat(row,col)) > tol then return False; end if;
end loop; end loop;
return True;
end almostzero;
procedure Examine (mat : CM) is
CT : CM := Conjugate (Transpose(mat));
isherm, isnorm, isunit : Boolean;
begin
isherm := almostzero(mat-CT, 1.0e-6);
isnorm := almostzero(mat*CT-CT*mat, 1.0e-6);
isunit := almostzero(CT-Inverse(mat), 1.0e-6);
Print(mat);
Put_Line("Conjugate transpose:"); Print(CT);
Put_Line("Hermitian?: " & isherm'Img);
Put_Line("Normal?: " & isnorm'Img);
Put_Line("Unitary?: " & isunit'Img);
end Examine;
hmat : CM := ((3.0+0.0*i, 2.0+1.0*i), (2.0-1.0*i, 1.0+0.0*i));
nmat : CM := ((1.0+0.0*i, 1.0+0.0*i, 0.0+0.0*i),
(0.0+0.0*i, 1.0+0.0*i, 1.0+0.0*i),
(1.0+0.0*i, 0.0+0.0*i, 1.0+0.0*i));
umat : CM := ((S2O2+0.0*i, S2O2+0.0*i, 0.0+0.0*i),
(0.0+S2O2*i, 0.0-S2O2*i, 0.0+0.0*i),
(0.0+0.0*i, 0.0+0.0*i, 0.0+1.0*i));
begin
Put_Line("hmat:"); Examine(hmat); New_Line;
Put_Line("nmat:"); Examine(nmat); New_Line;
Put_Line("umat:"); Examine(umat);
end ConTrans; |
http://rosettacode.org/wiki/Continued_fraction | Continued fraction | continued fraction
Mathworld
a
0
+
b
1
a
1
+
b
2
a
2
+
b
3
a
3
+
⋱
{\displaystyle a_{0}+{\cfrac {b_{1}}{a_{1}+{\cfrac {b_{2}}{a_{2}+{\cfrac {b_{3}}{a_{3}+\ddots }}}}}}}
The task is to write a program which generates such a number and prints a real representation of it. The code should be tested by calculating and printing the square root of 2, Napier's Constant, and Pi, using the following coefficients:
For the square root of 2, use
a
0
=
1
{\displaystyle a_{0}=1}
then
a
N
=
2
{\displaystyle a_{N}=2}
.
b
N
{\displaystyle b_{N}}
is always
1
{\displaystyle 1}
.
2
=
1
+
1
2
+
1
2
+
1
2
+
⋱
{\displaystyle {\sqrt {2}}=1+{\cfrac {1}{2+{\cfrac {1}{2+{\cfrac {1}{2+\ddots }}}}}}}
For Napier's Constant, use
a
0
=
2
{\displaystyle a_{0}=2}
, then
a
N
=
N
{\displaystyle a_{N}=N}
.
b
1
=
1
{\displaystyle b_{1}=1}
then
b
N
=
N
−
1
{\displaystyle b_{N}=N-1}
.
e
=
2
+
1
1
+
1
2
+
2
3
+
3
4
+
⋱
{\displaystyle e=2+{\cfrac {1}{1+{\cfrac {1}{2+{\cfrac {2}{3+{\cfrac {3}{4+\ddots }}}}}}}}}
For Pi, use
a
0
=
3
{\displaystyle a_{0}=3}
then
a
N
=
6
{\displaystyle a_{N}=6}
.
b
N
=
(
2
N
−
1
)
2
{\displaystyle b_{N}=(2N-1)^{2}}
.
π
=
3
+
1
6
+
9
6
+
25
6
+
⋱
{\displaystyle \pi =3+{\cfrac {1}{6+{\cfrac {9}{6+{\cfrac {25}{6+\ddots }}}}}}}
See also
Continued fraction/Arithmetic for tasks that do arithmetic over continued fractions.
| #Haskell | Haskell | import Data.List (unfoldr)
import Data.Char (intToDigit)
-- continued fraction represented as a (possibly infinite) list of pairs
sqrt2, napier, myPi :: [(Integer, Integer)]
sqrt2 = zip (1 : [2,2 ..]) [1,1 ..]
napier = zip (2 : [1 ..]) (1 : [1 ..])
myPi = zip (3 : [6,6 ..]) ((^ 2) <$> [1,3 ..])
-- approximate a continued fraction after certain number of iterations
approxCF
:: (Integral a, Fractional b)
=> Int -> [(a, a)] -> b
approxCF t = foldr (\(a, b) z -> fromIntegral a + fromIntegral b / z) 1 . take t
-- infinite decimal representation of a real number
decString
:: RealFrac a
=> a -> String
decString frac = show i ++ '.' : decString_ f
where
(i, f) = properFraction frac
decString_ = map intToDigit . unfoldr (Just . properFraction . (10 *))
main :: IO ()
main =
mapM_
(putStrLn .
take 200 . decString . (approxCF 950 :: [(Integer, Integer)] -> Rational))
[sqrt2, napier, myPi] |
http://rosettacode.org/wiki/Copy_a_string | Copy a string | This task is about copying a string.
Task
Where it is relevant, distinguish between copying the contents of a string
versus making an additional reference to an existing string.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #LFE | LFE | (let* ((a '"data assigned to a")
(b a))
(: io format '"Contents of 'b': ~s~n" (list b))) |
http://rosettacode.org/wiki/Copy_a_string | Copy a string | This task is about copying a string.
Task
Where it is relevant, distinguish between copying the contents of a string
versus making an additional reference to an existing string.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Liberty_BASIC | Liberty BASIC | src$ = "Hello"
dest$ = src$
print src$
print dest$
|
http://rosettacode.org/wiki/Constrained_random_points_on_a_circle | Constrained random points on a circle | Task
Generate 100 <x,y> coordinate pairs such that x and y are integers sampled from the uniform distribution with the condition that
10
≤
x
2
+
y
2
≤
15
{\displaystyle 10\leq {\sqrt {x^{2}+y^{2}}}\leq 15}
.
Then display/plot them. The outcome should be a "fuzzy" circle. The actual number of points plotted may be less than 100, given that some pairs may be generated more than once.
There are several possible approaches to accomplish this. Here are two possible algorithms.
1) Generate random pairs of integers and filter out those that don't satisfy this condition:
10
≤
x
2
+
y
2
≤
15
{\displaystyle 10\leq {\sqrt {x^{2}+y^{2}}}\leq 15}
.
2) Precalculate the set of all possible points (there are 404 of them) and select randomly from this set.
| #EchoLisp | EchoLisp |
(lib 'math)
(lib 'plot)
(define (points (n 100) (radius 10) (rmin 10) (rmax 15) (x) (y))
(plot-clear)
(plot-x-minmax (- rmax))
(plot-y-minmax( - rmax))
(for [(i n)]
(set! x (round (* (random -1) rmax)))
(set! y (round (* (random -1) rmax)))
#:when (in-interval? (pythagore x y) rmin rmax)
;; add a little bit of randomness : dots color and radius
(plot-fill-color (hsv->rgb (random) 0.9 0.9))
(plot-circle x y (random radius)))
(plot-edit))
|
http://rosettacode.org/wiki/Convex_hull | Convex hull | Find the points which form a convex hull from a set of arbitrary two dimensional points.
For example, given the points (16,3), (12,17), (0,6), (-4,-6), (16,6), (16,-7), (16,-3), (17,-4), (5,19), (19,-8), (3,16), (12,13), (3,-4), (17,5), (-3,15), (-3,-9), (0,11), (-9,-3), (-4,-2) and (12,10) the convex hull would be (-9,-3), (-3,-9), (19,-8), (17,5), (12,17), (5,19) and (-3,15).
See also
Convex Hull (youtube)
http://www.geeksforgeeks.org/convex-hull-set-2-graham-scan/
| #Haxe | Haxe | typedef Point = {x:Float, y:Float};
class Main {
// Calculate orientation for 3 points
// 0 -> Straight line
// 1 -> Clockwise
// 2 -> Counterclockwise
static function orientation(pt1:Point, pt2:Point, pt3:Point): Int
{
var val = ((pt2.x - pt1.x) * (pt3.y - pt1.y)) -
((pt2.y - pt1.y) * (pt3.x - pt1.x));
if (val == 0)
return 0;
else if (val > 0)
return 1;
else return 2;
}
static function convexHull(pts:Array<Point>):Array<Point> {
var result = new Array<Point>();
// There must be at least 3 points
if (pts.length < 3)
for (i in pts) result.push(i);
// Find the leftmost point
var indexMinX = 0;
for (i in 0...(pts.length - 1))
if (pts[i].x < pts[indexMinX].x)
indexMinX = i;
var p = indexMinX;
var q = 0;
while (true) {
// The leftmost point must be part of the hull.
result.push(pts[p]);
q = (p + 1) % pts.length;
for (i in 0...(pts.length - 1))
if (orientation(pts[p], pts[i], pts[q]) == 2) q = i;
p = q;
// Break from loop once we reach the first point again.
if (p == indexMinX)
break;
}
return result;
}
static function main() {
var pts = new Array<Point>();
pts.push({x: 16, y: 3});
pts.push({x: 12, y: 17});
pts.push({x: 0, y: 6});
pts.push({x: -4, y: -6});
pts.push({x: 16, y: 6});
pts.push({x: 16, y: -7});
pts.push({x: 16, y: -3});
pts.push({x: 17, y: -4});
pts.push({x: 5, y: 19});
pts.push({x: 19, y: -8});
pts.push({x: 3, y: 16});
pts.push({x: 12, y: 13});
pts.push({x: 3, y: -4});
pts.push({x: 17, y: 5});
pts.push({x: -3, y: 15});
pts.push({x: -3, y: -9});
pts.push({x: 0, y: 11});
pts.push({x: -9, y: -3});
pts.push({x: -4, y: -2});
pts.push({x: 12, y: 10});
var hull = convexHull(pts);
Sys.print('Convex Hull: [');
var length = hull.length;
var i = 0;
while (length > 0) {
if (i > 0)
Sys.print(', ');
Sys.print('(${hull[i].x}, ${hull[i].y})');
length--;
i++;
}
Sys.println(']');
}
} |
http://rosettacode.org/wiki/Convert_seconds_to_compound_duration | Convert seconds to compound duration | Task
Write a function or program which:
takes a positive integer representing a duration in seconds as input (e.g., 100), and
returns a string which shows the same duration decomposed into:
weeks,
days,
hours,
minutes, and
seconds.
This is detailed below (e.g., "2 hr, 59 sec").
Demonstrate that it passes the following three test-cases:
Test Cases
input number
output string
7259
2 hr, 59 sec
86400
1 d
6000000
9 wk, 6 d, 10 hr, 40 min
Details
The following five units should be used:
unit
suffix used in output
conversion
week
wk
1 week = 7 days
day
d
1 day = 24 hours
hour
hr
1 hour = 60 minutes
minute
min
1 minute = 60 seconds
second
sec
However, only include quantities with non-zero values in the output (e.g., return "1 d" and not "0 wk, 1 d, 0 hr, 0 min, 0 sec").
Give larger units precedence over smaller ones as much as possible (e.g., return 2 min, 10 sec and not 1 min, 70 sec or 130 sec)
Mimic the formatting shown in the test-cases (quantities sorted from largest unit to smallest and separated by comma+space; value and unit of each quantity separated by space).
| #Java | Java | public class CompoundDuration {
public static void main(String[] args) {
compound(7259);
compound(86400);
compound(6000_000);
}
private static void compound(long seconds) {
StringBuilder sb = new StringBuilder();
seconds = addUnit(sb, seconds, 604800, " wk, ");
seconds = addUnit(sb, seconds, 86400, " d, ");
seconds = addUnit(sb, seconds, 3600, " hr, ");
seconds = addUnit(sb, seconds, 60, " min, ");
addUnit(sb, seconds, 1, " sec, ");
sb.setLength(sb.length() > 2 ? sb.length() - 2 : 0);
System.out.println(sb);
}
private static long addUnit(StringBuilder sb, long sec, long unit, String s) {
long n;
if ((n = sec / unit) > 0) {
sb.append(n).append(s);
sec %= (n * unit);
}
return sec;
}
} |
http://rosettacode.org/wiki/Conjugate_transpose | Conjugate transpose | Suppose that a matrix
M
{\displaystyle M}
contains complex numbers. Then the conjugate transpose of
M
{\displaystyle M}
is a matrix
M
H
{\displaystyle M^{H}}
containing the complex conjugates of the matrix transposition of
M
{\displaystyle M}
.
(
M
H
)
j
i
=
M
i
j
¯
{\displaystyle (M^{H})_{ji}={\overline {M_{ij}}}}
This means that row
j
{\displaystyle j}
, column
i
{\displaystyle i}
of the conjugate transpose equals the
complex conjugate of row
i
{\displaystyle i}
, column
j
{\displaystyle j}
of the original matrix.
In the next list,
M
{\displaystyle M}
must also be a square matrix.
A Hermitian matrix equals its own conjugate transpose:
M
H
=
M
{\displaystyle M^{H}=M}
.
A normal matrix is commutative in multiplication with its conjugate transpose:
M
H
M
=
M
M
H
{\displaystyle M^{H}M=MM^{H}}
.
A unitary matrix has its inverse equal to its conjugate transpose:
M
H
=
M
−
1
{\displaystyle M^{H}=M^{-1}}
.
This is true iff
M
H
M
=
I
n
{\displaystyle M^{H}M=I_{n}}
and iff
M
M
H
=
I
n
{\displaystyle MM^{H}=I_{n}}
, where
I
n
{\displaystyle I_{n}}
is the identity matrix.
Task
Given some matrix of complex numbers, find its conjugate transpose.
Also determine if the matrix is a:
Hermitian matrix,
normal matrix, or
unitary matrix.
See also
MathWorld entry: conjugate transpose
MathWorld entry: Hermitian matrix
MathWorld entry: normal matrix
MathWorld entry: unitary matrix
| #ALGOL_68 | ALGOL 68 | BEGIN # find and classify the complex conjugate transpose of a complex matrix #
# returns the conjugate transpose of m #
OP CONJUGATETRANSPOSE = ( [,]COMPL m )[,]COMPL:
BEGIN
[ 2 LWB m : 2 UPB m, 1 LWB m : 1 UPB m ]COMPL result;
FOR i FROM 1 LWB m TO 1 UPB m DO
FOR j FROM 2 LWB m TO 2 UPB m DO
result[ j, i ] := CONJ m[ i, j ]
OD
OD;
result
END # CONJUGATETRANSPOSE # ;
# returns TRUE if m is an identity matrix, FALSE otherwise #
OP ISIDENTITY = ( [,]COMPL m )BOOL:
IF 1 LWB m /= 2 LWB m OR 1 UPB m /= 2 UPB m THEN
# non-square matrix #
FALSE
ELSE
# the matrix is square #
# returns TRUE IF v - e is nearly 0, FALSE Otherwise #
PROC nearly equal = ( COMPL v, REAL e )BOOL: ABS re OF v - e < 1e-14 AND ABS im OF v < 1e-14;
BOOL result := TRUE;
FOR i FROM 1 LWB m TO 1 UPB m WHILE result DO
IF result := nearly equal( m[ i, i ], 1 ) THEN
# the diagonal element is 1 - test the non-diagonals #
FOR j FROM 1 LWB m TO 1 UPB m WHILE result DO
IF i /= j THEN result := nearly equal( m[ i, j ], 0 ) FI
OD
FI
OD;
result
FI # ISIDENTITY # ;
# returns m multiplied by n #
PRIO X = 7;
OP X = ( [,]COMPL m, n )[,]COMPL:
BEGIN
[ 1 : 1 UPB m, 1 : 2 UPB n ]COMPL r;
FOR i FROM 1 LWB m TO 1 UPB m DO
FOR j FROM 2 LWB n TO 2 UPB n DO
r[ i, j ] := 0;
FOR k TO 2 UPB n DO
r[ i, j ] +:= m[ i, k ] * n[ k, j ]
OD
OD
OD;
r
END # X # ;
# prints the complex matris m #
PROC show matrix = ( [,]COMPL m )VOID:
FOR i FROM 1 LWB m TO 1 UPB m DO
print( ( " " ) );
FOR j FROM 2 LWB m TO 2 UPB m DO
print( ( "( ", fixed( re OF m[ i, j ], -8, 4 )
, ", ", fixed( im OF m[ i, j ], -8, 4 )
, "i )"
)
)
OD;
print( ( newline ) )
OD # show matrix # ;
# display the matrix m, its conjugate transpose and whether it is Hermitian, Normal and Unitary #
PROC show = ( [,]COMPL m )VOID:
BEGIN
[,]COMPL c = CONJUGATETRANSPOSE m;
[,]COMPL cm = c X m;
[,]COMPL mc = m X c;
print( ( "Matrix:", newline ) );
show matrix( m );
print( ( "Conjugate Transpose:", newline ) );
show matrix( c );
BOOL is normal = cm = mc;
BOOL is unitary = IF NOT is normal THEN FALSE
ELSE ISIDENTITY mc
FI;
print( ( IF c = m THEN "" ELSE "not " FI, "Hermitian; "
, IF is normal THEN "" ELSE "not " FI, "Normal; "
, IF is unitary THEN "" ELSE "not " FI, "Unitary"
, newline
)
);
print( ( newline ) )
END # show # ;
# test some matrices for Hermitian, Normal and Unitary #
show( ( ( ( 3.0000 I 0.0000 ), ( 2.0000 I 1.0000 ) )
, ( ( 2.0000 I -1.0000 ), ( 1.0000 I 0.0000 ) )
)
);
show( ( ( ( 1.0000 I 0.0000 ), ( 1.0000 I 0.0000 ), ( 0.0000 I 0.0000 ) )
, ( ( 0.0000 I 0.0000 ), ( 1.0000 I 0.0000 ), ( 1.0000 I 0.0000 ) )
, ( ( 1.0000 I 0.0000 ), ( 0.0000 I 0.0000 ), ( 1.0000 I 0.0000 ) )
)
);
REAL rh = sqrt( 0.5 );
show( ( ( ( rh I 0.0000 ), ( rh I 0.0000 ), ( 0.0000 I 0.0000 ) )
, ( ( 0.0000 I rh ), ( 0.0000 I - rh ), ( 0.0000 I 0.0000 ) )
, ( ( 0.0000 I 0.0000 ), ( 0.0000 I 0.0000 ), ( 0.0000 I 1.0000 ) )
)
)
END |
http://rosettacode.org/wiki/Continued_fraction | Continued fraction | continued fraction
Mathworld
a
0
+
b
1
a
1
+
b
2
a
2
+
b
3
a
3
+
⋱
{\displaystyle a_{0}+{\cfrac {b_{1}}{a_{1}+{\cfrac {b_{2}}{a_{2}+{\cfrac {b_{3}}{a_{3}+\ddots }}}}}}}
The task is to write a program which generates such a number and prints a real representation of it. The code should be tested by calculating and printing the square root of 2, Napier's Constant, and Pi, using the following coefficients:
For the square root of 2, use
a
0
=
1
{\displaystyle a_{0}=1}
then
a
N
=
2
{\displaystyle a_{N}=2}
.
b
N
{\displaystyle b_{N}}
is always
1
{\displaystyle 1}
.
2
=
1
+
1
2
+
1
2
+
1
2
+
⋱
{\displaystyle {\sqrt {2}}=1+{\cfrac {1}{2+{\cfrac {1}{2+{\cfrac {1}{2+\ddots }}}}}}}
For Napier's Constant, use
a
0
=
2
{\displaystyle a_{0}=2}
, then
a
N
=
N
{\displaystyle a_{N}=N}
.
b
1
=
1
{\displaystyle b_{1}=1}
then
b
N
=
N
−
1
{\displaystyle b_{N}=N-1}
.
e
=
2
+
1
1
+
1
2
+
2
3
+
3
4
+
⋱
{\displaystyle e=2+{\cfrac {1}{1+{\cfrac {1}{2+{\cfrac {2}{3+{\cfrac {3}{4+\ddots }}}}}}}}}
For Pi, use
a
0
=
3
{\displaystyle a_{0}=3}
then
a
N
=
6
{\displaystyle a_{N}=6}
.
b
N
=
(
2
N
−
1
)
2
{\displaystyle b_{N}=(2N-1)^{2}}
.
π
=
3
+
1
6
+
9
6
+
25
6
+
⋱
{\displaystyle \pi =3+{\cfrac {1}{6+{\cfrac {9}{6+{\cfrac {25}{6+\ddots }}}}}}}
See also
Continued fraction/Arithmetic for tasks that do arithmetic over continued fractions.
| #J | J | cfrac=: +`% / NB. Evaluate a list as a continued fraction
sqrt2=: cfrac 1 1,200$2 1x
pi=:cfrac 3, , ,&6"0 *:<:+:>:i.100x
e=: cfrac 2 1, , ,~"0 >:i.100x
NB. translate from fraction to decimal string
NB. translated from factor
dec =: (-@:[ (}.,'.',{.) ":@:<.@:(* 10x&^)~)"0
100 10 100 dec sqrt2, pi, e
1.4142135623730950488016887242096980785696718753769480731766797379907324784621205551109457595775322165
3.1415924109
2.7182818284590452353602874713526624977572470936999595749669676277240766303535475945713821785251664274 |
http://rosettacode.org/wiki/Copy_a_string | Copy a string | This task is about copying a string.
Task
Where it is relevant, distinguish between copying the contents of a string
versus making an additional reference to an existing string.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Lingo | Lingo | str = "Hello world!"
str2 = str |
http://rosettacode.org/wiki/Copy_a_string | Copy a string | This task is about copying a string.
Task
Where it is relevant, distinguish between copying the contents of a string
versus making an additional reference to an existing string.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Lisaac | Lisaac | + scon : STRING_CONSTANT;
+ svar : STRING;
scon := "sample";
svar := STRING.create 20;
svar.copy scon;
svar.append "!\n";
svar.print; |
http://rosettacode.org/wiki/Constrained_random_points_on_a_circle | Constrained random points on a circle | Task
Generate 100 <x,y> coordinate pairs such that x and y are integers sampled from the uniform distribution with the condition that
10
≤
x
2
+
y
2
≤
15
{\displaystyle 10\leq {\sqrt {x^{2}+y^{2}}}\leq 15}
.
Then display/plot them. The outcome should be a "fuzzy" circle. The actual number of points plotted may be less than 100, given that some pairs may be generated more than once.
There are several possible approaches to accomplish this. Here are two possible algorithms.
1) Generate random pairs of integers and filter out those that don't satisfy this condition:
10
≤
x
2
+
y
2
≤
15
{\displaystyle 10\leq {\sqrt {x^{2}+y^{2}}}\leq 15}
.
2) Precalculate the set of all possible points (there are 404 of them) and select randomly from this set.
| #Elixir | Elixir | defmodule Random do
defp generate_point(0, _, _, set), do: set
defp generate_point(n, f, condition, set) do
point = {x,y} = {f.(), f.()}
if x*x + y*y in condition and not point in set,
do: generate_point(n-1, f, condition, MapSet.put(set, point)),
else: generate_point(n, f, condition, set)
end
def circle do
f = fn -> :rand.uniform(31) - 16 end
points = generate_point(100, f, 10*10..15*15, MapSet.new)
range = -15..15
for x <- range do
for y <- range do
IO.write if {x,y} in points, do: "x", else: " "
end
IO.puts ""
end
end
end
Random.circle |
http://rosettacode.org/wiki/Convex_hull | Convex hull | Find the points which form a convex hull from a set of arbitrary two dimensional points.
For example, given the points (16,3), (12,17), (0,6), (-4,-6), (16,6), (16,-7), (16,-3), (17,-4), (5,19), (19,-8), (3,16), (12,13), (3,-4), (17,5), (-3,15), (-3,-9), (0,11), (-9,-3), (-4,-2) and (12,10) the convex hull would be (-9,-3), (-3,-9), (19,-8), (17,5), (12,17), (5,19) and (-3,15).
See also
Convex Hull (youtube)
http://www.geeksforgeeks.org/convex-hull-set-2-graham-scan/
| #Icon | Icon | #
# Convex hulls by Andrew's monotone chain algorithm.
#
# For a description of the algorithm, see
# https://en.wikibooks.org/w/index.php?title=Algorithm_Implementation/Geometry/Convex_hull/Monotone_chain&stableid=40169
#
record PlanePoint (x, y)
######################################################################
#
# Merge sort adapted from the Object Icon IPL (public domain code).
#
# A merge sort implementation. This returns a sorted copy, leaving the
# original unchanged.
#
# :Parameters :
# : `l` - the list to sort
# : `cmp` - a comparator function
#
procedure mergesort (l, cmp)
return mergesort1 (l, cmp, 1, *l)
end
procedure mergesort1 (l, cmp, first, last)
local l1, l2, l3, m, v1
if last <= first then
return l[first:last + 1]
m := (first + last) / 2
l1 := mergesort1 (l, cmp, first, m)
l2 := mergesort1 (l, cmp, m + 1, last)
l3 := []
every v1 := !l1 do {
while cmp (v1, l2[1]) > 0 do
put (l3, get(l2))
put (l3, v1)
}
every put(l3, !l2)
return l3
end
######################################################################
procedure point_equals (p, q)
if p.x = q.x & p.y = q.y then return else fail
end
# Impose a total order on points, making it one that will work for
# Andrew's monotone chain algorithm. *)
procedure point_comes_before (p, q)
if (p.x < q.x) | (p.x = q.x & p.y < q.y) then return else fail
end
# Subtraction is really a vector or multivector operation.
procedure point_subtract (p, q)
return PlanePoint (p.x - q.x, p.y - q.y)
end
# Cross product is really a multivector operation.
procedure point_cross (p, q)
return (p.x * q.y) - (p.y * q.x)
end
procedure point_to_string (p)
return "(" || string (p.x) || " " || string (p.y) || ")"
end
######################################################################
# Comparison like C's strcmp(3).
procedure compare_points (p, q)
local cmp
if point_comes_before (p, q) then
cmp := -1
else if point_comes_before (q, p) then
cmp := 1
else
cmp := 0
return cmp
end
procedure sort_points (points)
# Non-destructive sort.
return mergesort (points, compare_points)
end
procedure delete_neighbor_dups (arr, equals)
local arr1, i
if *arr = 0 then {
arr1 := []
} else {
arr1 := [arr[1]]
i := 2
while i <= *arr do {
if not (equals (arr[i], arr1[-1])) then
put (arr1, arr[i])
i +:= 1
}
}
return arr1
end
procedure construct_lower_hull (pt)
local hull, i, j
hull := list (*pt)
hull[1] := pt[1]
hull[2] := pt[2]
j := 2
every i := 3 to *pt do {
while (j ~= 1 &
point_cross (point_subtract (hull[j], hull[j - 1]),
point_subtract (pt[i], hull[j - 1])) <= 0) do j -:= 1
j +:= 1
hull[j] := pt[i]
}
return hull[1 : j + 1]
end
procedure construct_upper_hull (pt)
local hull, i, j
hull := list (*pt)
hull[1] := pt[-1]
hull[2] := pt[-2]
j := 2
every i := 3 to *pt do {
while (j ~= 1 &
point_cross (point_subtract (hull[j], hull[j - 1]),
point_subtract (pt[-i], hull[j - 1])) <= 0) do j -:= 1
j +:= 1
hull[j] := pt[-i]
}
return hull[1 : j + 1]
end
procedure construct_hull (pt)
local lower_hull, upper_hull
lower_hull := construct_lower_hull (pt)
upper_hull := construct_upper_hull (pt)
return lower_hull[1 : -1] ||| upper_hull [1 : -1]
end
procedure find_convex_hull (points)
local pt, hull
if *points = 0 then {
hull := []
} else {
pt := delete_neighbor_dups (sort_points (points), point_equals)
if *pt <= 2 then {
hull := pt
} else {
hull := construct_hull (pt)
}
}
return hull
end
procedure main ()
local example_points, hull
example_points :=
[PlanePoint (16.0, 3.0),
PlanePoint (12.0, 17.0),
PlanePoint (0.0, 6.0),
PlanePoint (-4.0, -6.0),
PlanePoint (16.0, 6.0),
PlanePoint (16.0, -7.0),
PlanePoint (16.0, -3.0),
PlanePoint (17.0, -4.0),
PlanePoint (5.0, 19.0),
PlanePoint (19.0, -8.0),
PlanePoint (3.0, 16.0),
PlanePoint (12.0, 13.0),
PlanePoint (3.0, -4.0),
PlanePoint (17.0, 5.0),
PlanePoint (-3.0, 15.0),
PlanePoint (-3.0, -9.0),
PlanePoint (0.0, 11.0),
PlanePoint (-9.0, -3.0),
PlanePoint (-4.0, -2.0),
PlanePoint (12.0, 10.0)]
hull := find_convex_hull (example_points)
every write (point_to_string (!hull))
end
###################################################################### |
http://rosettacode.org/wiki/Convert_seconds_to_compound_duration | Convert seconds to compound duration | Task
Write a function or program which:
takes a positive integer representing a duration in seconds as input (e.g., 100), and
returns a string which shows the same duration decomposed into:
weeks,
days,
hours,
minutes, and
seconds.
This is detailed below (e.g., "2 hr, 59 sec").
Demonstrate that it passes the following three test-cases:
Test Cases
input number
output string
7259
2 hr, 59 sec
86400
1 d
6000000
9 wk, 6 d, 10 hr, 40 min
Details
The following five units should be used:
unit
suffix used in output
conversion
week
wk
1 week = 7 days
day
d
1 day = 24 hours
hour
hr
1 hour = 60 minutes
minute
min
1 minute = 60 seconds
second
sec
However, only include quantities with non-zero values in the output (e.g., return "1 d" and not "0 wk, 1 d, 0 hr, 0 min, 0 sec").
Give larger units precedence over smaller ones as much as possible (e.g., return 2 min, 10 sec and not 1 min, 70 sec or 130 sec)
Mimic the formatting shown in the test-cases (quantities sorted from largest unit to smallest and separated by comma+space; value and unit of each quantity separated by space).
| #JavaScript | JavaScript | (function () {
'use strict';
// angloDuration :: Int -> String
function angloDuration(intSeconds) {
return zip(
weekParts(intSeconds),
['wk', 'd', 'hr', 'min','sec']
)
.reduce(function (a, x) {
return a.concat(x[0] ? (
[(x[0].toString() + ' ' + x[1])]
) : []);
}, [])
.join(', ');
}
// weekParts :: Int -> [Int]
function weekParts(intSeconds) {
return [undefined, 7, 24, 60, 60]
.reduceRight(function (a, x) {
var intRest = a.remaining,
intMod = isNaN(x) ? intRest : intRest % x;
return {
remaining:(intRest - intMod) / (x || 1),
parts: [intMod].concat(a.parts)
};
}, {
remaining: intSeconds,
parts: []
})
.parts
}
// GENERIC ZIP
// zip :: [a] -> [b] -> [(a,b)]
function zip(xs, ys) {
return xs.length === ys.length ? (
xs.map(function (x, i) {
return [x, ys[i]];
})
) : undefined;
}
// TEST
return [7259, 86400, 6000000]
.map(function (intSeconds) {
return intSeconds.toString() +
' -> ' + angloDuration(intSeconds);
})
.join('\n');
})();
|
http://rosettacode.org/wiki/Conjugate_transpose | Conjugate transpose | Suppose that a matrix
M
{\displaystyle M}
contains complex numbers. Then the conjugate transpose of
M
{\displaystyle M}
is a matrix
M
H
{\displaystyle M^{H}}
containing the complex conjugates of the matrix transposition of
M
{\displaystyle M}
.
(
M
H
)
j
i
=
M
i
j
¯
{\displaystyle (M^{H})_{ji}={\overline {M_{ij}}}}
This means that row
j
{\displaystyle j}
, column
i
{\displaystyle i}
of the conjugate transpose equals the
complex conjugate of row
i
{\displaystyle i}
, column
j
{\displaystyle j}
of the original matrix.
In the next list,
M
{\displaystyle M}
must also be a square matrix.
A Hermitian matrix equals its own conjugate transpose:
M
H
=
M
{\displaystyle M^{H}=M}
.
A normal matrix is commutative in multiplication with its conjugate transpose:
M
H
M
=
M
M
H
{\displaystyle M^{H}M=MM^{H}}
.
A unitary matrix has its inverse equal to its conjugate transpose:
M
H
=
M
−
1
{\displaystyle M^{H}=M^{-1}}
.
This is true iff
M
H
M
=
I
n
{\displaystyle M^{H}M=I_{n}}
and iff
M
M
H
=
I
n
{\displaystyle MM^{H}=I_{n}}
, where
I
n
{\displaystyle I_{n}}
is the identity matrix.
Task
Given some matrix of complex numbers, find its conjugate transpose.
Also determine if the matrix is a:
Hermitian matrix,
normal matrix, or
unitary matrix.
See also
MathWorld entry: conjugate transpose
MathWorld entry: Hermitian matrix
MathWorld entry: normal matrix
MathWorld entry: unitary matrix
| #C | C | /* Uses C99 specified complex.h, complex datatype has to be defined and operation provided if used on non-C99 compilers */
#include<stdlib.h>
#include<stdio.h>
#include<complex.h>
typedef struct
{
int rows, cols;
complex **z;
} matrix;
matrix
transpose (matrix a)
{
int i, j;
matrix b;
b.rows = a.cols;
b.cols = a.rows;
b.z = malloc (b.rows * sizeof (complex *));
for (i = 0; i < b.rows; i++)
{
b.z[i] = malloc (b.cols * sizeof (complex));
for (j = 0; j < b.cols; j++)
{
b.z[i][j] = conj (a.z[j][i]);
}
}
return b;
}
int
isHermitian (matrix a)
{
int i, j;
matrix b = transpose (a);
if (b.rows == a.rows && b.cols == a.cols)
{
for (i = 0; i < b.rows; i++)
{
for (j = 0; j < b.cols; j++)
{
if (b.z[i][j] != a.z[i][j])
return 0;
}
}
}
else
return 0;
return 1;
}
matrix
multiply (matrix a, matrix b)
{
matrix c;
int i, j;
if (a.cols == b.rows)
{
c.rows = a.rows;
c.cols = b.cols;
c.z = malloc (c.rows * (sizeof (complex *)));
for (i = 0; i < c.rows; i++)
{
c.z[i] = malloc (c.cols * sizeof (complex));
c.z[i][j] = 0 + 0 * I;
for (j = 0; j < b.cols; j++)
{
c.z[i][j] += a.z[i][j] * b.z[j][i];
}
}
}
return c;
}
int
isNormal (matrix a)
{
int i, j;
matrix a_ah, ah_a;
if (a.rows != a.cols)
return 0;
a_ah = multiply (a, transpose (a));
ah_a = multiply (transpose (a), a);
for (i = 0; i < a.rows; i++)
{
for (j = 0; j < a.cols; j++)
{
if (a_ah.z[i][j] != ah_a.z[i][j])
return 0;
}
}
return 1;
}
int
isUnitary (matrix a)
{
matrix b;
int i, j;
if (isNormal (a) == 1)
{
b = multiply (a, transpose(a));
for (i = 0; i < b.rows; i++)
{
for (j = 0; j < b.cols; j++)
{
if ((i == j && b.z[i][j] != 1) || (i != j && b.z[i][j] != 0))
return 0;
}
}
return 1;
}
return 0;
}
int
main ()
{
complex z = 3 + 4 * I;
matrix a, aT;
int i, j;
printf ("Enter rows and columns :");
scanf ("%d%d", &a.rows, &a.cols);
a.z = malloc (a.rows * sizeof (complex *));
printf ("Randomly Generated Complex Matrix A is : ");
for (i = 0; i < a.rows; i++)
{
printf ("\n");
a.z[i] = malloc (a.cols * sizeof (complex));
for (j = 0; j < a.cols; j++)
{
a.z[i][j] = rand () % 10 + rand () % 10 * I;
printf ("\t%f + %fi", creal (a.z[i][j]), cimag (a.z[i][j]));
}
}
aT = transpose (a);
printf ("\n\nTranspose of Complex Matrix A is : ");
for (i = 0; i < aT.rows; i++)
{
printf ("\n");
aT.z[i] = malloc (aT.cols * sizeof (complex));
for (j = 0; j < aT.cols; j++)
{
aT.z[i][j] = rand () % 10 + rand () % 10 * I;
printf ("\t%f + %fi", creal (aT.z[i][j]), cimag (aT.z[i][j]));
}
}
printf ("\n\nComplex Matrix A %s hermitian",
isHermitian (a) == 1 ? "is" : "is not");
printf ("\n\nComplex Matrix A %s unitary",
isUnitary (a) == 1 ? "is" : "is not");
printf ("\n\nComplex Matrix A %s normal",
isNormal (a) == 1 ? "is" : "is not");
return 0;
} |
http://rosettacode.org/wiki/Compound_data_type | Compound data type |
Data Structure
This illustrates a data structure, a means of storing data within a program.
You may see other such structures in the Data Structures category.
Task
Create a compound data type:
Point(x,y)
A compound data type is one that holds multiple independent values.
Related task
Enumeration
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
| #11l | 11l | T Point
Int x, y
F (x, y)
.x = x
.y = y |
http://rosettacode.org/wiki/Continued_fraction | Continued fraction | continued fraction
Mathworld
a
0
+
b
1
a
1
+
b
2
a
2
+
b
3
a
3
+
⋱
{\displaystyle a_{0}+{\cfrac {b_{1}}{a_{1}+{\cfrac {b_{2}}{a_{2}+{\cfrac {b_{3}}{a_{3}+\ddots }}}}}}}
The task is to write a program which generates such a number and prints a real representation of it. The code should be tested by calculating and printing the square root of 2, Napier's Constant, and Pi, using the following coefficients:
For the square root of 2, use
a
0
=
1
{\displaystyle a_{0}=1}
then
a
N
=
2
{\displaystyle a_{N}=2}
.
b
N
{\displaystyle b_{N}}
is always
1
{\displaystyle 1}
.
2
=
1
+
1
2
+
1
2
+
1
2
+
⋱
{\displaystyle {\sqrt {2}}=1+{\cfrac {1}{2+{\cfrac {1}{2+{\cfrac {1}{2+\ddots }}}}}}}
For Napier's Constant, use
a
0
=
2
{\displaystyle a_{0}=2}
, then
a
N
=
N
{\displaystyle a_{N}=N}
.
b
1
=
1
{\displaystyle b_{1}=1}
then
b
N
=
N
−
1
{\displaystyle b_{N}=N-1}
.
e
=
2
+
1
1
+
1
2
+
2
3
+
3
4
+
⋱
{\displaystyle e=2+{\cfrac {1}{1+{\cfrac {1}{2+{\cfrac {2}{3+{\cfrac {3}{4+\ddots }}}}}}}}}
For Pi, use
a
0
=
3
{\displaystyle a_{0}=3}
then
a
N
=
6
{\displaystyle a_{N}=6}
.
b
N
=
(
2
N
−
1
)
2
{\displaystyle b_{N}=(2N-1)^{2}}
.
π
=
3
+
1
6
+
9
6
+
25
6
+
⋱
{\displaystyle \pi =3+{\cfrac {1}{6+{\cfrac {9}{6+{\cfrac {25}{6+\ddots }}}}}}}
See also
Continued fraction/Arithmetic for tasks that do arithmetic over continued fractions.
| #Java | Java | import static java.lang.Math.pow;
import java.util.*;
import java.util.function.Function;
public class Test {
static double calc(Function<Integer, Integer[]> f, int n) {
double temp = 0;
for (int ni = n; ni >= 1; ni--) {
Integer[] p = f.apply(ni);
temp = p[1] / (double) (p[0] + temp);
}
return f.apply(0)[0] + temp;
}
public static void main(String[] args) {
List<Function<Integer, Integer[]>> fList = new ArrayList<>();
fList.add(n -> new Integer[]{n > 0 ? 2 : 1, 1});
fList.add(n -> new Integer[]{n > 0 ? n : 2, n > 1 ? (n - 1) : 1});
fList.add(n -> new Integer[]{n > 0 ? 6 : 3, (int) pow(2 * n - 1, 2)});
for (Function<Integer, Integer[]> f : fList)
System.out.println(calc(f, 200));
}
} |
http://rosettacode.org/wiki/Copy_a_string | Copy a string | This task is about copying a string.
Task
Where it is relevant, distinguish between copying the contents of a string
versus making an additional reference to an existing string.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Little | Little | string a = "A string";
string b = a;
a =~ s/$/\./;
puts(a);
puts(b); |
http://rosettacode.org/wiki/Copy_a_string | Copy a string | This task is about copying a string.
Task
Where it is relevant, distinguish between copying the contents of a string
versus making an additional reference to an existing string.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #LiveCode | LiveCode | put "foo" into bar
put bar into baz
answer bar && baz |
http://rosettacode.org/wiki/Constrained_random_points_on_a_circle | Constrained random points on a circle | Task
Generate 100 <x,y> coordinate pairs such that x and y are integers sampled from the uniform distribution with the condition that
10
≤
x
2
+
y
2
≤
15
{\displaystyle 10\leq {\sqrt {x^{2}+y^{2}}}\leq 15}
.
Then display/plot them. The outcome should be a "fuzzy" circle. The actual number of points plotted may be less than 100, given that some pairs may be generated more than once.
There are several possible approaches to accomplish this. Here are two possible algorithms.
1) Generate random pairs of integers and filter out those that don't satisfy this condition:
10
≤
x
2
+
y
2
≤
15
{\displaystyle 10\leq {\sqrt {x^{2}+y^{2}}}\leq 15}
.
2) Precalculate the set of all possible points (there are 404 of them) and select randomly from this set.
| #Euphoria | Euphoria | include std/console.e
sequence validpoints = {}
sequence discardedpoints = {}
sequence rand100points = {}
atom coordresult
integer randindex
--scan for all possible values. store discarded ones in another sequence, for extra reference.
for y = -15 to 15 do
for x = -15 to 15 do
coordresult = sqrt( x * x + y * y )
if coordresult >= 10 and coordresult <= 15 then --if it would fall in the ring area
validpoints &= {{x, y, coordresult}} --concatenate (add to the end) the coordinate pair x, y and the
-- result into a subsequence of sequence validpoints
else
discardedpoints &= {{x, y, coordresult}} --else put it in the discarded sequence
end if
end for
end for
for i = 1 to 100 label "oneofhundred" do --make 100 random coordinate pairs
randindex = rand(length(validpoints) ) --random value from 1 to the number of 3 value subsequences in validpoints (the data)
if length(rand100points) = 0 then --if rand100points sequence is empty, add the first subsequence to it.
rand100points &= {validpoints[randindex]}
else --if it isn't empty, then..
for j = 1 to length(rand100points) do --loop through each "data chunk" in rand100points
if equal(validpoints[randindex], rand100points[j]) = 1 then --if any are the same as the randomly chosen chunk in
retry "oneofhundred" -- validpoints, then retry from one line below the "oneofhundred" loop without incrementing i.
end if --the continue keyword would increment i instead.
end for
rand100points &= {validpoints[randindex]} --length of rand100points isnt 0 and no data chunks match ones that the program
--already picked before, so add this subsequence chunk to rand100points.
end if
end for
for i = 1 to 32 do --32 lines
printf(1,"\n")
for j = 1 to 32 label "xscan" do --32 characters on each line
for k = 1 to length(rand100points) do --for every subsequence in this
if rand100points[k][1]+16 = j and rand100points[k][2]+16 = i then --if the x and y coordinates in the picked points
printf(1, 178) --(adjusted to minimum of 1,1) are at the same place as in the console output grid
continue "xscan" --print a funny character and continue to the next "xscan"
end if
end for
printf(1, 176) --if no picked points were there, print another funny character to represent a blank space
end for
end for
printf(1, "\nNumber of valid coordinate pairs %d :", length(validpoints) )
printf(1, "\nNumber of discarded coordinate pairs : %d", length(discardedpoints) )
printf(1, "\nNumber of randomly picked coordinate pairs : %d\n", length(rand100points) )
any_key() |
http://rosettacode.org/wiki/Convex_hull | Convex hull | Find the points which form a convex hull from a set of arbitrary two dimensional points.
For example, given the points (16,3), (12,17), (0,6), (-4,-6), (16,6), (16,-7), (16,-3), (17,-4), (5,19), (19,-8), (3,16), (12,13), (3,-4), (17,5), (-3,15), (-3,-9), (0,11), (-9,-3), (-4,-2) and (12,10) the convex hull would be (-9,-3), (-3,-9), (19,-8), (17,5), (12,17), (5,19) and (-3,15).
See also
Convex Hull (youtube)
http://www.geeksforgeeks.org/convex-hull-set-2-graham-scan/
| #J | J | counterclockwise =: ({. , }. /: 12 o. }. - {.) @ /:~
crossproduct =: 11 o. [: (* +)/ }. - {.
removeinner =: #~ (1 , (0 > 3 crossproduct\ ]) , 1:)
hull =: [: removeinner^:_ counterclockwise |
http://rosettacode.org/wiki/Convert_seconds_to_compound_duration | Convert seconds to compound duration | Task
Write a function or program which:
takes a positive integer representing a duration in seconds as input (e.g., 100), and
returns a string which shows the same duration decomposed into:
weeks,
days,
hours,
minutes, and
seconds.
This is detailed below (e.g., "2 hr, 59 sec").
Demonstrate that it passes the following three test-cases:
Test Cases
input number
output string
7259
2 hr, 59 sec
86400
1 d
6000000
9 wk, 6 d, 10 hr, 40 min
Details
The following five units should be used:
unit
suffix used in output
conversion
week
wk
1 week = 7 days
day
d
1 day = 24 hours
hour
hr
1 hour = 60 minutes
minute
min
1 minute = 60 seconds
second
sec
However, only include quantities with non-zero values in the output (e.g., return "1 d" and not "0 wk, 1 d, 0 hr, 0 min, 0 sec").
Give larger units precedence over smaller ones as much as possible (e.g., return 2 min, 10 sec and not 1 min, 70 sec or 130 sec)
Mimic the formatting shown in the test-cases (quantities sorted from largest unit to smallest and separated by comma+space; value and unit of each quantity separated by space).
| #jq | jq | def seconds_to_time_string:
def nonzero(text): floor | if . > 0 then "\(.) \(text)" else empty end;
if . == 0 then "0 sec"
else
[(./60/60/24/7 | nonzero("wk")),
(./60/60/24 % 7 | nonzero("d")),
(./60/60 % 24 | nonzero("hr")),
(./60 % 60 | nonzero("min")),
(. % 60 | nonzero("sec"))]
| join(", ")
end; |
http://rosettacode.org/wiki/Convert_seconds_to_compound_duration | Convert seconds to compound duration | Task
Write a function or program which:
takes a positive integer representing a duration in seconds as input (e.g., 100), and
returns a string which shows the same duration decomposed into:
weeks,
days,
hours,
minutes, and
seconds.
This is detailed below (e.g., "2 hr, 59 sec").
Demonstrate that it passes the following three test-cases:
Test Cases
input number
output string
7259
2 hr, 59 sec
86400
1 d
6000000
9 wk, 6 d, 10 hr, 40 min
Details
The following five units should be used:
unit
suffix used in output
conversion
week
wk
1 week = 7 days
day
d
1 day = 24 hours
hour
hr
1 hour = 60 minutes
minute
min
1 minute = 60 seconds
second
sec
However, only include quantities with non-zero values in the output (e.g., return "1 d" and not "0 wk, 1 d, 0 hr, 0 min, 0 sec").
Give larger units precedence over smaller ones as much as possible (e.g., return 2 min, 10 sec and not 1 min, 70 sec or 130 sec)
Mimic the formatting shown in the test-cases (quantities sorted from largest unit to smallest and separated by comma+space; value and unit of each quantity separated by space).
| #Julia | Julia | # 1.x
function duration(sec::Integer)::String
t = Array{Int}([])
for dm in (60, 60, 24, 7)
sec, m = divrem(sec, dm)
pushfirst!(t, m)
end
pushfirst!(t, sec)
return join(["$num$unit" for (num, unit) in zip(t, ["w", "d", "h", "m", "s"]) if num > 0], ", ")
end
@show duration(7259)
@show duration(86400)
@show duration(6000000)
|
http://rosettacode.org/wiki/Conjugate_transpose | Conjugate transpose | Suppose that a matrix
M
{\displaystyle M}
contains complex numbers. Then the conjugate transpose of
M
{\displaystyle M}
is a matrix
M
H
{\displaystyle M^{H}}
containing the complex conjugates of the matrix transposition of
M
{\displaystyle M}
.
(
M
H
)
j
i
=
M
i
j
¯
{\displaystyle (M^{H})_{ji}={\overline {M_{ij}}}}
This means that row
j
{\displaystyle j}
, column
i
{\displaystyle i}
of the conjugate transpose equals the
complex conjugate of row
i
{\displaystyle i}
, column
j
{\displaystyle j}
of the original matrix.
In the next list,
M
{\displaystyle M}
must also be a square matrix.
A Hermitian matrix equals its own conjugate transpose:
M
H
=
M
{\displaystyle M^{H}=M}
.
A normal matrix is commutative in multiplication with its conjugate transpose:
M
H
M
=
M
M
H
{\displaystyle M^{H}M=MM^{H}}
.
A unitary matrix has its inverse equal to its conjugate transpose:
M
H
=
M
−
1
{\displaystyle M^{H}=M^{-1}}
.
This is true iff
M
H
M
=
I
n
{\displaystyle M^{H}M=I_{n}}
and iff
M
M
H
=
I
n
{\displaystyle MM^{H}=I_{n}}
, where
I
n
{\displaystyle I_{n}}
is the identity matrix.
Task
Given some matrix of complex numbers, find its conjugate transpose.
Also determine if the matrix is a:
Hermitian matrix,
normal matrix, or
unitary matrix.
See also
MathWorld entry: conjugate transpose
MathWorld entry: Hermitian matrix
MathWorld entry: normal matrix
MathWorld entry: unitary matrix
| #C.2B.2B | C++ | #include <cassert>
#include <cmath>
#include <complex>
#include <iomanip>
#include <iostream>
#include <sstream>
#include <vector>
template <typename scalar_type> class complex_matrix {
public:
using element_type = std::complex<scalar_type>;
complex_matrix(size_t rows, size_t columns)
: rows_(rows), columns_(columns), elements_(rows * columns) {}
complex_matrix(size_t rows, size_t columns, element_type value)
: rows_(rows), columns_(columns), elements_(rows * columns, value) {}
complex_matrix(size_t rows, size_t columns,
const std::initializer_list<std::initializer_list<element_type>>& values)
: rows_(rows), columns_(columns), elements_(rows * columns) {
assert(values.size() <= rows_);
size_t i = 0;
for (const auto& row : values) {
assert(row.size() <= columns_);
std::copy(begin(row), end(row), &elements_[i]);
i += columns_;
}
}
size_t rows() const { return rows_; }
size_t columns() const { return columns_; }
const element_type& operator()(size_t row, size_t column) const {
assert(row < rows_);
assert(column < columns_);
return elements_[row * columns_ + column];
}
element_type& operator()(size_t row, size_t column) {
assert(row < rows_);
assert(column < columns_);
return elements_[row * columns_ + column];
}
friend bool operator==(const complex_matrix& a, const complex_matrix& b) {
return a.rows_ == b.rows_ && a.columns_ == b.columns_ &&
a.elements_ == b.elements_;
}
private:
size_t rows_;
size_t columns_;
std::vector<element_type> elements_;
};
template <typename scalar_type>
complex_matrix<scalar_type> product(const complex_matrix<scalar_type>& a,
const complex_matrix<scalar_type>& b) {
assert(a.columns() == b.rows());
size_t arows = a.rows();
size_t bcolumns = b.columns();
size_t n = a.columns();
complex_matrix<scalar_type> c(arows, bcolumns);
for (size_t i = 0; i < arows; ++i) {
for (size_t j = 0; j < n; ++j) {
for (size_t k = 0; k < bcolumns; ++k)
c(i, k) += a(i, j) * b(j, k);
}
}
return c;
}
template <typename scalar_type>
complex_matrix<scalar_type>
conjugate_transpose(const complex_matrix<scalar_type>& a) {
size_t rows = a.rows(), columns = a.columns();
complex_matrix<scalar_type> b(columns, rows);
for (size_t i = 0; i < columns; i++) {
for (size_t j = 0; j < rows; j++) {
b(i, j) = std::conj(a(j, i));
}
}
return b;
}
template <typename scalar_type>
std::string to_string(const std::complex<scalar_type>& c) {
std::ostringstream out;
const int precision = 6;
out << std::fixed << std::setprecision(precision);
out << std::setw(precision + 3) << c.real();
if (c.imag() > 0)
out << " + " << std::setw(precision + 2) << c.imag() << 'i';
else if (c.imag() == 0)
out << " + " << std::setw(precision + 2) << 0.0 << 'i';
else
out << " - " << std::setw(precision + 2) << -c.imag() << 'i';
return out.str();
}
template <typename scalar_type>
void print(std::ostream& out, const complex_matrix<scalar_type>& a) {
size_t rows = a.rows(), columns = a.columns();
for (size_t row = 0; row < rows; ++row) {
for (size_t column = 0; column < columns; ++column) {
if (column > 0)
out << ' ';
out << to_string(a(row, column));
}
out << '\n';
}
}
template <typename scalar_type>
bool is_hermitian_matrix(const complex_matrix<scalar_type>& matrix) {
if (matrix.rows() != matrix.columns())
return false;
return matrix == conjugate_transpose(matrix);
}
template <typename scalar_type>
bool is_normal_matrix(const complex_matrix<scalar_type>& matrix) {
if (matrix.rows() != matrix.columns())
return false;
auto c = conjugate_transpose(matrix);
return product(c, matrix) == product(matrix, c);
}
bool is_equal(const std::complex<double>& a, double b) {
constexpr double e = 1e-15;
return std::abs(a.imag()) < e && std::abs(a.real() - b) < e;
}
template <typename scalar_type>
bool is_identity_matrix(const complex_matrix<scalar_type>& matrix) {
if (matrix.rows() != matrix.columns())
return false;
size_t rows = matrix.rows();
for (size_t i = 0; i < rows; ++i) {
for (size_t j = 0; j < rows; ++j) {
if (!is_equal(matrix(i, j), scalar_type(i == j ? 1 : 0)))
return false;
}
}
return true;
}
template <typename scalar_type>
bool is_unitary_matrix(const complex_matrix<scalar_type>& matrix) {
if (matrix.rows() != matrix.columns())
return false;
auto c = conjugate_transpose(matrix);
auto p = product(c, matrix);
return is_identity_matrix(p) && p == product(matrix, c);
}
template <typename scalar_type>
void test(const complex_matrix<scalar_type>& matrix) {
std::cout << "Matrix:\n";
print(std::cout, matrix);
std::cout << "Conjugate transpose:\n";
print(std::cout, conjugate_transpose(matrix));
std::cout << std::boolalpha;
std::cout << "Hermitian: " << is_hermitian_matrix(matrix) << '\n';
std::cout << "Normal: " << is_normal_matrix(matrix) << '\n';
std::cout << "Unitary: " << is_unitary_matrix(matrix) << '\n';
}
int main() {
using matrix = complex_matrix<double>;
matrix matrix1(3, 3, {{{2, 0}, {2, 1}, {4, 0}},
{{2, -1}, {3, 0}, {0, 1}},
{{4, 0}, {0, -1}, {1, 0}}});
double n = std::sqrt(0.5);
matrix matrix2(3, 3, {{{n, 0}, {n, 0}, {0, 0}},
{{0, -n}, {0, n}, {0, 0}},
{{0, 0}, {0, 0}, {0, 1}}});
matrix matrix3(3, 3, {{{2, 2}, {3, 1}, {-3, 5}},
{{2, -1}, {4, 1}, {0, 0}},
{{7, -5}, {1, -4}, {1, 0}}});
test(matrix1);
std::cout << '\n';
test(matrix2);
std::cout << '\n';
test(matrix3);
return 0;
} |
http://rosettacode.org/wiki/Compound_data_type | Compound data type |
Data Structure
This illustrates a data structure, a means of storing data within a program.
You may see other such structures in the Data Structures category.
Task
Create a compound data type:
Point(x,y)
A compound data type is one that holds multiple independent values.
Related task
Enumeration
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
| #ACL2 | ACL2 | (defstructure point
(x (:assert (rationalp x)))
(y (:assert (rationalp y))))
(assign p1 (make-point :x 1 :y 2))
(point-x (@ p1)) ; Access the x value of the point
(assign p1 (update-point (@ p1) :x 3)) ; Update the x value
(point-x (@ p1))
(point-p (@ p1)) ; Recognizer for points |
http://rosettacode.org/wiki/Continued_fraction | Continued fraction | continued fraction
Mathworld
a
0
+
b
1
a
1
+
b
2
a
2
+
b
3
a
3
+
⋱
{\displaystyle a_{0}+{\cfrac {b_{1}}{a_{1}+{\cfrac {b_{2}}{a_{2}+{\cfrac {b_{3}}{a_{3}+\ddots }}}}}}}
The task is to write a program which generates such a number and prints a real representation of it. The code should be tested by calculating and printing the square root of 2, Napier's Constant, and Pi, using the following coefficients:
For the square root of 2, use
a
0
=
1
{\displaystyle a_{0}=1}
then
a
N
=
2
{\displaystyle a_{N}=2}
.
b
N
{\displaystyle b_{N}}
is always
1
{\displaystyle 1}
.
2
=
1
+
1
2
+
1
2
+
1
2
+
⋱
{\displaystyle {\sqrt {2}}=1+{\cfrac {1}{2+{\cfrac {1}{2+{\cfrac {1}{2+\ddots }}}}}}}
For Napier's Constant, use
a
0
=
2
{\displaystyle a_{0}=2}
, then
a
N
=
N
{\displaystyle a_{N}=N}
.
b
1
=
1
{\displaystyle b_{1}=1}
then
b
N
=
N
−
1
{\displaystyle b_{N}=N-1}
.
e
=
2
+
1
1
+
1
2
+
2
3
+
3
4
+
⋱
{\displaystyle e=2+{\cfrac {1}{1+{\cfrac {1}{2+{\cfrac {2}{3+{\cfrac {3}{4+\ddots }}}}}}}}}
For Pi, use
a
0
=
3
{\displaystyle a_{0}=3}
then
a
N
=
6
{\displaystyle a_{N}=6}
.
b
N
=
(
2
N
−
1
)
2
{\displaystyle b_{N}=(2N-1)^{2}}
.
π
=
3
+
1
6
+
9
6
+
25
6
+
⋱
{\displaystyle \pi =3+{\cfrac {1}{6+{\cfrac {9}{6+{\cfrac {25}{6+\ddots }}}}}}}
See also
Continued fraction/Arithmetic for tasks that do arithmetic over continued fractions.
| #jq | jq |
# "first" is the first triple,
# e.g. [1,a,b]; count specifies the number of terms to use.
def continued_fraction( first; next; count ):
# input: [i, a, b]]
def cf:
if .[0] == count then 0
else next as $ab
| .[1] + (.[2] / ($ab | cf))
end ;
first | cf;
# "first" and "next" are as above;
# if delta is 0 then continue until there is no detectable change.
def continued_fraction_delta(first; next; delta):
def abs: if . < 0 then -. else . end;
def cf:
# state: [n, prev]
.[0] as $n | .[1] as $prev
| continued_fraction(first; next; $n+1) as $this
| if $prev == null then [$n+1, $this] | cf
elif delta <= 0 and ($prev == $this) then $this
elif (($prev - $this)|abs) <= delta then $this
else [$n+1, $this] | cf
end;
[2,null] | cf;
|
http://rosettacode.org/wiki/Continued_fraction | Continued fraction | continued fraction
Mathworld
a
0
+
b
1
a
1
+
b
2
a
2
+
b
3
a
3
+
⋱
{\displaystyle a_{0}+{\cfrac {b_{1}}{a_{1}+{\cfrac {b_{2}}{a_{2}+{\cfrac {b_{3}}{a_{3}+\ddots }}}}}}}
The task is to write a program which generates such a number and prints a real representation of it. The code should be tested by calculating and printing the square root of 2, Napier's Constant, and Pi, using the following coefficients:
For the square root of 2, use
a
0
=
1
{\displaystyle a_{0}=1}
then
a
N
=
2
{\displaystyle a_{N}=2}
.
b
N
{\displaystyle b_{N}}
is always
1
{\displaystyle 1}
.
2
=
1
+
1
2
+
1
2
+
1
2
+
⋱
{\displaystyle {\sqrt {2}}=1+{\cfrac {1}{2+{\cfrac {1}{2+{\cfrac {1}{2+\ddots }}}}}}}
For Napier's Constant, use
a
0
=
2
{\displaystyle a_{0}=2}
, then
a
N
=
N
{\displaystyle a_{N}=N}
.
b
1
=
1
{\displaystyle b_{1}=1}
then
b
N
=
N
−
1
{\displaystyle b_{N}=N-1}
.
e
=
2
+
1
1
+
1
2
+
2
3
+
3
4
+
⋱
{\displaystyle e=2+{\cfrac {1}{1+{\cfrac {1}{2+{\cfrac {2}{3+{\cfrac {3}{4+\ddots }}}}}}}}}
For Pi, use
a
0
=
3
{\displaystyle a_{0}=3}
then
a
N
=
6
{\displaystyle a_{N}=6}
.
b
N
=
(
2
N
−
1
)
2
{\displaystyle b_{N}=(2N-1)^{2}}
.
π
=
3
+
1
6
+
9
6
+
25
6
+
⋱
{\displaystyle \pi =3+{\cfrac {1}{6+{\cfrac {9}{6+{\cfrac {25}{6+\ddots }}}}}}}
See also
Continued fraction/Arithmetic for tasks that do arithmetic over continued fractions.
| #Julia | Julia | function _sqrt(a::Bool, n)
if a
return n > 0 ? 2.0 : 1.0
else
return 1.0
end
end
function _napier(a::Bool, n)
if a
return n > 0 ? Float64(n) : 2.0
else
return n > 1 ? n - 1.0 : 1.0
end
end
function _pi(a::Bool, n)
if a
return n > 0 ? 6.0 : 3.0
else
return (2.0 * n - 1.0) ^ 2.0 # exponentiation operator
end
end
function calc(f::Function, expansions::Integer)
a, b = true, false
r = 0.0
for i in expansions:-1:1
r = f(b, i) / (f(a, i) + r)
end
return f(a, 0) + r
end
for (v, f) in (("√2", _sqrt), ("e", _napier), ("π", _pi))
@printf("%3s = %f\n", v, calc(f, 1000))
end |
http://rosettacode.org/wiki/Copy_a_string | Copy a string | This task is about copying a string.
Task
Where it is relevant, distinguish between copying the contents of a string
versus making an additional reference to an existing string.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Logo | Logo | make "a "foo
make "b "foo
print .eq :a :b ; true, identical symbols are reused
make "c :a
print .eq :a :c ; true, copy a reference
make "c word :b "|| ; force a copy of the contents of a word by appending the empty word
print equal? :b :c ; true
print .eq :b :c ; false |
http://rosettacode.org/wiki/Copy_a_string | Copy a string | This task is about copying a string.
Task
Where it is relevant, distinguish between copying the contents of a string
versus making an additional reference to an existing string.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Lua | Lua |
a = "string"
b = a
print(a == b) -->true
print(b) -->string |
http://rosettacode.org/wiki/Constrained_random_points_on_a_circle | Constrained random points on a circle | Task
Generate 100 <x,y> coordinate pairs such that x and y are integers sampled from the uniform distribution with the condition that
10
≤
x
2
+
y
2
≤
15
{\displaystyle 10\leq {\sqrt {x^{2}+y^{2}}}\leq 15}
.
Then display/plot them. The outcome should be a "fuzzy" circle. The actual number of points plotted may be less than 100, given that some pairs may be generated more than once.
There are several possible approaches to accomplish this. Here are two possible algorithms.
1) Generate random pairs of integers and filter out those that don't satisfy this condition:
10
≤
x
2
+
y
2
≤
15
{\displaystyle 10\leq {\sqrt {x^{2}+y^{2}}}\leq 15}
.
2) Precalculate the set of all possible points (there are 404 of them) and select randomly from this set.
| #F.23 | F# | module CirclePoints =
let main args =
let rnd = new System.Random()
let rand size = rnd.Next(size) - size/2
let size = 30
let gen n =
let rec f (x,y) =
let t = (int (sqrt (float (x*x + y*y)) ))
if 10 <= t && t <= 15 then (x,y) else f (rand size, rand size)
f (rand size, rand size)
let plot = Array.init 100 (fun n -> gen n)
for row in 0 .. size-1 do
let chars = Array.create (size+1) ' '
Array.choose (fun (x,y) -> if y = (row-size/2) then Some(x) else None) plot
|> Array.iter (fun x -> chars.[x+size/2] <- 'o')
printfn "%s" (new string(chars))
0
#if INTERACTIVE
CirclePoints.main fsi.CommandLineArgs
#else
[<EntryPoint>]
let main args = CirclePoints.main args
#endif |
http://rosettacode.org/wiki/Convex_hull | Convex hull | Find the points which form a convex hull from a set of arbitrary two dimensional points.
For example, given the points (16,3), (12,17), (0,6), (-4,-6), (16,6), (16,-7), (16,-3), (17,-4), (5,19), (19,-8), (3,16), (12,13), (3,-4), (17,5), (-3,15), (-3,-9), (0,11), (-9,-3), (-4,-2) and (12,10) the convex hull would be (-9,-3), (-3,-9), (19,-8), (17,5), (12,17), (5,19) and (-3,15).
See also
Convex Hull (youtube)
http://www.geeksforgeeks.org/convex-hull-set-2-graham-scan/
| #Java | Java | import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import static java.util.Collections.emptyList;
public class ConvexHull {
private static class Point implements Comparable<Point> {
private int x, y;
public Point(int x, int y) {
this.x = x;
this.y = y;
}
@Override
public int compareTo(Point o) {
return Integer.compare(x, o.x);
}
@Override
public String toString() {
return String.format("(%d, %d)", x, y);
}
}
private static List<Point> convexHull(List<Point> p) {
if (p.isEmpty()) return emptyList();
p.sort(Point::compareTo);
List<Point> h = new ArrayList<>();
// lower hull
for (Point pt : p) {
while (h.size() >= 2 && !ccw(h.get(h.size() - 2), h.get(h.size() - 1), pt)) {
h.remove(h.size() - 1);
}
h.add(pt);
}
// upper hull
int t = h.size() + 1;
for (int i = p.size() - 1; i >= 0; i--) {
Point pt = p.get(i);
while (h.size() >= t && !ccw(h.get(h.size() - 2), h.get(h.size() - 1), pt)) {
h.remove(h.size() - 1);
}
h.add(pt);
}
h.remove(h.size() - 1);
return h;
}
// ccw returns true if the three points make a counter-clockwise turn
private static boolean ccw(Point a, Point b, Point c) {
return ((b.x - a.x) * (c.y - a.y)) > ((b.y - a.y) * (c.x - a.x));
}
public static void main(String[] args) {
List<Point> points = Arrays.asList(new Point(16, 3),
new Point(12, 17),
new Point(0, 6),
new Point(-4, -6),
new Point(16, 6),
new Point(16, -7),
new Point(16, -3),
new Point(17, -4),
new Point(5, 19),
new Point(19, -8),
new Point(3, 16),
new Point(12, 13),
new Point(3, -4),
new Point(17, 5),
new Point(-3, 15),
new Point(-3, -9),
new Point(0, 11),
new Point(-9, -3),
new Point(-4, -2),
new Point(12, 10));
List<Point> hull = convexHull(points);
System.out.printf("Convex Hull: %s\n", hull);
}
} |
http://rosettacode.org/wiki/Convert_seconds_to_compound_duration | Convert seconds to compound duration | Task
Write a function or program which:
takes a positive integer representing a duration in seconds as input (e.g., 100), and
returns a string which shows the same duration decomposed into:
weeks,
days,
hours,
minutes, and
seconds.
This is detailed below (e.g., "2 hr, 59 sec").
Demonstrate that it passes the following three test-cases:
Test Cases
input number
output string
7259
2 hr, 59 sec
86400
1 d
6000000
9 wk, 6 d, 10 hr, 40 min
Details
The following five units should be used:
unit
suffix used in output
conversion
week
wk
1 week = 7 days
day
d
1 day = 24 hours
hour
hr
1 hour = 60 minutes
minute
min
1 minute = 60 seconds
second
sec
However, only include quantities with non-zero values in the output (e.g., return "1 d" and not "0 wk, 1 d, 0 hr, 0 min, 0 sec").
Give larger units precedence over smaller ones as much as possible (e.g., return 2 min, 10 sec and not 1 min, 70 sec or 130 sec)
Mimic the formatting shown in the test-cases (quantities sorted from largest unit to smallest and separated by comma+space; value and unit of each quantity separated by space).
| #Kotlin | Kotlin | fun compoundDuration(n: Int): String {
if (n < 0) return "" // task doesn't ask for negative integers to be converted
if (n == 0) return "0 sec"
val weeks : Int
val days : Int
val hours : Int
val minutes: Int
val seconds: Int
var divisor: Int = 7 * 24 * 60 * 60
var rem : Int
var result = ""
weeks = n / divisor
rem = n % divisor
divisor /= 7
days = rem / divisor
rem %= divisor
divisor /= 24
hours = rem / divisor
rem %= divisor
divisor /= 60
minutes = rem / divisor
seconds = rem % divisor
if (weeks > 0) result += "$weeks wk, "
if (days > 0) result += "$days d, "
if (hours > 0) result += "$hours hr, "
if (minutes > 0) result += "$minutes min, "
if (seconds > 0)
result += "$seconds sec"
else
result = result.substring(0, result.length - 2)
return result
}
fun main(args: Array<String>) {
val durations = intArrayOf(0, 7, 84, 7259, 86400, 6000000)
durations.forEach { println("$it\t-> ${compoundDuration(it)}") }
} |
http://rosettacode.org/wiki/Concurrent_computing | Concurrent computing | Task
Using either native language concurrency syntax or freely available libraries, write a program to display the strings "Enjoy" "Rosetta" "Code", one string per line, in random order.
Concurrency syntax must use threads, tasks, co-routines, or whatever concurrency is called in your language.
| #Ada | Ada | with Ada.Text_IO, Ada.Numerics.Float_Random;
procedure Concurrent_Hello is
type Messages is (Enjoy, Rosetta, Code);
task type Writer (Message : Messages);
task body Writer is
Seed : Ada.Numerics.Float_Random.Generator;
begin
Ada.Numerics.Float_Random.Reset (Seed); -- time-dependent, see ARM A.5.2
delay Duration (Ada.Numerics.Float_Random.Random (Seed));
Ada.Text_IO.Put_Line (Messages'Image(Message));
end Writer;
Taks: array(Messages) of access Writer -- 3 Writer tasks will immediately run
:= (new Writer(Enjoy), new Writer(Rosetta), new Writer(Code));
begin
null; -- the "environment task" doesn't need to do anything
end Concurrent_Hello; |
http://rosettacode.org/wiki/Conjugate_transpose | Conjugate transpose | Suppose that a matrix
M
{\displaystyle M}
contains complex numbers. Then the conjugate transpose of
M
{\displaystyle M}
is a matrix
M
H
{\displaystyle M^{H}}
containing the complex conjugates of the matrix transposition of
M
{\displaystyle M}
.
(
M
H
)
j
i
=
M
i
j
¯
{\displaystyle (M^{H})_{ji}={\overline {M_{ij}}}}
This means that row
j
{\displaystyle j}
, column
i
{\displaystyle i}
of the conjugate transpose equals the
complex conjugate of row
i
{\displaystyle i}
, column
j
{\displaystyle j}
of the original matrix.
In the next list,
M
{\displaystyle M}
must also be a square matrix.
A Hermitian matrix equals its own conjugate transpose:
M
H
=
M
{\displaystyle M^{H}=M}
.
A normal matrix is commutative in multiplication with its conjugate transpose:
M
H
M
=
M
M
H
{\displaystyle M^{H}M=MM^{H}}
.
A unitary matrix has its inverse equal to its conjugate transpose:
M
H
=
M
−
1
{\displaystyle M^{H}=M^{-1}}
.
This is true iff
M
H
M
=
I
n
{\displaystyle M^{H}M=I_{n}}
and iff
M
M
H
=
I
n
{\displaystyle MM^{H}=I_{n}}
, where
I
n
{\displaystyle I_{n}}
is the identity matrix.
Task
Given some matrix of complex numbers, find its conjugate transpose.
Also determine if the matrix is a:
Hermitian matrix,
normal matrix, or
unitary matrix.
See also
MathWorld entry: conjugate transpose
MathWorld entry: Hermitian matrix
MathWorld entry: normal matrix
MathWorld entry: unitary matrix
| #Common_Lisp | Common Lisp |
(defun matrix-multiply (m1 m2)
(mapcar
(lambda (row)
(apply #'mapcar
(lambda (&rest column)
(apply #'+ (mapcar #'* row column))) m2)) m1))
(defun identity-p (m &optional (tolerance 1e-6))
"Is m an identity matrix?"
(loop for row in m
for r = 1 then (1+ r) do
(loop for col in row
for c = 1 then (1+ c) do
(if (eql r c)
(unless (< (abs (- col 1)) tolerance) (return-from identity-p nil))
(unless (< (abs col) tolerance) (return-from identity-p nil)) )))
T )
(defun conjugate-transpose (m)
(apply #'mapcar #'list (mapcar #'(lambda (r) (mapcar #'conjugate r)) m)) )
(defun hermitian-p (m)
(equalp m (conjugate-transpose m)))
(defun normal-p (m)
(let ((m* (conjugate-transpose m)))
(equalp (matrix-multiply m m*) (matrix-multiply m* m)) ))
(defun unitary-p (m)
(identity-p (matrix-multiply m (conjugate-transpose m))) )
|
http://rosettacode.org/wiki/Compound_data_type | Compound data type |
Data Structure
This illustrates a data structure, a means of storing data within a program.
You may see other such structures in the Data Structures category.
Task
Create a compound data type:
Point(x,y)
A compound data type is one that holds multiple independent values.
Related task
Enumeration
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
| #6502_Assembly | 6502 Assembly | MAX_POINT_OBJECTS = 64 ; define a constant
.rsset $0400 ; reserve memory storage starting at address $0400
point_x .rs MAX_POINT_OBJECTS ; reserve 64 bytes for x-coordinates
point_y .rs MAX_POINT_OBJECTS ; reserve 64 bytes for y-coordinates |
http://rosettacode.org/wiki/Compound_data_type | Compound data type |
Data Structure
This illustrates a data structure, a means of storing data within a program.
You may see other such structures in the Data Structures category.
Task
Create a compound data type:
Point(x,y)
A compound data type is one that holds multiple independent values.
Related task
Enumeration
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
| #Action.21 | Action! | INCLUDE "D2:REAL.ACT" ;from the Action! Tool Kit
DEFINE REALPTR="CARD"
TYPE PointI=[INT x,y]
TYPE PointR=[REALPTR rx,ry]
PROC Main()
PointI p1
PointR p2
REAL realx,realy
Put(125) PutE() ;clear screen
p1.x=123
p1.y=4567
ValR("12.34",realx)
ValR("5.6789",realy)
p2.rx=realx
p2.ry=realy
PrintF("Integer point p1=(%I,%I)%E",p1.x,p1.y)
Print("Real point p2=(")
PrintR(p2.rx) Print(",")
PrintR(p2.ry) Print(")")
RETURN |
http://rosettacode.org/wiki/Continued_fraction | Continued fraction | continued fraction
Mathworld
a
0
+
b
1
a
1
+
b
2
a
2
+
b
3
a
3
+
⋱
{\displaystyle a_{0}+{\cfrac {b_{1}}{a_{1}+{\cfrac {b_{2}}{a_{2}+{\cfrac {b_{3}}{a_{3}+\ddots }}}}}}}
The task is to write a program which generates such a number and prints a real representation of it. The code should be tested by calculating and printing the square root of 2, Napier's Constant, and Pi, using the following coefficients:
For the square root of 2, use
a
0
=
1
{\displaystyle a_{0}=1}
then
a
N
=
2
{\displaystyle a_{N}=2}
.
b
N
{\displaystyle b_{N}}
is always
1
{\displaystyle 1}
.
2
=
1
+
1
2
+
1
2
+
1
2
+
⋱
{\displaystyle {\sqrt {2}}=1+{\cfrac {1}{2+{\cfrac {1}{2+{\cfrac {1}{2+\ddots }}}}}}}
For Napier's Constant, use
a
0
=
2
{\displaystyle a_{0}=2}
, then
a
N
=
N
{\displaystyle a_{N}=N}
.
b
1
=
1
{\displaystyle b_{1}=1}
then
b
N
=
N
−
1
{\displaystyle b_{N}=N-1}
.
e
=
2
+
1
1
+
1
2
+
2
3
+
3
4
+
⋱
{\displaystyle e=2+{\cfrac {1}{1+{\cfrac {1}{2+{\cfrac {2}{3+{\cfrac {3}{4+\ddots }}}}}}}}}
For Pi, use
a
0
=
3
{\displaystyle a_{0}=3}
then
a
N
=
6
{\displaystyle a_{N}=6}
.
b
N
=
(
2
N
−
1
)
2
{\displaystyle b_{N}=(2N-1)^{2}}
.
π
=
3
+
1
6
+
9
6
+
25
6
+
⋱
{\displaystyle \pi =3+{\cfrac {1}{6+{\cfrac {9}{6+{\cfrac {25}{6+\ddots }}}}}}}
See also
Continued fraction/Arithmetic for tasks that do arithmetic over continued fractions.
| #Klong | Klong |
cf::{[f g i];f::x;g::y;i::z;
f(0)+z{i::i-1;g(i+1)%f(i+1)+x}:*0}
cf({:[0=x;1;2]};{x;1};1000)
cf({:[0=x;2;x]};{:[x>1;x-1;x]};1000)
cf({:[0=x;3;6]};{((2*x)-1)^2};1000)
|
http://rosettacode.org/wiki/Continued_fraction | Continued fraction | continued fraction
Mathworld
a
0
+
b
1
a
1
+
b
2
a
2
+
b
3
a
3
+
⋱
{\displaystyle a_{0}+{\cfrac {b_{1}}{a_{1}+{\cfrac {b_{2}}{a_{2}+{\cfrac {b_{3}}{a_{3}+\ddots }}}}}}}
The task is to write a program which generates such a number and prints a real representation of it. The code should be tested by calculating and printing the square root of 2, Napier's Constant, and Pi, using the following coefficients:
For the square root of 2, use
a
0
=
1
{\displaystyle a_{0}=1}
then
a
N
=
2
{\displaystyle a_{N}=2}
.
b
N
{\displaystyle b_{N}}
is always
1
{\displaystyle 1}
.
2
=
1
+
1
2
+
1
2
+
1
2
+
⋱
{\displaystyle {\sqrt {2}}=1+{\cfrac {1}{2+{\cfrac {1}{2+{\cfrac {1}{2+\ddots }}}}}}}
For Napier's Constant, use
a
0
=
2
{\displaystyle a_{0}=2}
, then
a
N
=
N
{\displaystyle a_{N}=N}
.
b
1
=
1
{\displaystyle b_{1}=1}
then
b
N
=
N
−
1
{\displaystyle b_{N}=N-1}
.
e
=
2
+
1
1
+
1
2
+
2
3
+
3
4
+
⋱
{\displaystyle e=2+{\cfrac {1}{1+{\cfrac {1}{2+{\cfrac {2}{3+{\cfrac {3}{4+\ddots }}}}}}}}}
For Pi, use
a
0
=
3
{\displaystyle a_{0}=3}
then
a
N
=
6
{\displaystyle a_{N}=6}
.
b
N
=
(
2
N
−
1
)
2
{\displaystyle b_{N}=(2N-1)^{2}}
.
π
=
3
+
1
6
+
9
6
+
25
6
+
⋱
{\displaystyle \pi =3+{\cfrac {1}{6+{\cfrac {9}{6+{\cfrac {25}{6+\ddots }}}}}}}
See also
Continued fraction/Arithmetic for tasks that do arithmetic over continued fractions.
| #Kotlin | Kotlin | // version 1.1.2
typealias Func = (Int) -> IntArray
fun calc(f: Func, n: Int): Double {
var temp = 0.0
for (i in n downTo 1) {
val p = f(i)
temp = p[1] / (p[0] + temp)
}
return f(0)[0] + temp
}
fun main(args: Array<String>) {
val pList = listOf<Pair<String, Func>>(
"sqrt(2)" to { n -> intArrayOf(if (n > 0) 2 else 1, 1) },
"e " to { n -> intArrayOf(if (n > 0) n else 2, if (n > 1) n - 1 else 1) },
"pi " to { n -> intArrayOf(if (n > 0) 6 else 3, (2 * n - 1) * (2 * n - 1)) }
)
for (pair in pList) println("${pair.first} = ${calc(pair.second, 200)}")
} |
http://rosettacode.org/wiki/Copy_a_string | Copy a string | This task is about copying a string.
Task
Where it is relevant, distinguish between copying the contents of a string
versus making an additional reference to an existing string.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Maple | Maple |
> s := "some string";
s := "some string"
> t := "some string";
t := "some string"
> evalb( s = t ); # they are equal
true
> addressof( s ) = addressof( t ); # not just equal data, but the same address in memory
3078334210 = 3078334210
> u := t: # copy reference
|
http://rosettacode.org/wiki/Copy_a_string | Copy a string | This task is about copying a string.
Task
Where it is relevant, distinguish between copying the contents of a string
versus making an additional reference to an existing string.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Mathematica_.2F_Wolfram_Language | Mathematica / Wolfram Language | a="Hello World"
b=a |
http://rosettacode.org/wiki/Constrained_random_points_on_a_circle | Constrained random points on a circle | Task
Generate 100 <x,y> coordinate pairs such that x and y are integers sampled from the uniform distribution with the condition that
10
≤
x
2
+
y
2
≤
15
{\displaystyle 10\leq {\sqrt {x^{2}+y^{2}}}\leq 15}
.
Then display/plot them. The outcome should be a "fuzzy" circle. The actual number of points plotted may be less than 100, given that some pairs may be generated more than once.
There are several possible approaches to accomplish this. Here are two possible algorithms.
1) Generate random pairs of integers and filter out those that don't satisfy this condition:
10
≤
x
2
+
y
2
≤
15
{\displaystyle 10\leq {\sqrt {x^{2}+y^{2}}}\leq 15}
.
2) Precalculate the set of all possible points (there are 404 of them) and select randomly from this set.
| #Factor | Factor | USING: io kernel math.matrices math.order math.ranges
math.statistics math.vectors random sequences strings ;
CHAR: X -15 15 [a,b] dup cartesian-product concat
[ sum-of-squares 100 225 between? ] filter 100 sample
[ 15 v+n ] map 31 31 32 <matrix> [ matrix-set-nths ] keep
[ >string print ] each |
http://rosettacode.org/wiki/Convex_hull | Convex hull | Find the points which form a convex hull from a set of arbitrary two dimensional points.
For example, given the points (16,3), (12,17), (0,6), (-4,-6), (16,6), (16,-7), (16,-3), (17,-4), (5,19), (19,-8), (3,16), (12,13), (3,-4), (17,5), (-3,15), (-3,-9), (0,11), (-9,-3), (-4,-2) and (12,10) the convex hull would be (-9,-3), (-3,-9), (19,-8), (17,5), (12,17), (5,19) and (-3,15).
See also
Convex Hull (youtube)
http://www.geeksforgeeks.org/convex-hull-set-2-graham-scan/
| #JavaScript | JavaScript |
function convexHull(points) {
points.sort(comparison);
var L = [];
for (var i = 0; i < points.length; i++) {
while (L.length >= 2 && cross(L[L.length - 2], L[L.length - 1], points[i]) <= 0) {
L.pop();
}
L.push(points[i]);
}
var U = [];
for (var i = points.length - 1; i >= 0; i--) {
while (U.length >= 2 && cross(U[U.length - 2], U[U.length - 1], points[i]) <= 0) {
U.pop();
}
U.push(points[i]);
}
L.pop();
U.pop();
return L.concat(U);
}
function comparison(a, b) {
return a.x == b.x ? a.y - b.y : a.x - b.x;
}
function cross(a, b, o) {
return (a.x - o.x) * (b.y - o.y) - (a.y - o.y) * (b.x - o.x);
}
|
http://rosettacode.org/wiki/Convert_seconds_to_compound_duration | Convert seconds to compound duration | Task
Write a function or program which:
takes a positive integer representing a duration in seconds as input (e.g., 100), and
returns a string which shows the same duration decomposed into:
weeks,
days,
hours,
minutes, and
seconds.
This is detailed below (e.g., "2 hr, 59 sec").
Demonstrate that it passes the following three test-cases:
Test Cases
input number
output string
7259
2 hr, 59 sec
86400
1 d
6000000
9 wk, 6 d, 10 hr, 40 min
Details
The following five units should be used:
unit
suffix used in output
conversion
week
wk
1 week = 7 days
day
d
1 day = 24 hours
hour
hr
1 hour = 60 minutes
minute
min
1 minute = 60 seconds
second
sec
However, only include quantities with non-zero values in the output (e.g., return "1 d" and not "0 wk, 1 d, 0 hr, 0 min, 0 sec").
Give larger units precedence over smaller ones as much as possible (e.g., return 2 min, 10 sec and not 1 min, 70 sec or 130 sec)
Mimic the formatting shown in the test-cases (quantities sorted from largest unit to smallest and separated by comma+space; value and unit of each quantity separated by space).
| #Liberty_BASIC | Liberty BASIC |
[start]
input "Enter SECONDS: "; seconds
seconds=int(abs(seconds))
if seconds=0 then print "Program complete.": end
UnitsFound=0: LastFound$=""
years=int(seconds/31449600): seconds=seconds mod 31449600
if years then LastFound$="years"
weeks=int(seconds/604800): seconds=seconds mod 604800
if weeks then LastFound$="weeks"
days=int(seconds/86400): seconds=seconds mod 86400
if days then LastFound$="days"
hours=int(seconds/3600): seconds=seconds mod 3600
if hours then LastFound$="hours"
minutes=int(seconds/60): seconds=seconds mod 60
if minutes then LastFound$="minutes"
if seconds then LastFound$="seconds"
select case years
case 0
case 1: print years; " year";
case else: print years; " years";
end select
select case weeks
case 0
case 1
if years then
if LastFound$="weeks" then print " and "; else print ", ";
end if
print weeks; " week";
case else
if years then
if LastFound$="weeks" then print " and "; else print ", ";
end if
print weeks; " weeks";
end select
select case days
case 0
case 1
if years or weeks then
if LastFound$="days" then print " and "; else print ", ";
end if
print days; " day";
case else
if years or weeks then
if LastFound$="days" then print " and "; else print ", ";
end if
print days; " days";
end select
select case hours
case 0
case 1
if years or weeks or days then
if LastFound$="hours" then print " and "; else print ", ";
end if
print hours; " hour";
case else
if years or weeks or days then
if LastFound$="hours" then print " and "; else print ", ";
end if
print hours; " hours";
end select
select case minutes
case 0
case 1
if years or weeks or days or hours then
if LastFound$="minutes" then print " and "; else print ", ";
end if
print minutes; " minute";
case else
if years or weeks or days or hours then
if LastFound$="minutes" then print " and "; else print ", ";
end if
print minutes; " minutes";
end select
select case seconds
case 0
case 1
if years or weeks or days or hours or minutes then
if LastFound$="seconds" then print " and "; else print ", ";
end if
print seconds; " second";
case else
if years or weeks or days or hours or minutes then
if LastFound$="seconds" then print " and "; else print ", ";
end if
print seconds; " seconds";
end select
print
goto [start]
|
http://rosettacode.org/wiki/Concurrent_computing | Concurrent computing | Task
Using either native language concurrency syntax or freely available libraries, write a program to display the strings "Enjoy" "Rosetta" "Code", one string per line, in random order.
Concurrency syntax must use threads, tasks, co-routines, or whatever concurrency is called in your language.
| #ALGOL_68 | ALGOL 68 | main:(
PROC echo = (STRING string)VOID:
printf(($gl$,string));
PAR(
echo("Enjoy"),
echo("Rosetta"),
echo("Code")
)
) |
http://rosettacode.org/wiki/Concurrent_computing | Concurrent computing | Task
Using either native language concurrency syntax or freely available libraries, write a program to display the strings "Enjoy" "Rosetta" "Code", one string per line, in random order.
Concurrency syntax must use threads, tasks, co-routines, or whatever concurrency is called in your language.
| #APL | APL | {⎕←⍵}&¨'Enjoy' 'Rosetta' 'Code' |
http://rosettacode.org/wiki/Conjugate_transpose | Conjugate transpose | Suppose that a matrix
M
{\displaystyle M}
contains complex numbers. Then the conjugate transpose of
M
{\displaystyle M}
is a matrix
M
H
{\displaystyle M^{H}}
containing the complex conjugates of the matrix transposition of
M
{\displaystyle M}
.
(
M
H
)
j
i
=
M
i
j
¯
{\displaystyle (M^{H})_{ji}={\overline {M_{ij}}}}
This means that row
j
{\displaystyle j}
, column
i
{\displaystyle i}
of the conjugate transpose equals the
complex conjugate of row
i
{\displaystyle i}
, column
j
{\displaystyle j}
of the original matrix.
In the next list,
M
{\displaystyle M}
must also be a square matrix.
A Hermitian matrix equals its own conjugate transpose:
M
H
=
M
{\displaystyle M^{H}=M}
.
A normal matrix is commutative in multiplication with its conjugate transpose:
M
H
M
=
M
M
H
{\displaystyle M^{H}M=MM^{H}}
.
A unitary matrix has its inverse equal to its conjugate transpose:
M
H
=
M
−
1
{\displaystyle M^{H}=M^{-1}}
.
This is true iff
M
H
M
=
I
n
{\displaystyle M^{H}M=I_{n}}
and iff
M
M
H
=
I
n
{\displaystyle MM^{H}=I_{n}}
, where
I
n
{\displaystyle I_{n}}
is the identity matrix.
Task
Given some matrix of complex numbers, find its conjugate transpose.
Also determine if the matrix is a:
Hermitian matrix,
normal matrix, or
unitary matrix.
See also
MathWorld entry: conjugate transpose
MathWorld entry: Hermitian matrix
MathWorld entry: normal matrix
MathWorld entry: unitary matrix
| #D | D | import std.stdio, std.complex, std.math, std.range, std.algorithm,
std.numeric;
T[][] conjugateTranspose(T)(in T[][] m) pure nothrow @safe {
auto r = new typeof(return)(m[0].length, m.length);
foreach (immutable nr, const row; m)
foreach (immutable nc, immutable c; row)
r[nc][nr] = c.conj;
return r;
}
bool isRectangular(T)(in T[][] M) pure nothrow @safe @nogc {
return M.all!(row => row.length == M[0].length);
}
T[][] matMul(T)(in T[][] A, in T[][] B) pure nothrow /*@safe*/
in {
assert(A.isRectangular && B.isRectangular &&
!A.empty && !B.empty && A[0].length == B.length);
} body {
auto result = new T[][](A.length, B[0].length);
auto aux = new T[B.length];
foreach (immutable j; 0 .. B[0].length) {
foreach (immutable k, const row; B)
aux[k] = row[j];
foreach (immutable i, const ai; A)
result[i][j] = dotProduct(ai, aux);
}
return result;
}
/// Check any number of complex matrices for equality within
/// some bits of mantissa.
bool areEqual(T)(in Complex!T[][][] matrices, in size_t nBits=20)
pure nothrow /*@safe*/ {
static bool allSame(U)(in U[] v) pure nothrow @nogc {
return v[1 .. $].all!(c => c == v[0]);
}
bool allNearSame(in Complex!T[] v) pure nothrow @nogc {
auto v0 = v[0].Complex!T; // To avoid another cast.
return v[1 .. $].all!(c => feqrel(v0.re, c.re) >= nBits &&
feqrel(v0.im, c.im) >= nBits);
}
immutable x = matrices.map!(m => m.length).array;
if (!allSame(x))
return false;
immutable y = matrices.map!(m => m[0].length).array;
if (!allSame(y))
return false;
foreach (immutable s; 0 .. x[0])
foreach (immutable t; 0 .. y[0])
if (!allNearSame(matrices.map!(m => m[s][t]).array))
return false;
return true;
}
bool isHermitian(T)(in Complex!T[][] m, in Complex!T[][] ct)
pure nothrow /*@safe*/ {
return [m, ct].areEqual;
}
bool isNormal(T)(in Complex!T[][] m, in Complex!T[][] ct)
pure nothrow /*@safe*/ {
return [matMul(m, ct), matMul(ct, m)].areEqual;
}
auto complexIdentitymatrix(in size_t side) pure nothrow /*@safe*/ {
return side.iota.map!(r => side.iota.map!(c => complex(r == c)).array).array;
}
bool isUnitary(T)(in Complex!T[][] m, in Complex!T[][] ct)
pure nothrow /*@safe*/ {
immutable mct = matMul(m, ct);
immutable ident = mct.length.complexIdentitymatrix;
return [mct, matMul(ct, m), ident].areEqual;
}
void main() /*@safe*/ {
alias C = complex;
immutable x = 2 ^^ 0.5 / 2;
immutable data = [[[C(3.0, 0.0), C(2.0, 1.0)],
[C(2.0, -1.0), C(1.0, 0.0)]],
[[C(1.0, 0.0), C(1.0, 0.0), C(0.0, 0.0)],
[C(0.0, 0.0), C(1.0, 0.0), C(1.0, 0.0)],
[C(1.0, 0.0), C(0.0, 0.0), C(1.0, 0.0)]],
[[C(x, 0.0), C(x, 0.0), C(0.0, 0.0)],
[C(0.0, -x), C(0.0, x), C(0.0, 0.0)],
[C(0.0, 0.0), C(0.0, 0.0), C(0.0, 1.0)]]];
foreach (immutable mat; data) {
enum mFormat = "[%([%(%1.3f, %)],\n %)]]";
writefln("Matrix:\n" ~ mFormat, mat);
immutable ct = conjugateTranspose(mat);
"Its conjugate transpose:".writeln;
writefln(mFormat, ct);
writefln("Hermitian? %s.", isHermitian(mat, ct));
writefln("Normal? %s.", isNormal(mat, ct));
writefln("Unitary? %s.\n", isUnitary(mat, ct));
}
} |
http://rosettacode.org/wiki/Compound_data_type | Compound data type |
Data Structure
This illustrates a data structure, a means of storing data within a program.
You may see other such structures in the Data Structures category.
Task
Create a compound data type:
Point(x,y)
A compound data type is one that holds multiple independent values.
Related task
Enumeration
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
| #ActionScript | ActionScript | package
{
public class Point
{
public var x:Number;
public var y:Number;
public function Point(x:Number, y:Number)
{
this.x = x;
this.y = y;
}
}
} |
http://rosettacode.org/wiki/Compound_data_type | Compound data type |
Data Structure
This illustrates a data structure, a means of storing data within a program.
You may see other such structures in the Data Structures category.
Task
Create a compound data type:
Point(x,y)
A compound data type is one that holds multiple independent values.
Related task
Enumeration
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
| #Ada | Ada | type Point is tagged record
X : Integer := 0;
Y : Integer := 0;
end record; |
http://rosettacode.org/wiki/Continued_fraction | Continued fraction | continued fraction
Mathworld
a
0
+
b
1
a
1
+
b
2
a
2
+
b
3
a
3
+
⋱
{\displaystyle a_{0}+{\cfrac {b_{1}}{a_{1}+{\cfrac {b_{2}}{a_{2}+{\cfrac {b_{3}}{a_{3}+\ddots }}}}}}}
The task is to write a program which generates such a number and prints a real representation of it. The code should be tested by calculating and printing the square root of 2, Napier's Constant, and Pi, using the following coefficients:
For the square root of 2, use
a
0
=
1
{\displaystyle a_{0}=1}
then
a
N
=
2
{\displaystyle a_{N}=2}
.
b
N
{\displaystyle b_{N}}
is always
1
{\displaystyle 1}
.
2
=
1
+
1
2
+
1
2
+
1
2
+
⋱
{\displaystyle {\sqrt {2}}=1+{\cfrac {1}{2+{\cfrac {1}{2+{\cfrac {1}{2+\ddots }}}}}}}
For Napier's Constant, use
a
0
=
2
{\displaystyle a_{0}=2}
, then
a
N
=
N
{\displaystyle a_{N}=N}
.
b
1
=
1
{\displaystyle b_{1}=1}
then
b
N
=
N
−
1
{\displaystyle b_{N}=N-1}
.
e
=
2
+
1
1
+
1
2
+
2
3
+
3
4
+
⋱
{\displaystyle e=2+{\cfrac {1}{1+{\cfrac {1}{2+{\cfrac {2}{3+{\cfrac {3}{4+\ddots }}}}}}}}}
For Pi, use
a
0
=
3
{\displaystyle a_{0}=3}
then
a
N
=
6
{\displaystyle a_{N}=6}
.
b
N
=
(
2
N
−
1
)
2
{\displaystyle b_{N}=(2N-1)^{2}}
.
π
=
3
+
1
6
+
9
6
+
25
6
+
⋱
{\displaystyle \pi =3+{\cfrac {1}{6+{\cfrac {9}{6+{\cfrac {25}{6+\ddots }}}}}}}
See also
Continued fraction/Arithmetic for tasks that do arithmetic over continued fractions.
| #Lambdatalk | Lambdatalk |
{def gcf
{def gcf.rec
{lambda {:f :n :r}
{if {< :n 1}
then {+ {car {:f 0}} :r}
else {gcf.rec :f
{- :n 1}
{let { {:r :r}
{:ab {:f :n}}
} {/ {cdr :ab}
{+ {car :ab} :r}} }}}}}
{lambda {:f :n}
{gcf.rec :f :n 0}}}
{def phi
{lambda {:n}
{cons 1 1}}}
{gcf phi 50}
-> 1.618033988749895
{def sqrt2
{lambda {:n}
{cons {if {> :n 0} then 2 else 1} 1}}}
{gcf sqrt2 25}
-> 1.4142135623730951
{def napier
{lambda {:n}
{cons {if {> :n 0} then :n else 2} {if {> :n 1} then {- :n 1} else 1} }}}
{gcf napier 20}
-> 2.7182818284590455
{def fpi
{lambda {:n}
{cons {if {> :n 0} then 6 else 3} {pow {- {* 2 :n} 1} 2} }}}
{gcf fpi 500}
-> 3.1415926 516017554
// only 8 exact decimals for 500 iterations
// A very very slow convergence.
// Here is a quicker version without any obvious pattern
{def pi
{lambda {:n}
{cons {A.get :n {A.new 3 7 15 1 292 1 1 1 2 1 3 1 14 2 1 1}} 1}}}
{gcf pi 15}
-> 3.1415926 53589793
// Much quicker, 15 exact decimals after 15 iterations
|
http://rosettacode.org/wiki/Copy_a_string | Copy a string | This task is about copying a string.
Task
Where it is relevant, distinguish between copying the contents of a string
versus making an additional reference to an existing string.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #MATLAB | MATLAB | string1 = 'Hello';
string2 = string1; |
http://rosettacode.org/wiki/Copy_a_string | Copy a string | This task is about copying a string.
Task
Where it is relevant, distinguish between copying the contents of a string
versus making an additional reference to an existing string.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Maxima | Maxima | /* It's possible in Maxima to access individual characters by subscripts, but it's not the usual way.
Also, the result is "Lisp character", which cannot be used by other Maxima functions except cunlisp. The usual
way to access characters is charat, returning a "Maxima character" (actually a one characte string). With the latter,
it's impossible to modify a string in place, thus scopy is of little use. */
a: "loners"$
b: scopy(a)$
c: a$
c[2]: c[5]$
a;
"losers"
b;
"loners"
c;
"losers" |
http://rosettacode.org/wiki/Constrained_random_points_on_a_circle | Constrained random points on a circle | Task
Generate 100 <x,y> coordinate pairs such that x and y are integers sampled from the uniform distribution with the condition that
10
≤
x
2
+
y
2
≤
15
{\displaystyle 10\leq {\sqrt {x^{2}+y^{2}}}\leq 15}
.
Then display/plot them. The outcome should be a "fuzzy" circle. The actual number of points plotted may be less than 100, given that some pairs may be generated more than once.
There are several possible approaches to accomplish this. Here are two possible algorithms.
1) Generate random pairs of integers and filter out those that don't satisfy this condition:
10
≤
x
2
+
y
2
≤
15
{\displaystyle 10\leq {\sqrt {x^{2}+y^{2}}}\leq 15}
.
2) Precalculate the set of all possible points (there are 404 of them) and select randomly from this set.
| #Falcon | Falcon |
// Generate points in [min,max]^2 with constraint
function random_point (min, max, constraint)
[x, y] = [random(min, max), random(min, max)]
return constraint(x, y) ? [x, y] : random_point(min, max, constraint)
end
// Generate point list
in_circle = { x, y => 10**2 <= x**2 + y**2 and x**2 + y**2 <= 15**2 }
points = [].comp([0:100], {__ => random_point(-15, 15, in_circle)})
// Show points
for i in [-15:16]
for j in [-15:16]
>> [i, j] in points ? "x" : " "
end
>
end
|
http://rosettacode.org/wiki/Convex_hull | Convex hull | Find the points which form a convex hull from a set of arbitrary two dimensional points.
For example, given the points (16,3), (12,17), (0,6), (-4,-6), (16,6), (16,-7), (16,-3), (17,-4), (5,19), (19,-8), (3,16), (12,13), (3,-4), (17,5), (-3,15), (-3,-9), (0,11), (-9,-3), (-4,-2) and (12,10) the convex hull would be (-9,-3), (-3,-9), (19,-8), (17,5), (12,17), (5,19) and (-3,15).
See also
Convex Hull (youtube)
http://www.geeksforgeeks.org/convex-hull-set-2-graham-scan/
| #jq | jq | # ccw returns true if the three points make a counter-clockwise turn
def ccw(a; b; c):
a as [$ax, $ay]
| b as [$bx, $by]
| c as [$cx, $cy]
| (($bx - $ax) * ($cy - $ay)) > (($by - $ay) * ($cx - $ax)) ;
def convexHull:
if . == [] then []
else sort as $pts
# lower hull:
| reduce $pts[] as $pt ([];
until (length < 2 or ccw(.[-2]; .[-1]; $pt); .[:-1] )
| . + [$pt] )
# upper hull
| (length + 1) as $t
| reduce range($pts|length-2; -1; -1) as $i (.;
$pts[$i] as $pt
| until (length < $t or ccw(.[-2]; .[-1]; $pt); .[:-1] )
| . + [$pt])
| .[:-1]
end ; |
http://rosettacode.org/wiki/Convert_seconds_to_compound_duration | Convert seconds to compound duration | Task
Write a function or program which:
takes a positive integer representing a duration in seconds as input (e.g., 100), and
returns a string which shows the same duration decomposed into:
weeks,
days,
hours,
minutes, and
seconds.
This is detailed below (e.g., "2 hr, 59 sec").
Demonstrate that it passes the following three test-cases:
Test Cases
input number
output string
7259
2 hr, 59 sec
86400
1 d
6000000
9 wk, 6 d, 10 hr, 40 min
Details
The following five units should be used:
unit
suffix used in output
conversion
week
wk
1 week = 7 days
day
d
1 day = 24 hours
hour
hr
1 hour = 60 minutes
minute
min
1 minute = 60 seconds
second
sec
However, only include quantities with non-zero values in the output (e.g., return "1 d" and not "0 wk, 1 d, 0 hr, 0 min, 0 sec").
Give larger units precedence over smaller ones as much as possible (e.g., return 2 min, 10 sec and not 1 min, 70 sec or 130 sec)
Mimic the formatting shown in the test-cases (quantities sorted from largest unit to smallest and separated by comma+space; value and unit of each quantity separated by space).
| #Lua | Lua | function duration (secs)
local units, dur = {"wk", "d", "hr", "min"}, ""
for i, v in ipairs({604800, 86400, 3600, 60}) do
if secs >= v then
dur = dur .. math.floor(secs / v) .. " " .. units[i] .. ", "
secs = secs % v
end
end
if secs == 0 then
return dur:sub(1, -3)
else
return dur .. secs .. " sec"
end
end
print(duration(7259))
print(duration(86400))
print(duration(6000000)) |
http://rosettacode.org/wiki/Concurrent_computing | Concurrent computing | Task
Using either native language concurrency syntax or freely available libraries, write a program to display the strings "Enjoy" "Rosetta" "Code", one string per line, in random order.
Concurrency syntax must use threads, tasks, co-routines, or whatever concurrency is called in your language.
| #Astro | Astro | let words = ["Enjoy", "Rosetta", "Code"]
for word in words:
(word) |> async (w) =>
sleep(random())
print(w) |
http://rosettacode.org/wiki/Concurrent_computing | Concurrent computing | Task
Using either native language concurrency syntax or freely available libraries, write a program to display the strings "Enjoy" "Rosetta" "Code", one string per line, in random order.
Concurrency syntax must use threads, tasks, co-routines, or whatever concurrency is called in your language.
| #BaCon | BaCon | ' Concurrent computing using the OpenMP extension in GCC. Requires BaCon 3.6 or higher.
' Specify compiler flag
PRAGMA OPTIONS -fopenmp
' Sepcify linker flag
PRAGMA LDFLAGS -lgomp
' Declare array with text
DECLARE str$[] = { "Enjoy", "Rosetta", "Code" }
' Indicate MP optimization for FOR loop
PRAGMA omp parallel for num_threads(3)
' The actual FOR loop
FOR i = 0 TO 2
PRINT str$[i]
NEXT
|
http://rosettacode.org/wiki/Conjugate_transpose | Conjugate transpose | Suppose that a matrix
M
{\displaystyle M}
contains complex numbers. Then the conjugate transpose of
M
{\displaystyle M}
is a matrix
M
H
{\displaystyle M^{H}}
containing the complex conjugates of the matrix transposition of
M
{\displaystyle M}
.
(
M
H
)
j
i
=
M
i
j
¯
{\displaystyle (M^{H})_{ji}={\overline {M_{ij}}}}
This means that row
j
{\displaystyle j}
, column
i
{\displaystyle i}
of the conjugate transpose equals the
complex conjugate of row
i
{\displaystyle i}
, column
j
{\displaystyle j}
of the original matrix.
In the next list,
M
{\displaystyle M}
must also be a square matrix.
A Hermitian matrix equals its own conjugate transpose:
M
H
=
M
{\displaystyle M^{H}=M}
.
A normal matrix is commutative in multiplication with its conjugate transpose:
M
H
M
=
M
M
H
{\displaystyle M^{H}M=MM^{H}}
.
A unitary matrix has its inverse equal to its conjugate transpose:
M
H
=
M
−
1
{\displaystyle M^{H}=M^{-1}}
.
This is true iff
M
H
M
=
I
n
{\displaystyle M^{H}M=I_{n}}
and iff
M
M
H
=
I
n
{\displaystyle MM^{H}=I_{n}}
, where
I
n
{\displaystyle I_{n}}
is the identity matrix.
Task
Given some matrix of complex numbers, find its conjugate transpose.
Also determine if the matrix is a:
Hermitian matrix,
normal matrix, or
unitary matrix.
See also
MathWorld entry: conjugate transpose
MathWorld entry: Hermitian matrix
MathWorld entry: normal matrix
MathWorld entry: unitary matrix
| #F.23 | F# |
// Conjugate transpose. Nigel Galloway: January 10th., 2022
let fN g=let g=g|>List.map(List.map(fun(n,g)->System.Numerics.Complex(n,g)))|>MathNet.Numerics.LinearAlgebra.MatrixExtensions.matrix in (g,g.ConjugateTranspose())
let fG n g=(MathNet.Numerics.LinearAlgebra.Matrix.inverse n-g)|>MathNet.Numerics.LinearAlgebra.Matrix.forall(fun(n:System.Numerics.Complex)->abs n.Real<1e-14&&abs n.Imaginary<1e-14)
let test=[fN [[(3.0,0.0);(2.0,1.0)];[(2.0,-1.0);(1.0,0.0)]];fN [[(1.0,0.0);(1.0,0.0);(0.0,0.0)];[(0.0,0.0);(1.0,0.0);(1.0,0.0)];[(1.0,0.0);(0.0,0.0);(1.0,0.0)]];fN [[(1.0/sqrt 2.0,0.0);(1.0/sqrt 2.0,0.0);(0.0,0.0)];[(0.0,1.0/sqrt 2.0);(0.0,-1.0/sqrt 2.0);(0.0,0.0)];[(0.0,0.0);(0.0,0.0);(0.0,1.0)]]]
test|>List.iter(fun(n,g)->printfn $"Matrix\n------\n%A{n}\nConjugate transposed\n--------------------\n%A{g}\nIs hermitian: %A{n.IsHermitian()}\nIs normal: %A{n*g=g*n}\nIs unitary: %A{fG n g}\n")
|
http://rosettacode.org/wiki/Compound_data_type | Compound data type |
Data Structure
This illustrates a data structure, a means of storing data within a program.
You may see other such structures in the Data Structures category.
Task
Create a compound data type:
Point(x,y)
A compound data type is one that holds multiple independent values.
Related task
Enumeration
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
| #ALGOL_68 | ALGOL 68 | MODE UNIONX = UNION(
STRUCT(REAL r, INT i),
INT,
REAL,
STRUCT(INT ii),
STRUCT(REAL rr),
STRUCT([]REAL r)
); |
http://rosettacode.org/wiki/Compound_data_type | Compound data type |
Data Structure
This illustrates a data structure, a means of storing data within a program.
You may see other such structures in the Data Structures category.
Task
Create a compound data type:
Point(x,y)
A compound data type is one that holds multiple independent values.
Related task
Enumeration
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
| #ALGOL_W | ALGOL W | begin
% create the compound data type %
record Point( real x, y );
% declare a Point variable %
reference(Point) p;
% assign a value to p %
p := Point( 1, 0.5 );
% access the fields of p - note Algol W uses x(p) where many languages would use p.x %
write( x(p), y(p) )
end. |
http://rosettacode.org/wiki/Continued_fraction | Continued fraction | continued fraction
Mathworld
a
0
+
b
1
a
1
+
b
2
a
2
+
b
3
a
3
+
⋱
{\displaystyle a_{0}+{\cfrac {b_{1}}{a_{1}+{\cfrac {b_{2}}{a_{2}+{\cfrac {b_{3}}{a_{3}+\ddots }}}}}}}
The task is to write a program which generates such a number and prints a real representation of it. The code should be tested by calculating and printing the square root of 2, Napier's Constant, and Pi, using the following coefficients:
For the square root of 2, use
a
0
=
1
{\displaystyle a_{0}=1}
then
a
N
=
2
{\displaystyle a_{N}=2}
.
b
N
{\displaystyle b_{N}}
is always
1
{\displaystyle 1}
.
2
=
1
+
1
2
+
1
2
+
1
2
+
⋱
{\displaystyle {\sqrt {2}}=1+{\cfrac {1}{2+{\cfrac {1}{2+{\cfrac {1}{2+\ddots }}}}}}}
For Napier's Constant, use
a
0
=
2
{\displaystyle a_{0}=2}
, then
a
N
=
N
{\displaystyle a_{N}=N}
.
b
1
=
1
{\displaystyle b_{1}=1}
then
b
N
=
N
−
1
{\displaystyle b_{N}=N-1}
.
e
=
2
+
1
1
+
1
2
+
2
3
+
3
4
+
⋱
{\displaystyle e=2+{\cfrac {1}{1+{\cfrac {1}{2+{\cfrac {2}{3+{\cfrac {3}{4+\ddots }}}}}}}}}
For Pi, use
a
0
=
3
{\displaystyle a_{0}=3}
then
a
N
=
6
{\displaystyle a_{N}=6}
.
b
N
=
(
2
N
−
1
)
2
{\displaystyle b_{N}=(2N-1)^{2}}
.
π
=
3
+
1
6
+
9
6
+
25
6
+
⋱
{\displaystyle \pi =3+{\cfrac {1}{6+{\cfrac {9}{6+{\cfrac {25}{6+\ddots }}}}}}}
See also
Continued fraction/Arithmetic for tasks that do arithmetic over continued fractions.
| #Lua | Lua | function calc(fa, fb, expansions)
local a = 0.0
local b = 0.0
local r = 0.0
local i = expansions
while i > 0 do
a = fa(i)
b = fb(i)
r = b / (a + r)
i = i - 1
end
a = fa(0)
return a + r
end
function sqrt2a(n)
if n ~= 0 then
return 2.0
else
return 1.0
end
end
function sqrt2b(n)
return 1.0
end
function napiera(n)
if n ~= 0 then
return n
else
return 2.0
end
end
function napierb(n)
if n > 1.0 then
return n - 1.0
else
return 1.0
end
end
function pia(n)
if n ~= 0 then
return 6.0
else
return 3.0
end
end
function pib(n)
local c = 2.0 * n - 1.0
return c * c
end
function main()
local sqrt2 = calc(sqrt2a, sqrt2b, 1000)
local napier = calc(napiera, napierb, 1000)
local pi = calc(pia, pib, 1000)
print(sqrt2)
print(napier)
print(pi)
end
main() |
http://rosettacode.org/wiki/Copy_a_string | Copy a string | This task is about copying a string.
Task
Where it is relevant, distinguish between copying the contents of a string
versus making an additional reference to an existing string.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #MAXScript | MAXScript | str1 = "Hello"
str2 = copy str1 |
http://rosettacode.org/wiki/Copy_a_string | Copy a string | This task is about copying a string.
Task
Where it is relevant, distinguish between copying the contents of a string
versus making an additional reference to an existing string.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Metafont | Metafont | string s, a;
s := "hello";
a := s;
s := s & " world";
message s; % writes "hello world"
message a; % writes "hello"
end |
http://rosettacode.org/wiki/Constrained_random_points_on_a_circle | Constrained random points on a circle | Task
Generate 100 <x,y> coordinate pairs such that x and y are integers sampled from the uniform distribution with the condition that
10
≤
x
2
+
y
2
≤
15
{\displaystyle 10\leq {\sqrt {x^{2}+y^{2}}}\leq 15}
.
Then display/plot them. The outcome should be a "fuzzy" circle. The actual number of points plotted may be less than 100, given that some pairs may be generated more than once.
There are several possible approaches to accomplish this. Here are two possible algorithms.
1) Generate random pairs of integers and filter out those that don't satisfy this condition:
10
≤
x
2
+
y
2
≤
15
{\displaystyle 10\leq {\sqrt {x^{2}+y^{2}}}\leq 15}
.
2) Precalculate the set of all possible points (there are 404 of them) and select randomly from this set.
| #Fortran | Fortran | program Constrained_Points
implicit none
integer, parameter :: samples = 100
integer :: i, j, n, randpoint
real :: r
type points
integer :: x, y
end type
type(points) :: set(500), temp
! Create set of valid points
n = 0
do i = -15, 15
do j = -15, 15
if(sqrt(real(i*i + j*j)) >= 10.0 .and. sqrt(real(i*i + j*j)) <= 15.0) then
n = n + 1
set(n)%x = i
set(n)%y = j
end if
end do
end do
! create 100 random points
! Choose a random number between 1 and n inclusive and swap point at this index with point at index 1
! Choose a random number between 2 and n inclusive and swap point at this index with point at index 2
! Continue in this fashion until 100 points have been selected
call random_seed
do i = 1, samples
call random_number(r)
randpoint = r * (n + 1 - i) + i
temp = set(i)
set(i) = set(randpoint)
set(randpoint) = temp
end do
! In order to facilitate printing sort random points into ascending order
! sort x in ascending order
do i = 2, samples
j = i - 1
temp = set(i)
do while (j>=1 .and. set(j)%x > temp%x)
set(j+1) = set(j)
j = j - 1
end do
set(j+1) = temp
end do
! sort y in ascending order for same x
do i = 2, samples
j = i - 1
temp = set(i)
do while (j>=1 .and. set(j)%x == temp%x .and. set(j)%y > temp%y)
set(j+1) = set(j)
j = j - 1
end do
set(j+1) = temp
end do
! print circle
write(*,"(a,a)", advance="no") repeat(" ", set(1)%y+15), "*"
do i = 2, samples
if(set(i)%x == set(i-1)%x) then
write(*,"(a,a)", advance="no") repeat(" ", set(i)%y - set(i-1)%y-1), "*"
else
n = set(i)%x - set(i-1)%x
do j = 1, n
write(*,*)
end do
write(*,"(a,a)", advance="no") repeat(" ", set(i)%y+15), "*"
end if
end do
end program |
http://rosettacode.org/wiki/Convex_hull | Convex hull | Find the points which form a convex hull from a set of arbitrary two dimensional points.
For example, given the points (16,3), (12,17), (0,6), (-4,-6), (16,6), (16,-7), (16,-3), (17,-4), (5,19), (19,-8), (3,16), (12,13), (3,-4), (17,5), (-3,15), (-3,-9), (0,11), (-9,-3), (-4,-2) and (12,10) the convex hull would be (-9,-3), (-3,-9), (19,-8), (17,5), (12,17), (5,19) and (-3,15).
See also
Convex Hull (youtube)
http://www.geeksforgeeks.org/convex-hull-set-2-graham-scan/
| #Julia | Julia | # v1.0.4
# https://github.com/JuliaPolyhedra/Polyhedra.jl/blob/master/examples/operations.ipynb
using Polyhedra, CDDLib
A = vrep([[16,3], [12,17], [0,6], [-4,-6], [16,6], [16,-7], [16,-3], [17,-4], [5,19], [19,-8], [3,16], [12,13], [3,-4], [17,5], [-3,15], [-3,-9], [0,11], [-9,-3], [-4,-2], [12,10]])
P = polyhedron(A, CDDLib.Library())
Pch = convexhull(P, P)
removevredundancy!(Pch)
println("$Pch") |
http://rosettacode.org/wiki/Convert_seconds_to_compound_duration | Convert seconds to compound duration | Task
Write a function or program which:
takes a positive integer representing a duration in seconds as input (e.g., 100), and
returns a string which shows the same duration decomposed into:
weeks,
days,
hours,
minutes, and
seconds.
This is detailed below (e.g., "2 hr, 59 sec").
Demonstrate that it passes the following three test-cases:
Test Cases
input number
output string
7259
2 hr, 59 sec
86400
1 d
6000000
9 wk, 6 d, 10 hr, 40 min
Details
The following five units should be used:
unit
suffix used in output
conversion
week
wk
1 week = 7 days
day
d
1 day = 24 hours
hour
hr
1 hour = 60 minutes
minute
min
1 minute = 60 seconds
second
sec
However, only include quantities with non-zero values in the output (e.g., return "1 d" and not "0 wk, 1 d, 0 hr, 0 min, 0 sec").
Give larger units precedence over smaller ones as much as possible (e.g., return 2 min, 10 sec and not 1 min, 70 sec or 130 sec)
Mimic the formatting shown in the test-cases (quantities sorted from largest unit to smallest and separated by comma+space; value and unit of each quantity separated by space).
| #Maple | Maple |
tim := proc (s) local weeks, days, hours, minutes, seconds;
weeks := trunc((1/604800)*s);
days := trunc((1/86400)*s)-7*weeks;
hours := trunc((1/3600)*s)-24*days-168*weeks;
minutes := trunc((1/60)*s)-60*hours-1440*days-10080*weeks;
seconds := s-60*minutes-3600*hours-86400*days-604800*weeks;
printf("%s", cat(`if`(0 < weeks, cat(weeks, "wk, "), NULL), `if`(0 < days, cat(days, "d, "), NULL), `if`(0 < hours, cat(hours, "hr, "), NULL), `if`(0 < minutes, cat(minutes, "min, "), NULL), `if`(0 < seconds, cat(seconds, "sec"), NULL)))
end proc;
|
http://rosettacode.org/wiki/Convert_seconds_to_compound_duration | Convert seconds to compound duration | Task
Write a function or program which:
takes a positive integer representing a duration in seconds as input (e.g., 100), and
returns a string which shows the same duration decomposed into:
weeks,
days,
hours,
minutes, and
seconds.
This is detailed below (e.g., "2 hr, 59 sec").
Demonstrate that it passes the following three test-cases:
Test Cases
input number
output string
7259
2 hr, 59 sec
86400
1 d
6000000
9 wk, 6 d, 10 hr, 40 min
Details
The following five units should be used:
unit
suffix used in output
conversion
week
wk
1 week = 7 days
day
d
1 day = 24 hours
hour
hr
1 hour = 60 minutes
minute
min
1 minute = 60 seconds
second
sec
However, only include quantities with non-zero values in the output (e.g., return "1 d" and not "0 wk, 1 d, 0 hr, 0 min, 0 sec").
Give larger units precedence over smaller ones as much as possible (e.g., return 2 min, 10 sec and not 1 min, 70 sec or 130 sec)
Mimic the formatting shown in the test-cases (quantities sorted from largest unit to smallest and separated by comma+space; value and unit of each quantity separated by space).
| #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | compoundDuration[x_Integer] :=
StringJoin @@ (Riffle[
ToString /@ ((({Floor[x/604800],
Mod[x, 604800]} /. {a_, b_} -> {a, Floor[b/86400],
Mod[b, 86400]}) /. {a__, b_} -> {a, Floor[b/3600],
Mod[b, 3600]}) /. {a__, b_} -> {a, Floor[b/60],
Mod[b, 60]}), {" wk, ", " d, ", " hr, ", " min, ",
" sec"}] //. {a___, "0", b_, c___} -> {a, c})
Grid[Table[{n, "secs =",
compoundDuration[n]}, {n, {7259, 86400, 6000000}}],
Alignment -> {Left, Baseline}] |
http://rosettacode.org/wiki/Concurrent_computing | Concurrent computing | Task
Using either native language concurrency syntax or freely available libraries, write a program to display the strings "Enjoy" "Rosetta" "Code", one string per line, in random order.
Concurrency syntax must use threads, tasks, co-routines, or whatever concurrency is called in your language.
| #BBC_BASIC | BBC BASIC | INSTALL @lib$+"TIMERLIB"
tID1% = FN_ontimer(100, PROCtask1, 1)
tID2% = FN_ontimer(100, PROCtask2, 1)
tID3% = FN_ontimer(100, PROCtask3, 1)
ON ERROR PRINT REPORT$ : PROCcleanup : END
ON CLOSE PROCcleanup : QUIT
REPEAT
WAIT 0
UNTIL FALSE
END
DEF PROCtask1
PRINT "Enjoy"
ENDPROC
DEF PROCtask2
PRINT "Rosetta"
ENDPROC
DEF PROCtask3
PRINT "Code"
ENDPROC
DEF PROCcleanup
PROC_killtimer(tID1%)
PROC_killtimer(tID2%)
PROC_killtimer(tID3%)
ENDPROC |
http://rosettacode.org/wiki/Concurrent_computing | Concurrent computing | Task
Using either native language concurrency syntax or freely available libraries, write a program to display the strings "Enjoy" "Rosetta" "Code", one string per line, in random order.
Concurrency syntax must use threads, tasks, co-routines, or whatever concurrency is called in your language.
| #C | C | #include <stdio.h>
#include <unistd.h>
#include <pthread.h>
pthread_mutex_t condm = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
int bang = 0;
#define WAITBANG() do { \
pthread_mutex_lock(&condm); \
while( bang == 0 ) \
{ \
pthread_cond_wait(&cond, &condm); \
} \
pthread_mutex_unlock(&condm); } while(0);\
void *t_enjoy(void *p)
{
WAITBANG();
printf("Enjoy\n");
pthread_exit(0);
}
void *t_rosetta(void *p)
{
WAITBANG();
printf("Rosetta\n");
pthread_exit(0);
}
void *t_code(void *p)
{
WAITBANG();
printf("Code\n");
pthread_exit(0);
}
typedef void *(*threadfunc)(void *);
int main()
{
int i;
pthread_t a[3];
threadfunc p[3] = {t_enjoy, t_rosetta, t_code};
for(i=0;i<3;i++)
{
pthread_create(&a[i], NULL, p[i], NULL);
}
sleep(1);
bang = 1;
pthread_cond_broadcast(&cond);
for(i=0;i<3;i++)
{
pthread_join(a[i], NULL);
}
} |
http://rosettacode.org/wiki/Conjugate_transpose | Conjugate transpose | Suppose that a matrix
M
{\displaystyle M}
contains complex numbers. Then the conjugate transpose of
M
{\displaystyle M}
is a matrix
M
H
{\displaystyle M^{H}}
containing the complex conjugates of the matrix transposition of
M
{\displaystyle M}
.
(
M
H
)
j
i
=
M
i
j
¯
{\displaystyle (M^{H})_{ji}={\overline {M_{ij}}}}
This means that row
j
{\displaystyle j}
, column
i
{\displaystyle i}
of the conjugate transpose equals the
complex conjugate of row
i
{\displaystyle i}
, column
j
{\displaystyle j}
of the original matrix.
In the next list,
M
{\displaystyle M}
must also be a square matrix.
A Hermitian matrix equals its own conjugate transpose:
M
H
=
M
{\displaystyle M^{H}=M}
.
A normal matrix is commutative in multiplication with its conjugate transpose:
M
H
M
=
M
M
H
{\displaystyle M^{H}M=MM^{H}}
.
A unitary matrix has its inverse equal to its conjugate transpose:
M
H
=
M
−
1
{\displaystyle M^{H}=M^{-1}}
.
This is true iff
M
H
M
=
I
n
{\displaystyle M^{H}M=I_{n}}
and iff
M
M
H
=
I
n
{\displaystyle MM^{H}=I_{n}}
, where
I
n
{\displaystyle I_{n}}
is the identity matrix.
Task
Given some matrix of complex numbers, find its conjugate transpose.
Also determine if the matrix is a:
Hermitian matrix,
normal matrix, or
unitary matrix.
See also
MathWorld entry: conjugate transpose
MathWorld entry: Hermitian matrix
MathWorld entry: normal matrix
MathWorld entry: unitary matrix
| #Factor | Factor | USING: kernel math.functions math.matrices sequences ;
IN: rosetta.hermitian
: conj-t ( matrix -- conjugate-transpose )
flip [ [ conjugate ] map ] map ;
: hermitian-matrix? ( matrix -- ? )
dup conj-t = ;
: normal-matrix? ( matrix -- ? )
dup conj-t [ m. ] [ swap m. ] 2bi = ;
: unitary-matrix? ( matrix -- ? )
[ dup conj-t m. ] [ length identity-matrix ] bi = ; |
http://rosettacode.org/wiki/Conjugate_transpose | Conjugate transpose | Suppose that a matrix
M
{\displaystyle M}
contains complex numbers. Then the conjugate transpose of
M
{\displaystyle M}
is a matrix
M
H
{\displaystyle M^{H}}
containing the complex conjugates of the matrix transposition of
M
{\displaystyle M}
.
(
M
H
)
j
i
=
M
i
j
¯
{\displaystyle (M^{H})_{ji}={\overline {M_{ij}}}}
This means that row
j
{\displaystyle j}
, column
i
{\displaystyle i}
of the conjugate transpose equals the
complex conjugate of row
i
{\displaystyle i}
, column
j
{\displaystyle j}
of the original matrix.
In the next list,
M
{\displaystyle M}
must also be a square matrix.
A Hermitian matrix equals its own conjugate transpose:
M
H
=
M
{\displaystyle M^{H}=M}
.
A normal matrix is commutative in multiplication with its conjugate transpose:
M
H
M
=
M
M
H
{\displaystyle M^{H}M=MM^{H}}
.
A unitary matrix has its inverse equal to its conjugate transpose:
M
H
=
M
−
1
{\displaystyle M^{H}=M^{-1}}
.
This is true iff
M
H
M
=
I
n
{\displaystyle M^{H}M=I_{n}}
and iff
M
M
H
=
I
n
{\displaystyle MM^{H}=I_{n}}
, where
I
n
{\displaystyle I_{n}}
is the identity matrix.
Task
Given some matrix of complex numbers, find its conjugate transpose.
Also determine if the matrix is a:
Hermitian matrix,
normal matrix, or
unitary matrix.
See also
MathWorld entry: conjugate transpose
MathWorld entry: Hermitian matrix
MathWorld entry: normal matrix
MathWorld entry: unitary matrix
| #Fortran | Fortran | gfortran -std=f2008 -Wall -fopenmp -ffree-form -fall-intrinsics -fimplicit-none f.f08 -o f |
http://rosettacode.org/wiki/Compound_data_type | Compound data type |
Data Structure
This illustrates a data structure, a means of storing data within a program.
You may see other such structures in the Data Structures category.
Task
Create a compound data type:
Point(x,y)
A compound data type is one that holds multiple independent values.
Related task
Enumeration
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
| #AmigaE | AmigaE | OBJECT point
x, y
ENDOBJECT
PROC main()
DEF pt:PTR TO point,
NEW pt
-> Floats are also stored as integer types making
-> the float conversion operator necessary.
pt.x := !10.4
pt.y := !3.14
END pt
ENDPROC |
http://rosettacode.org/wiki/Compound_data_type | Compound data type |
Data Structure
This illustrates a data structure, a means of storing data within a program.
You may see other such structures in the Data Structures category.
Task
Create a compound data type:
Point(x,y)
A compound data type is one that holds multiple independent values.
Related task
Enumeration
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
| #ARM_Assembly | ARM Assembly |
/* ARM assembly Raspberry PI */
/* program structure.s */
/************************************/
/* Constantes */
/************************************/
.equ STDOUT, 1 @ Linux output console
.equ EXIT, 1 @ Linux syscall
.equ WRITE, 4 @ Linux syscall
/*******************************************/
/* Structures */
/********************************************/
.struct 0
point_x: @ x coordinate
.struct point_x + 4
point_y: @ y coordinate
.struct point_y + 4
point_end: @ end structure point
/*********************************/
/* Initialized data */
/*********************************/
.data
sMessResult: .ascii "value x : "
sMessValeur: .fill 11, 1, ' ' @ size => 11
szCarriageReturn: .asciz "\n"
/*********************************/
/* UnInitialized data */
/*********************************/
.bss
stPoint: .skip point_end @ reservation place in memory
/*********************************/
/* code section */
/*********************************/
.text
.global main
main: @ entry of program
ldr r1,iAdrstPoint
mov r0,#5 @ x value
str r0,[r1,#point_x]
mov r0,#10 @ y value
str r0,[r1,#point_y]
@ display value
ldr r2,iAdrstPoint
ldr r0,[r2,#point_x]
ldr r1,iAdrsMessValeur
bl conversion10 @ call conversion decimal
ldr r0,iAdrsMessResult
bl affichageMess @ display message
100: @ standard end of the program
mov r0, #0 @ return code
mov r7, #EXIT @ request to exit program
svc #0 @ perform the system call
iAdrsMessValeur: .int sMessValeur
iAdrszCarriageReturn: .int szCarriageReturn
iAdrsMessResult: .int sMessResult
iAdrstPoint: .int stPoint
/******************************************************************/
/* display text with size calculation */
/******************************************************************/
/* r0 contains the address of the message */
affichageMess:
push {r0,r1,r2,r7,lr} @ save registres
mov r2,#0 @ counter length
1: @ loop length calculation
ldrb r1,[r0,r2] @ read octet start position + index
cmp r1,#0 @ if 0 its over
addne r2,r2,#1 @ else add 1 in the length
bne 1b @ and loop
@ so here r2 contains the length of the message
mov r1,r0 @ address message in r1
mov r0,#STDOUT @ code to write to the standard output Linux
mov r7, #WRITE @ code call system "write"
svc #0 @ call systeme
pop {r0,r1,r2,r7,lr} @ restaur des 2 registres */
bx lr @ return
/******************************************************************/
/* Converting a register to a decimal unsigned */
/******************************************************************/
/* r0 contains value and r1 address area */
/* r0 return size of result (no zero final in area) */
/* area size => 11 bytes */
.equ LGZONECAL, 10
conversion10:
push {r1-r4,lr} @ save registers
mov r3,r1
mov r2,#LGZONECAL
1: @ start loop
bl divisionpar10U @ unsigned r0 <- dividende. quotient ->r0 reste -> r1
add r1,#48 @ digit
strb r1,[r3,r2] @ store digit on area
cmp r0,#0 @ stop if quotient = 0
subne r2,#1 @ else previous position
bne 1b @ and loop
@ and move digit from left of area
mov r4,#0
2:
ldrb r1,[r3,r2]
strb r1,[r3,r4]
add r2,#1
add r4,#1
cmp r2,#LGZONECAL
ble 2b
@ and move spaces in end on area
mov r0,r4 @ result length
mov r1,#' ' @ space
3:
strb r1,[r3,r4] @ store space in area
add r4,#1 @ next position
cmp r4,#LGZONECAL
ble 3b @ loop if r4 <= area size
100:
pop {r1-r4,lr} @ restaur registres
bx lr @return
/***************************************************/
/* division par 10 unsigned */
/***************************************************/
/* r0 dividende */
/* r0 quotient */
/* r1 remainder */
divisionpar10U:
push {r2,r3,r4, lr}
mov r4,r0 @ save value
ldr r3,iMagicNumber @ r3 <- magic_number raspberry 1 2
umull r1, r2, r3, r0 @ r1<- Lower32Bits(r1*r0) r2<- Upper32Bits(r1*r0)
mov r0, r2, LSR #3 @ r2 <- r2 >> shift 3
add r2,r0,r0, lsl #2 @ r2 <- r0 * 5
sub r1,r4,r2, lsl #1 @ r1 <- r4 - (r2 * 2) = r4 - (r0 * 10)
pop {r2,r3,r4,lr}
bx lr @ leave function
iMagicNumber: .int 0xCCCCCCCD
|
http://rosettacode.org/wiki/Continued_fraction | Continued fraction | continued fraction
Mathworld
a
0
+
b
1
a
1
+
b
2
a
2
+
b
3
a
3
+
⋱
{\displaystyle a_{0}+{\cfrac {b_{1}}{a_{1}+{\cfrac {b_{2}}{a_{2}+{\cfrac {b_{3}}{a_{3}+\ddots }}}}}}}
The task is to write a program which generates such a number and prints a real representation of it. The code should be tested by calculating and printing the square root of 2, Napier's Constant, and Pi, using the following coefficients:
For the square root of 2, use
a
0
=
1
{\displaystyle a_{0}=1}
then
a
N
=
2
{\displaystyle a_{N}=2}
.
b
N
{\displaystyle b_{N}}
is always
1
{\displaystyle 1}
.
2
=
1
+
1
2
+
1
2
+
1
2
+
⋱
{\displaystyle {\sqrt {2}}=1+{\cfrac {1}{2+{\cfrac {1}{2+{\cfrac {1}{2+\ddots }}}}}}}
For Napier's Constant, use
a
0
=
2
{\displaystyle a_{0}=2}
, then
a
N
=
N
{\displaystyle a_{N}=N}
.
b
1
=
1
{\displaystyle b_{1}=1}
then
b
N
=
N
−
1
{\displaystyle b_{N}=N-1}
.
e
=
2
+
1
1
+
1
2
+
2
3
+
3
4
+
⋱
{\displaystyle e=2+{\cfrac {1}{1+{\cfrac {1}{2+{\cfrac {2}{3+{\cfrac {3}{4+\ddots }}}}}}}}}
For Pi, use
a
0
=
3
{\displaystyle a_{0}=3}
then
a
N
=
6
{\displaystyle a_{N}=6}
.
b
N
=
(
2
N
−
1
)
2
{\displaystyle b_{N}=(2N-1)^{2}}
.
π
=
3
+
1
6
+
9
6
+
25
6
+
⋱
{\displaystyle \pi =3+{\cfrac {1}{6+{\cfrac {9}{6+{\cfrac {25}{6+\ddots }}}}}}}
See also
Continued fraction/Arithmetic for tasks that do arithmetic over continued fractions.
| #Maple | Maple |
contfrac:=n->evalf(Value(NumberTheory:-ContinuedFraction(n)));
contfrac(2^(0.5));
contfrac(Pi);
contfrac(exp(1));
|
http://rosettacode.org/wiki/Continued_fraction | Continued fraction | continued fraction
Mathworld
a
0
+
b
1
a
1
+
b
2
a
2
+
b
3
a
3
+
⋱
{\displaystyle a_{0}+{\cfrac {b_{1}}{a_{1}+{\cfrac {b_{2}}{a_{2}+{\cfrac {b_{3}}{a_{3}+\ddots }}}}}}}
The task is to write a program which generates such a number and prints a real representation of it. The code should be tested by calculating and printing the square root of 2, Napier's Constant, and Pi, using the following coefficients:
For the square root of 2, use
a
0
=
1
{\displaystyle a_{0}=1}
then
a
N
=
2
{\displaystyle a_{N}=2}
.
b
N
{\displaystyle b_{N}}
is always
1
{\displaystyle 1}
.
2
=
1
+
1
2
+
1
2
+
1
2
+
⋱
{\displaystyle {\sqrt {2}}=1+{\cfrac {1}{2+{\cfrac {1}{2+{\cfrac {1}{2+\ddots }}}}}}}
For Napier's Constant, use
a
0
=
2
{\displaystyle a_{0}=2}
, then
a
N
=
N
{\displaystyle a_{N}=N}
.
b
1
=
1
{\displaystyle b_{1}=1}
then
b
N
=
N
−
1
{\displaystyle b_{N}=N-1}
.
e
=
2
+
1
1
+
1
2
+
2
3
+
3
4
+
⋱
{\displaystyle e=2+{\cfrac {1}{1+{\cfrac {1}{2+{\cfrac {2}{3+{\cfrac {3}{4+\ddots }}}}}}}}}
For Pi, use
a
0
=
3
{\displaystyle a_{0}=3}
then
a
N
=
6
{\displaystyle a_{N}=6}
.
b
N
=
(
2
N
−
1
)
2
{\displaystyle b_{N}=(2N-1)^{2}}
.
π
=
3
+
1
6
+
9
6
+
25
6
+
⋱
{\displaystyle \pi =3+{\cfrac {1}{6+{\cfrac {9}{6+{\cfrac {25}{6+\ddots }}}}}}}
See also
Continued fraction/Arithmetic for tasks that do arithmetic over continued fractions.
| #Mathematica_.2F_Wolfram_Language | Mathematica / Wolfram Language | sqrt2=Function[n,{1,Transpose@{Array[2&,n],Array[1&,n]}}];
napier=Function[n,{2,Transpose@{Range[n],Prepend[Range[n-1],1]}}];
pi=Function[n,{3,Transpose@{Array[6&,n],Array[(2#-1)^2&,n]}}];
approx=Function[l,
N[Divide@@First@Fold[{{#2.#[[;;,1]],#2.#[[;;,2]]},#[[1]]}&,{{l[[2,1,1]]l[[1]]+l[[2,1,2]],l[[2,1,1]]},{l[[1]],1}},l[[2,2;;]]],10]];
r2=approx/@{sqrt2@#,napier@#,pi@#}&@10000;r2//TableForm |
http://rosettacode.org/wiki/Copy_a_string | Copy a string | This task is about copying a string.
Task
Where it is relevant, distinguish between copying the contents of a string
versus making an additional reference to an existing string.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #MiniScript | MiniScript | phrase = "hi"
copy = phrase
print phrase
print copy |
http://rosettacode.org/wiki/Copy_a_string | Copy a string | This task is about copying a string.
Task
Where it is relevant, distinguish between copying the contents of a string
versus making an additional reference to an existing string.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #MIPS_Assembly | MIPS Assembly | .data
.text
strcpy:
addi $sp, $sp, -4
sw $s0, 0($sp)
add $s0, $zero, $zero
L1:
add $t1, $s0, $a1
lb $t2, 0($t1)
add $t3, $s0, $a0
sb $t2, 0($t3)
beq $t2, $zero, L2
addi $s0, $s0, 1
j L1
L2:
lw $s0, 0($sp)
addi $sp, $sp, 4
jr $ra
|
http://rosettacode.org/wiki/Constrained_random_points_on_a_circle | Constrained random points on a circle | Task
Generate 100 <x,y> coordinate pairs such that x and y are integers sampled from the uniform distribution with the condition that
10
≤
x
2
+
y
2
≤
15
{\displaystyle 10\leq {\sqrt {x^{2}+y^{2}}}\leq 15}
.
Then display/plot them. The outcome should be a "fuzzy" circle. The actual number of points plotted may be less than 100, given that some pairs may be generated more than once.
There are several possible approaches to accomplish this. Here are two possible algorithms.
1) Generate random pairs of integers and filter out those that don't satisfy this condition:
10
≤
x
2
+
y
2
≤
15
{\displaystyle 10\leq {\sqrt {x^{2}+y^{2}}}\leq 15}
.
2) Precalculate the set of all possible points (there are 404 of them) and select randomly from this set.
| #Frink | Frink | g = new graphics
count = 0
do
{
x = random[-15,15]
y = random[-15,15]
r = sqrt[x^2 + y^2]
if 10 <= r and r <= 15
{
count = count + 1
g.fillEllipseCenter[x,y,.3, .3]
}
} while count < 100
g.show[] |
http://rosettacode.org/wiki/Convex_hull | Convex hull | Find the points which form a convex hull from a set of arbitrary two dimensional points.
For example, given the points (16,3), (12,17), (0,6), (-4,-6), (16,6), (16,-7), (16,-3), (17,-4), (5,19), (19,-8), (3,16), (12,13), (3,-4), (17,5), (-3,15), (-3,-9), (0,11), (-9,-3), (-4,-2) and (12,10) the convex hull would be (-9,-3), (-3,-9), (19,-8), (17,5), (12,17), (5,19) and (-3,15).
See also
Convex Hull (youtube)
http://www.geeksforgeeks.org/convex-hull-set-2-graham-scan/
| #Kotlin | Kotlin | // version 1.1.3
class Point(val x: Int, val y: Int) : Comparable<Point> {
override fun compareTo(other: Point) = this.x.compareTo(other.x)
override fun toString() = "($x, $y)"
}
fun convexHull(p: Array<Point>): List<Point> {
if (p.isEmpty()) return emptyList()
p.sort()
val h = mutableListOf<Point>()
// lower hull
for (pt in p) {
while (h.size >= 2 && !ccw(h[h.size - 2], h.last(), pt)) {
h.removeAt(h.lastIndex)
}
h.add(pt)
}
// upper hull
val t = h.size + 1
for (i in p.size - 2 downTo 0) {
val pt = p[i]
while (h.size >= t && !ccw(h[h.size - 2], h.last(), pt)) {
h.removeAt(h.lastIndex)
}
h.add(pt)
}
h.removeAt(h.lastIndex)
return h
}
/* ccw returns true if the three points make a counter-clockwise turn */
fun ccw(a: Point, b: Point, c: Point) =
((b.x - a.x) * (c.y - a.y)) > ((b.y - a.y) * (c.x - a.x))
fun main(args: Array<String>) {
val points = arrayOf(
Point(16, 3), Point(12, 17), Point( 0, 6), Point(-4, -6), Point(16, 6),
Point(16, -7), Point(16, -3), Point(17, -4), Point( 5, 19), Point(19, -8),
Point( 3, 16), Point(12, 13), Point( 3, -4), Point(17, 5), Point(-3, 15),
Point(-3, -9), Point( 0, 11), Point(-9, -3), Point(-4, -2), Point(12, 10)
)
val hull = convexHull(points)
println("Convex Hull: $hull")
} |
http://rosettacode.org/wiki/Convert_seconds_to_compound_duration | Convert seconds to compound duration | Task
Write a function or program which:
takes a positive integer representing a duration in seconds as input (e.g., 100), and
returns a string which shows the same duration decomposed into:
weeks,
days,
hours,
minutes, and
seconds.
This is detailed below (e.g., "2 hr, 59 sec").
Demonstrate that it passes the following three test-cases:
Test Cases
input number
output string
7259
2 hr, 59 sec
86400
1 d
6000000
9 wk, 6 d, 10 hr, 40 min
Details
The following five units should be used:
unit
suffix used in output
conversion
week
wk
1 week = 7 days
day
d
1 day = 24 hours
hour
hr
1 hour = 60 minutes
minute
min
1 minute = 60 seconds
second
sec
However, only include quantities with non-zero values in the output (e.g., return "1 d" and not "0 wk, 1 d, 0 hr, 0 min, 0 sec").
Give larger units precedence over smaller ones as much as possible (e.g., return 2 min, 10 sec and not 1 min, 70 sec or 130 sec)
Mimic the formatting shown in the test-cases (quantities sorted from largest unit to smallest and separated by comma+space; value and unit of each quantity separated by space).
| #Nim | Nim | from strutils import addSep
const
Units = [" wk", " d", " hr", " min", " sec"]
Quantities = [7 * 24 * 60 * 60, 24 * 60 * 60, 60 * 60, 60, 1]
#---------------------------------------------------------------------------------------------------
proc `$$`*(sec: int): string =
## Convert a duration in seconds to a friendly string.
doAssert(sec > 0)
var duration = sec
var idx = 0
while duration != 0:
let q = duration div Quantities[idx]
if q != 0:
duration = duration mod Quantities[idx]
result.addSep(", ", 0)
result.add($q & Units[idx])
inc idx
#———————————————————————————————————————————————————————————————————————————————————————————————————
when isMainModule:
for sec in [7259, 86400, 6000000]:
echo sec, "s = ", $$sec |
http://rosettacode.org/wiki/Convert_seconds_to_compound_duration | Convert seconds to compound duration | Task
Write a function or program which:
takes a positive integer representing a duration in seconds as input (e.g., 100), and
returns a string which shows the same duration decomposed into:
weeks,
days,
hours,
minutes, and
seconds.
This is detailed below (e.g., "2 hr, 59 sec").
Demonstrate that it passes the following three test-cases:
Test Cases
input number
output string
7259
2 hr, 59 sec
86400
1 d
6000000
9 wk, 6 d, 10 hr, 40 min
Details
The following five units should be used:
unit
suffix used in output
conversion
week
wk
1 week = 7 days
day
d
1 day = 24 hours
hour
hr
1 hour = 60 minutes
minute
min
1 minute = 60 seconds
second
sec
However, only include quantities with non-zero values in the output (e.g., return "1 d" and not "0 wk, 1 d, 0 hr, 0 min, 0 sec").
Give larger units precedence over smaller ones as much as possible (e.g., return 2 min, 10 sec and not 1 min, 70 sec or 130 sec)
Mimic the formatting shown in the test-cases (quantities sorted from largest unit to smallest and separated by comma+space; value and unit of each quantity separated by space).
| #OCaml | OCaml | let divisors = [
(max_int, "wk"); (* many wk = many wk *)
(7, "d"); (* 7 d = 1 wk *)
(24, "hr"); (* 24 hr = 1 d *)
(60, "min"); (* 60 min = 1 hr *)
(60, "sec") (* 60 sec = 1 min *)
]
(* Convert a number of seconds into a list of values for weeks, days, hours,
* minutes and seconds, by dividing the number of seconds 'secs' successively by
* the values contained in the list 'divisors' (taking them in reverse order).
* Ex:
* compute_duration 7259
* returns
* [(0, "wk"); (0, "d"); (2, "hr") (0, "min"); (59, "sec")]
*)
let compute_duration secs =
let rec doloop remain res = function
| [] -> res
| (n, s) :: ds -> doloop (remain / n) ((remain mod n, s) :: res) ds
in
doloop secs [] (List.rev divisors)
(* Format nicely the list of values.
* Ex:
* pretty_print [(0, "wk"); (0, "d"); (2, "hr") (0, "min"); (59, "sec")]
* returns
* "2 hr, 59 sec"
*
* Intermediate steps:
* 1. Keep only the pairs where duration is not 0
* [(2, "hr"); (59, "sec")]
* 2. Format each pair as a string
* ["2 hr"; "59 sec"]
* 3. Concatenate the strings separating them by a comma+space
* "2 hr, 59 sec"
*)
let pretty_print dur =
List.filter (fun (d, _) -> d <> 0) dur
|> List.map (fun (d, l) -> Printf.sprintf "%d %s" d l)
|> String.concat ", "
(* Transform a number of seconds into the corresponding compound duration
* string.
* Not sure what to do with 0... *)
let compound = function
| n when n > 0 -> compute_duration n |> pretty_print
| n when n = 0 -> string_of_int 0 ^ "..."
| _ -> invalid_arg "Number of seconds must be positive"
(* Some testing... *)
let () =
let test_cases = [
(7259, "2 hr, 59 sec");
(86400, "1 d");
(6000000, "9 wk, 6 d, 10 hr, 40 min");
(0, "0...");
(3599, "59 min, 59 sec");
(3600, "1 hr");
(3601, "1 hr, 1 sec")
] in
let testit (n, s) =
let calc = compound n in
Printf.printf "[%s] %d seconds -> %s; expected: %s\n"
(if calc = s then "PASS" else "FAIL")
n calc s
in
List.iter testit test_cases |
http://rosettacode.org/wiki/Concurrent_computing | Concurrent computing | Task
Using either native language concurrency syntax or freely available libraries, write a program to display the strings "Enjoy" "Rosetta" "Code", one string per line, in random order.
Concurrency syntax must use threads, tasks, co-routines, or whatever concurrency is called in your language.
| #C.23 | C# |
static Random tRand = new Random();
static void Main(string[] args)
{
Thread t = new Thread(new ParameterizedThreadStart(WriteText));
t.Start("Enjoy");
t = new Thread(new ParameterizedThreadStart(WriteText));
t.Start("Rosetta");
t = new Thread(new ParameterizedThreadStart(WriteText));
t.Start("Code");
Console.ReadLine();
}
private static void WriteText(object p)
{
Thread.Sleep(tRand.Next(1000, 4000));
Console.WriteLine(p);
}
|
http://rosettacode.org/wiki/Concurrent_computing | Concurrent computing | Task
Using either native language concurrency syntax or freely available libraries, write a program to display the strings "Enjoy" "Rosetta" "Code", one string per line, in random order.
Concurrency syntax must use threads, tasks, co-routines, or whatever concurrency is called in your language.
| #C.2B.2B | C++ | #include <thread>
#include <iostream>
#include <vector>
#include <random>
#include <chrono>
int main()
{
std::random_device rd;
std::mt19937 eng(rd()); // mt19937 generator with a hardware random seed.
std::uniform_int_distribution<> dist(1,1000);
std::vector<std::thread> threads;
for(const auto& str: {"Enjoy\n", "Rosetta\n", "Code\n"}) {
// between 1 and 1000ms per our distribution
std::chrono::milliseconds duration(dist(eng));
threads.emplace_back([str, duration](){
std::this_thread::sleep_for(duration);
std::cout << str;
});
}
for(auto& t: threads) t.join();
return 0;
} |
http://rosettacode.org/wiki/Conjugate_transpose | Conjugate transpose | Suppose that a matrix
M
{\displaystyle M}
contains complex numbers. Then the conjugate transpose of
M
{\displaystyle M}
is a matrix
M
H
{\displaystyle M^{H}}
containing the complex conjugates of the matrix transposition of
M
{\displaystyle M}
.
(
M
H
)
j
i
=
M
i
j
¯
{\displaystyle (M^{H})_{ji}={\overline {M_{ij}}}}
This means that row
j
{\displaystyle j}
, column
i
{\displaystyle i}
of the conjugate transpose equals the
complex conjugate of row
i
{\displaystyle i}
, column
j
{\displaystyle j}
of the original matrix.
In the next list,
M
{\displaystyle M}
must also be a square matrix.
A Hermitian matrix equals its own conjugate transpose:
M
H
=
M
{\displaystyle M^{H}=M}
.
A normal matrix is commutative in multiplication with its conjugate transpose:
M
H
M
=
M
M
H
{\displaystyle M^{H}M=MM^{H}}
.
A unitary matrix has its inverse equal to its conjugate transpose:
M
H
=
M
−
1
{\displaystyle M^{H}=M^{-1}}
.
This is true iff
M
H
M
=
I
n
{\displaystyle M^{H}M=I_{n}}
and iff
M
M
H
=
I
n
{\displaystyle MM^{H}=I_{n}}
, where
I
n
{\displaystyle I_{n}}
is the identity matrix.
Task
Given some matrix of complex numbers, find its conjugate transpose.
Also determine if the matrix is a:
Hermitian matrix,
normal matrix, or
unitary matrix.
See also
MathWorld entry: conjugate transpose
MathWorld entry: Hermitian matrix
MathWorld entry: normal matrix
MathWorld entry: unitary matrix
| #FreeBASIC | FreeBASIC | 'complex type and operators for it
type complex
real as double
imag as double
end type
operator + ( a as complex, b as complex ) as complex
dim as complex r
r.real = a.real + b.real
r.imag = a.imag + b.imag
return r
end operator
operator * ( a as complex, b as complex ) as complex
dim as complex r
r.real = a.real*b.real - a.imag*b.imag
r.imag = a.real*b.imag + b.real*a.imag
return r
end operator
operator = ( a as complex, b as complex ) as boolean
if not a.real = b.real then return false
if not a.imag = b.imag then return false
return true
end operator
function complex_conjugate( a as complex ) as complex
dim as complex r
r.real = a.real
r.imag = -a.imag
return r
end function
'matrix type and operations for it
'reuses code from the matrix multiplication task
type Matrix
dim as complex m( any , any )
declare constructor ( )
declare constructor ( byval x as uinteger )
end type
constructor Matrix ( )
end constructor
constructor Matrix ( byval x as uinteger )
redim this.m( x - 1 , x - 1 )
end constructor
operator * ( byref a as Matrix , byref b as Matrix ) as Matrix
dim as Matrix ret
dim as uinteger i, j, k
redim ret.m( ubound( a.m , 1 ) , ubound( a.m , 1 ) )
for i = 0 to ubound( a.m , 1 )
for j = 0 to ubound( b.m , 2 )
for k = 0 to ubound( b.m , 1 )
ret.m( i , j ) += a.m( i , k ) * b.m( k , j )
next k
next j
next i
return ret
end operator
function conjugate_transpose( byref a as Matrix ) as Matrix
dim as Matrix ret
dim as uinteger i, j
redim ret.m( ubound( a.m , 1 ) , ubound( a.m , 1 ) )
for i = 0 to ubound( a.m , 1 )
for j = 0 to ubound( a.m , 2 )
ret.m( i, j ) = complex_conjugate(a.m( j, i ))
next j
next i
return ret
end function
'tests if matrices are unitary, hermitian, or normal
operator = (byref a as Matrix, byref b as matrix) as boolean
dim as integer i, j
if ubound(a.m, 1) <> ubound(b.m, 1) then return false
for i = 0 to ubound( a.m , 1 )
for j = 0 to ubound( a.m , 2 )
if not a.m(i,j)=b.m(i,j) then return false
next j
next i
return true
end operator
function is_identity( byref a as Matrix ) as boolean
dim as integer i, j
for i = 0 to ubound( a.m , 1 )
for j = 0 to ubound( a.m , 2 )
if i = j and ( not a.m(i,j).real = 1.0 or not a.m(i,j).imag = 0.0 ) then return false
if i <> j and ( not a.m(i,j).real = 0.0 or not a.m(i,j).imag = 0.0 ) then return false
next j
next i
return true
end function
function is_hermitian( byref a as Matrix ) as boolean
if a = conjugate_transpose(a) then return true
return false
end function
function is_normal( byref a as Matrix ) as boolean
dim as Matrix aa = conjugate_transpose(a)
if a*aa = aa*a then return true else return false
end function
function is_unitary( byref a as Matrix ) as boolean
dim as Matrix aa = conjugate_transpose(a)
if not is_identity( a*aa ) or not is_identity( aa*a ) then return false
return true
end function
'''now some example matrices
dim as Matrix A = Matrix(2) 'an identity matrix
A.m(0,0).real = 1.0 : A.m(0,0).imag = 0.0 : A.m(0,1).real = 0.0 : A.m(0,1).imag = 0.0
A.m(1,0).real = 0.0 : A.m(1,0).imag = 0.0 : A.m(1,1).real = 1.0 : A.m(1,1).imag = 0.0
dim as Matrix B = Matrix(2) 'a hermitian matrix
B.m(0,0).real = 1.0 : B.m(0,0).imag = 0.0 : B.m(0,1).real = 1.0 : B.m(0,1).imag = -1.0
B.m(1,0).real = 1.0 : B.m(1,0).imag = 1.0 : B.m(1,1).real = 1.0 : B.m(1,1).imag = 0.0
dim as Matrix C = Matrix(2) 'a random matrix
C.m(0,0).real = rnd : C.m(0,0).imag = rnd : C.m(0,1).real = rnd : C.m(0,1).imag = rnd
C.m(1,0).real = rnd : C.m(1,0).imag = rnd : C.m(1,1).real = rnd : C.m(1,1).imag = rnd
print is_hermitian(A), is_normal(A), is_unitary(A)
print is_hermitian(B), is_normal(B), is_unitary(B)
print is_hermitian(C), is_normal(C), is_unitary(C) |
http://rosettacode.org/wiki/Compound_data_type | Compound data type |
Data Structure
This illustrates a data structure, a means of storing data within a program.
You may see other such structures in the Data Structures category.
Task
Create a compound data type:
Point(x,y)
A compound data type is one that holds multiple independent values.
Related task
Enumeration
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
| #Arturo | Arturo | point: #[
x: 10
y: 20
]
print point |
http://rosettacode.org/wiki/Compound_data_type | Compound data type |
Data Structure
This illustrates a data structure, a means of storing data within a program.
You may see other such structures in the Data Structures category.
Task
Create a compound data type:
Point(x,y)
A compound data type is one that holds multiple independent values.
Related task
Enumeration
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
| #ATS | ATS | typedef point (t : t@ype+) = @(t, t)
val p : point double = (1.0, 3.0) |
http://rosettacode.org/wiki/Continued_fraction | Continued fraction | continued fraction
Mathworld
a
0
+
b
1
a
1
+
b
2
a
2
+
b
3
a
3
+
⋱
{\displaystyle a_{0}+{\cfrac {b_{1}}{a_{1}+{\cfrac {b_{2}}{a_{2}+{\cfrac {b_{3}}{a_{3}+\ddots }}}}}}}
The task is to write a program which generates such a number and prints a real representation of it. The code should be tested by calculating and printing the square root of 2, Napier's Constant, and Pi, using the following coefficients:
For the square root of 2, use
a
0
=
1
{\displaystyle a_{0}=1}
then
a
N
=
2
{\displaystyle a_{N}=2}
.
b
N
{\displaystyle b_{N}}
is always
1
{\displaystyle 1}
.
2
=
1
+
1
2
+
1
2
+
1
2
+
⋱
{\displaystyle {\sqrt {2}}=1+{\cfrac {1}{2+{\cfrac {1}{2+{\cfrac {1}{2+\ddots }}}}}}}
For Napier's Constant, use
a
0
=
2
{\displaystyle a_{0}=2}
, then
a
N
=
N
{\displaystyle a_{N}=N}
.
b
1
=
1
{\displaystyle b_{1}=1}
then
b
N
=
N
−
1
{\displaystyle b_{N}=N-1}
.
e
=
2
+
1
1
+
1
2
+
2
3
+
3
4
+
⋱
{\displaystyle e=2+{\cfrac {1}{1+{\cfrac {1}{2+{\cfrac {2}{3+{\cfrac {3}{4+\ddots }}}}}}}}}
For Pi, use
a
0
=
3
{\displaystyle a_{0}=3}
then
a
N
=
6
{\displaystyle a_{N}=6}
.
b
N
=
(
2
N
−
1
)
2
{\displaystyle b_{N}=(2N-1)^{2}}
.
π
=
3
+
1
6
+
9
6
+
25
6
+
⋱
{\displaystyle \pi =3+{\cfrac {1}{6+{\cfrac {9}{6+{\cfrac {25}{6+\ddots }}}}}}}
See also
Continued fraction/Arithmetic for tasks that do arithmetic over continued fractions.
| #Maxima | Maxima | cfeval(x) := block([a, b, n, z], a: x[1], b: x[2], n: length(a), z: 0,
for i from n step -1 thru 2 do z: b[i]/(a[i] + z), a[1] + z)$
cf_sqrt2(n) := [cons(1, makelist(2, i, 2, n)), cons(0, makelist(1, i, 2, n))]$
cf_e(n) := [cons(2, makelist(i, i, 1, n - 1)), append([0, 1], makelist(i, i, 1, n - 2))]$
cf_pi(n) := [cons(3, makelist(6, i, 2, n)), cons(0, makelist((2*i - 1)^2, i, 1, n - 1))]$
cfeval(cf_sqrt2(20)), numer; /* 1.414213562373097 */
% - sqrt(2), numer; /* 1.3322676295501878*10^-15 */
cfeval(cf_e(20)), numer; /* 2.718281828459046 */
% - %e, numer; /* 4.4408920985006262*10^-16 */
cfeval(cf_pi(20)), numer; /* 3.141623806667839 */
% - %pi, numer; /* 3.115307804568701*10^-5 */
/* convergence is much slower for pi */
fpprec: 20$
x: cfeval(cf_pi(10000))$
bfloat(x - %pi); /* 2.4999999900104930006b-13 */ |
http://rosettacode.org/wiki/Continued_fraction | Continued fraction | continued fraction
Mathworld
a
0
+
b
1
a
1
+
b
2
a
2
+
b
3
a
3
+
⋱
{\displaystyle a_{0}+{\cfrac {b_{1}}{a_{1}+{\cfrac {b_{2}}{a_{2}+{\cfrac {b_{3}}{a_{3}+\ddots }}}}}}}
The task is to write a program which generates such a number and prints a real representation of it. The code should be tested by calculating and printing the square root of 2, Napier's Constant, and Pi, using the following coefficients:
For the square root of 2, use
a
0
=
1
{\displaystyle a_{0}=1}
then
a
N
=
2
{\displaystyle a_{N}=2}
.
b
N
{\displaystyle b_{N}}
is always
1
{\displaystyle 1}
.
2
=
1
+
1
2
+
1
2
+
1
2
+
⋱
{\displaystyle {\sqrt {2}}=1+{\cfrac {1}{2+{\cfrac {1}{2+{\cfrac {1}{2+\ddots }}}}}}}
For Napier's Constant, use
a
0
=
2
{\displaystyle a_{0}=2}
, then
a
N
=
N
{\displaystyle a_{N}=N}
.
b
1
=
1
{\displaystyle b_{1}=1}
then
b
N
=
N
−
1
{\displaystyle b_{N}=N-1}
.
e
=
2
+
1
1
+
1
2
+
2
3
+
3
4
+
⋱
{\displaystyle e=2+{\cfrac {1}{1+{\cfrac {1}{2+{\cfrac {2}{3+{\cfrac {3}{4+\ddots }}}}}}}}}
For Pi, use
a
0
=
3
{\displaystyle a_{0}=3}
then
a
N
=
6
{\displaystyle a_{N}=6}
.
b
N
=
(
2
N
−
1
)
2
{\displaystyle b_{N}=(2N-1)^{2}}
.
π
=
3
+
1
6
+
9
6
+
25
6
+
⋱
{\displaystyle \pi =3+{\cfrac {1}{6+{\cfrac {9}{6+{\cfrac {25}{6+\ddots }}}}}}}
See also
Continued fraction/Arithmetic for tasks that do arithmetic over continued fractions.
| #NetRexx | NetRexx | /* REXX ***************************************************************
* Derived from REXX ... Derived from PL/I with a little "massage"
* SQRT2= 1.41421356237309505 <- PL/I Result
* 1.41421356237309504880168872421 <- NetRexx Result 30 digits
* NAPIER= 2.71828182845904524
* 2.71828182845904523536028747135
* PI= 3.14159262280484695
* 3.14159262280484694855146925223
* 07.09.2012 Walter Pachl
* 08.09.2012 Walter Pachl simplified (with the help of a friend)
**********************************************************************/
options replace format comments java crossref savelog symbols
class CFB public
properties static
Numeric Digits 30
Sqrt2 =1
napier=2
pi =3
a =0
b =0
method main(args = String[]) public static
Say 'SQRT2='.left(7) calc(sqrt2, 200)
Say 'NAPIER='.left(7) calc(napier, 200)
Say 'PI='.left(7) calc(pi, 200)
Return
method get_Coeffs(form,n) public static
select
when form=Sqrt2 Then do
if n > 0 then a = 2; else a = 1
b = 1
end
when form=Napier Then do
if n > 0 then a = n; else a = 2
if n > 1 then b = n - 1; else b = 1
end
when form=pi Then do
if n > 0 then a = 6; else a = 3
b = (2*n - 1)**2
end
end
Return
method calc(form,n) public static
temp=0
loop ni = n to 1 by -1
Get_Coeffs(form,ni)
temp = b/(a + temp)
end
Get_Coeffs(form,0)
return (a + temp) |
http://rosettacode.org/wiki/Copy_a_string | Copy a string | This task is about copying a string.
Task
Where it is relevant, distinguish between copying the contents of a string
versus making an additional reference to an existing string.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Mirah | Mirah | src = "Hello"
new_alias = src
puts 'interned strings are equal' if src == new_alias
str_copy = String.new(src)
puts 'non-interned strings are not equal' if str_copy != src
puts 'compare strings with equals()' if str_copy.equals(src)
|
http://rosettacode.org/wiki/Copy_a_string | Copy a string | This task is about copying a string.
Task
Where it is relevant, distinguish between copying the contents of a string
versus making an additional reference to an existing string.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Modula-3 | Modula-3 | VAR src: TEXT := "Foo";
VAR dst: TEXT := src; |
http://rosettacode.org/wiki/Constrained_random_points_on_a_circle | Constrained random points on a circle | Task
Generate 100 <x,y> coordinate pairs such that x and y are integers sampled from the uniform distribution with the condition that
10
≤
x
2
+
y
2
≤
15
{\displaystyle 10\leq {\sqrt {x^{2}+y^{2}}}\leq 15}
.
Then display/plot them. The outcome should be a "fuzzy" circle. The actual number of points plotted may be less than 100, given that some pairs may be generated more than once.
There are several possible approaches to accomplish this. Here are two possible algorithms.
1) Generate random pairs of integers and filter out those that don't satisfy this condition:
10
≤
x
2
+
y
2
≤
15
{\displaystyle 10\leq {\sqrt {x^{2}+y^{2}}}\leq 15}
.
2) Precalculate the set of all possible points (there are 404 of them) and select randomly from this set.
| #gnuplot | gnuplot |
## Ring of random points 2/18/17 aev
reset
fn="RingRandPntsGnu";
ttl="Ring of random points"
ofn=fn.".png"; lim=1000;
randgp(top) = floor(rand(0)*top)
set terminal png font arial 12 size 640,640
set output ofn
set title ttl font "Arial:Bold,12"
unset key;
set size square
set parametric
set xrange [-20:20]; set yrange [-20:20];
set style line 1 lt rgb "red"
$rring << EOD
EOD
set print $rring append
do for [i=1:lim] {
x=randgp(30); y=randgp(30);
r=sqrt(x**2+y**2);
if (r>=10&&r<=15) \
{print x," ",y; print -x," ",-y;print x," ",-y; print -x," ",y;}
}
plot [0:2*pi] sin(t)*10,cos(t)*10, sin(t)*15,cos(t)*15 ls 1,\
$rring using 1:2 with points pt 7 ps 0.5 lc "black"
set output
unset print
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.