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/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/
| #Lua | Lua | function print_point(p)
io.write("("..p.x..", "..p.y..")")
return nil
end
function print_points(pl)
io.write("[")
for i,p in pairs(pl) do
if i>1 then
io.write(", ")
end
print_point(p)
end
io.write("]")
return nil
end
function ccw(a,b,c)
return (b.x - a.x) * (c.y - a.y) > (b.y - a.y) * (c.x - a.x)
end
function pop_back(ta)
table.remove(ta,#ta)
return ta
end
function convexHull(pl)
if #pl == 0 then
return {}
end
table.sort(pl, function(left,right)
return left.x < right.x
end)
local h = {}
-- lower hull
for i,pt in pairs(pl) do
while #h >= 2 and not ccw(h[#h-1], h[#h], pt) do
table.remove(h,#h)
end
table.insert(h,pt)
end
-- upper hull
local t = #h + 1
for i=#pl, 1, -1 do
local pt = pl[i]
while #h >= t and not ccw(h[#h-1], h[#h], pt) do
table.remove(h,#h)
end
table.insert(h,pt)
end
table.remove(h,#h)
return h
end
-- main
local points = {
{x=16,y= 3},{x=12,y=17},{x= 0,y= 6},{x=-4,y=-6},{x=16,y= 6},
{x=16,y=-7},{x=16,y=-3},{x=17,y=-4},{x= 5,y=19},{x=19,y=-8},
{x= 3,y=16},{x=12,y=13},{x= 3,y=-4},{x=17,y= 5},{x=-3,y=15},
{x=-3,y=-9},{x= 0,y=11},{x=-9,y=-3},{x=-4,y=-2},{x=12,y=10}
}
local hull = convexHull(points)
io.write("Convex Hull: ")
print_points(hull)
print() |
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).
| #PARI.2FGP | PARI/GP |
\\ Convert seconds to compound duration
\\ 4/11/16 aev
secs2compdur(secs)={
my(us=[604800,86400,3600,60,1],ut=[" wk, "," d, "," hr, "," min, "," sec"],
cd=[0,0,0,0,0],u,cdt="");
for(i=1,5, u=secs\us[i]; if(u==0, next, cd[i]=u; secs-=us[i]*cd[i]));
for(i=1,5, if(cd[i]==0, next, cdt=Str(cdt,cd[i],ut[i])));
if(ssubstr(cdt,#cdt-1,1)==",", cdt=ssubstr(cdt,1,#cdt-2));
return(cdt);
}
{\\ Required tests:
print(secs2compdur(7259));
print(secs2compdur(86400));
print(secs2compdur(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.
| #Cind | Cind |
execute() {
{# host.println("Enjoy");
# host.println("Rosetta");
# host.println("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.
| #Clojure | Clojure | (doseq [text ["Enjoy" "Rosetta" "Code"]]
(future (println text))) |
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
| #Go | Go | package main
import (
"fmt"
"math"
"math/cmplx"
)
// a type to represent matrices
type matrix struct {
ele []complex128
cols int
}
// conjugate transpose, implemented here as a method on the matrix type.
func (m *matrix) conjTranspose() *matrix {
r := &matrix{make([]complex128, len(m.ele)), len(m.ele) / m.cols}
rx := 0
for _, e := range m.ele {
r.ele[rx] = cmplx.Conj(e)
rx += r.cols
if rx >= len(r.ele) {
rx -= len(r.ele) - 1
}
}
return r
}
// program to demonstrate capabilites on example matricies
func main() {
show("h", matrixFromRows([][]complex128{
{3, 2 + 1i},
{2 - 1i, 1}}))
show("n", matrixFromRows([][]complex128{
{1, 1, 0},
{0, 1, 1},
{1, 0, 1}}))
show("u", matrixFromRows([][]complex128{
{math.Sqrt2 / 2, math.Sqrt2 / 2, 0},
{math.Sqrt2 / -2i, math.Sqrt2 / 2i, 0},
{0, 0, 1i}}))
}
func show(name string, m *matrix) {
m.print(name)
ct := m.conjTranspose()
ct.print(name + "_ct")
fmt.Println("Hermitian:", m.equal(ct, 1e-14))
mct := m.mult(ct)
ctm := ct.mult(m)
fmt.Println("Normal:", mct.equal(ctm, 1e-14))
i := eye(m.cols)
fmt.Println("Unitary:", mct.equal(i, 1e-14) && ctm.equal(i, 1e-14))
}
// two constructors
func matrixFromRows(rows [][]complex128) *matrix {
m := &matrix{make([]complex128, len(rows)*len(rows[0])), len(rows[0])}
for rx, row := range rows {
copy(m.ele[rx*m.cols:(rx+1)*m.cols], row)
}
return m
}
func eye(n int) *matrix {
r := &matrix{make([]complex128, n*n), n}
n++
for x := 0; x < len(r.ele); x += n {
r.ele[x] = 1
}
return r
}
// print method outputs matrix to stdout
func (m *matrix) print(heading string) {
fmt.Print("\n", heading, "\n")
for e := 0; e < len(m.ele); e += m.cols {
fmt.Printf("%6.3f ", m.ele[e:e+m.cols])
fmt.Println()
}
}
// equal method uses ε to allow for floating point error.
func (a *matrix) equal(b *matrix, ε float64) bool {
for x, aEle := range a.ele {
if math.Abs(real(aEle)-real(b.ele[x])) > math.Abs(real(aEle))*ε ||
math.Abs(imag(aEle)-imag(b.ele[x])) > math.Abs(imag(aEle))*ε {
return false
}
}
return true
}
// mult method taken from matrix multiply task
func (m1 *matrix) mult(m2 *matrix) (m3 *matrix) {
m3 = &matrix{make([]complex128, (len(m1.ele)/m1.cols)*m2.cols), m2.cols}
for m1c0, m3x := 0, 0; m1c0 < len(m1.ele); m1c0 += m1.cols {
for m2r0 := 0; m2r0 < m2.cols; m2r0++ {
for m1x, m2x := m1c0, m2r0; m2x < len(m2.ele); m2x += m2.cols {
m3.ele[m3x] += m1.ele[m1x] * m2.ele[m2x]
m1x++
}
m3x++
}
}
return m3
} |
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
| #AutoHotkey | AutoHotkey | point := Object()
point.x := 1
point.y := 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
| #AWK | AWK | BEGIN {
p["x"]=10
p["y"]=42
z = "ZZ"
p[ z ]=999
p[ 4 ]=5
for (i in p) print( i, ":", p[i] )
} |
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.
| #Nim | Nim | proc calc(f: proc(n: int): tuple[a, b: float], n: int): float =
var a, b, temp = 0.0
for i in countdown(n, 1):
(a, b) = f(i)
temp = b / (a + temp)
(a, b) = f(0)
a + temp
proc sqrt2(n: int): tuple[a, b: float] =
if n > 0:
(2.0, 1.0)
else:
(1.0, 1.0)
proc napier(n: int): tuple[a, b: float] =
let a = if n > 0: float(n) else: 2.0
let b = if n > 1: float(n - 1) else: 1.0
(a, b)
proc pi(n: int): tuple[a, b: float] =
let a = if n > 0: 6.0 else: 3.0
let b = (2 * float(n) - 1) * (2 * float(n) - 1)
(a, b)
echo calc(sqrt2, 20)
echo calc(napier, 15)
echo calc(pi, 10000) |
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.
| #OCaml | OCaml | let pi = 3, fun n -> ((2*n-1)*(2*n-1), 6)
and nap = 2, fun n -> (max 1 (n-1), n)
and root2 = 1, fun n -> (1, 2) in
let eval (i,f) k =
let rec frac n =
let a, b = f n in
float a /. (float b +.
if n >= k then 0.0 else frac (n+1)) in
float i +. frac 1 in
Printf.printf "sqrt(2)\t= %.15f\n" (eval root2 1000);
Printf.printf "e\t= %.15f\n" (eval nap 1000);
Printf.printf "pi\t= %.15f\n" (eval pi 1000); |
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
| #MUMPS | MUMPS | SET S1="Greetings, Planet"
SET S2=S1 |
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
| #Nanoquery | Nanoquery | a = "Hello"
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.
| #Go | Go | package main
import (
"bytes"
"fmt"
"math/rand"
"time"
)
const (
nPts = 100
rMin = 10
rMax = 15
)
func main() {
rand.Seed(time.Now().Unix())
span := rMax + 1 + rMax
rows := make([][]byte, span)
for r := range rows {
rows[r] = bytes.Repeat([]byte{' '}, span*2)
}
u := 0 // count unique points
min2 := rMin * rMin
max2 := rMax * rMax
for n := 0; n < nPts; {
x := rand.Intn(span) - rMax
y := rand.Intn(span) - rMax
// x, y is the generated coordinate pair
rs := x*x + y*y
if rs < min2 || rs > max2 {
continue
}
n++ // count pair as meeting condition
r := y + rMax
c := (x + rMax) * 2
if rows[r][c] == ' ' {
rows[r][c] = '*'
u++
}
}
for _, row := range rows {
fmt.Println(string(row))
}
fmt.Println(u, "unique points")
} |
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/
| #Maple | Maple | pts:=[[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]]:
with(geometry):
map(coordinates,convexhull([seq(point(P||i,pts[i]),i=1..nops(pts))]));
# [[-9, -3], [-3, -9], [19, -8], [17, 5], [12, 17], [5, 19], [-3, 15]]
with(ComputationalGeometry):
pts[ConvexHull(pts)];
# [[12, 17], [5, 19], [-3, 15], [-9, -3], [-3, -9], [19, -8], [17, 5]]
simplex:-convexhull(pts);
# [[-9, -3], [-3, -9], [19, -8], [17, 5], [12, 17], [5, 19], [-3, 15]] |
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).
| #Pascal | Pascal | program convertSecondsToCompoundDuration(output);
const
suffixUnitWeek = 'wk';
suffixUnitDay = 'd';
suffixUnitHour = 'hr'; { Use `'h'` to be SI-compatible. }
suffixUnitMinute = 'min';
suffixUnitSecond = 'sec'; { NB: Only `'s'` is SI-approved. }
suffixSeparator = ' '; { A non-breaking space would be appropriate. }
quantitySeparator = ', ';
{ Maximum expected length of `string` “12345 wk, 6 d, 7 hr, 8 min, 9 sec” }
timeSpanPrintedMaximumLength = 4 * length(quantitySeparator) +
20 + length(suffixUnitWeek) + 1 + length(suffixUnitDay) +
2 + length(suffixUnitHour) + 2 + length(suffixUnitMinute) +
2 + length(suffixUnitSecond) + 5 * length(suffixSeparator);
{ Units of time expressed in seconds. }
minute = 60;
hour = 60 * minute;
day = 24 * hour;
week = 7 * day;
type
wholeNumber = 0..maxInt;
naturalNumber = 1..maxInt;
canonicalTimeSpan = record
weeks: wholeNumber;
days: 0..6;
hours: 0..23;
minutes: 0..59;
seconds: 0..59;
end;
stringFitForTimeSpan = string(timeSpanPrintedMaximumLength);
{
\brief turns a time span expressed in seconds into a `canonicalTimeSpan`
\param duration the non-negative duration expressed in seconds
\return a `canonicalTimeSpan` representing \param duration seconds
}
function getCanonicalTimeSpan(duration: wholeNumber): canonicalTimeSpan;
{ Perform `div`ision and update `duration`. }
function split(protected unit: naturalNumber): wholeNumber;
begin
split := duration div unit;
duration := duration mod unit
end;
var
result: canonicalTimeSpan;
begin
with result do
begin
weeks := split(week);
days := split(day);
hours := split(hour);
minutes := split(minute);
seconds := duration
end;
{ In Pascal there needs to be _exactly_ one assignment to the }
{ result variable bearing the same name as of the `function`. }
getCanonicalTimeSpan := result
end;
{
\brief turns a non-trivial duration into a string
\param n a positive duration expressed in seconds
\return \param n expressed in some human-readable form
}
function timeSpanString(protected n: naturalNumber): stringFitForTimeSpan;
const
qs = quantitySeparator;
var
result: stringFitForTimeSpan;
begin
with getCanonicalTimeSpan(n) do
begin
{ `:1` specifies the minimum-width. Omitting it would cause }
{ the compiler to insert a vendor-defined default, e. g. 20. }
writeStr(result, weeks:1, suffixSeparator, suffixUnitWeek);
{ For strings, `:n` specifies the _exact_ width (padded with spaces). }
writeStr(result, result:ord(weeks > 0) * length(result));
if days > 0 then
begin
writeStr(result, result, qs:ord(length(result) > 0) * length(qs),
days:1, suffixSeparator, suffixUnitDay);
end;
if hours > 0 then
begin
writeStr(result, result, qs:ord(length(result) > 0) * length(qs),
hours:1, suffixSeparator, suffixUnitHour);
end;
if minutes > 0 then
begin
writeStr(result, result, qs:ord(length(result) > 0) * length(qs),
minutes:1, suffixSeparator, suffixUnitMinute);
end;
if seconds > 0 then
begin
writeStr(result, result, qs:ord(length(result) > 0) * length(qs),
seconds:1, suffixSeparator, suffixUnitSecond);
end
end;
timeSpanString := result
end;
{ === MAIN ============================================================= }
begin
writeLn( 7259, ' seconds are “', timeSpanString(7259), '”');
writeLn( 86400, ' seconds are “', timeSpanString(86400), '”');
writeLn(6000000, ' seconds are “', timeSpanString(6000000), '”')
end. |
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.
| #CoffeeScript | CoffeeScript | { exec } = require 'child_process'
for word in [ 'Enjoy', 'Rosetta', 'Code' ]
exec "echo #{word}", (err, stdout) ->
console.log stdout |
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.
| #Common_Lisp | Common Lisp | (defun concurrency-example (&optional (out *standard-output*))
(let ((lock (bordeaux-threads:make-lock)))
(flet ((writer (string)
#'(lambda ()
(bordeaux-threads:acquire-lock lock t)
(write-line string out)
(bordeaux-threads:release-lock lock))))
(bordeaux-threads:make-thread (writer "Enjoy"))
(bordeaux-threads:make-thread (writer "Rosetta"))
(bordeaux-threads:make-thread (writer "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
| #Haskell | Haskell | import Data.Complex (Complex(..), conjugate)
import Data.List (transpose)
type Matrix a = [[a]]
main :: IO ()
main =
mapM_
(\a -> do
putStrLn "\nMatrix:"
mapM_ print a
putStrLn "Conjugate Transpose:"
mapM_ print (conjTranspose a)
putStrLn $ "Hermitian? " ++ show (isHermitianMatrix a)
putStrLn $ "Normal? " ++ show (isNormalMatrix a)
putStrLn $ "Unitary? " ++ show (isUnitaryMatrix a))
([ [[3, 2 :+ 1], [2 :+ (-1), 1]]
, [[1, 1, 0], [0, 1, 1], [1, 0, 1]]
, [ [sqrt 2 / 2 :+ 0, sqrt 2 / 2 :+ 0, 0]
, [0 :+ sqrt 2 / 2, 0 :+ (-sqrt 2 / 2), 0]
, [0, 0, 0 :+ 1]
]
] :: [Matrix (Complex Double)])
isHermitianMatrix, isNormalMatrix, isUnitaryMatrix
:: RealFloat a
=> Matrix (Complex a) -> Bool
isHermitianMatrix = mTest id conjTranspose
isNormalMatrix = mTest mmct (mmul =<< conjTranspose)
isUnitaryMatrix = mTest mmct (ident . length)
mTest
:: RealFloat a
=> (a2 -> Matrix (Complex a)) -> (a2 -> Matrix (Complex a)) -> a2 -> Bool
mTest f g = (approxEqualMatrix . f) <*> g
mmct
:: RealFloat a
=> Matrix (Complex a) -> Matrix (Complex a)
mmct = mmul <*> conjTranspose
approxEqualMatrix
:: (Fractional a, Ord a)
=> Matrix (Complex a) -> Matrix (Complex a) -> Bool
approxEqualMatrix a b =
length a == length b &&
length (head a) == length (head b) &&
and (zipWith approxEqualComplex (concat a) (concat b))
where
approxEqualComplex (rx :+ ix) (ry :+ iy) =
abs (rx - ry) < eps && abs (ix - iy) < eps
eps = 1e-14
mmul
:: Num a
=> Matrix a -> Matrix a -> Matrix a
mmul a b =
[ [ sum (zipWith (*) row column)
| column <- transpose b ]
| row <- a ]
ident
:: Num a
=> Int -> Matrix a
ident size =
[ [ fromIntegral $ div a b * div b a
| a <- [1 .. size] ]
| b <- [1 .. size] ]
conjTranspose
:: Num a
=> Matrix (Complex a) -> Matrix (Complex a)
conjTranspose = map (map conjugate) . transpose |
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
| #Axe | Axe | Lbl POINT
r₂→{r₁}ʳ
r₃→{r₁+2}ʳ
r₁
Return |
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
| #BASIC | BASIC | TYPE Point
x AS INTEGER
y AS INTEGER
END TYPE |
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.
| #PARI.2FGP | PARI/GP | back(v)=my(t=contfracpnqn(v));t[1,1]/t[2,1]*1.
back(vector(100,i,2-(i==1))) |
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
| #Neko | Neko | var src = "Hello"
var dst = 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
| #Nemerle | Nemerle | using System;
using System.Console;
using Nemerle;
module StrCopy
{
Main() : void
{
mutable str1 = "I am not changed"; // str1 is bound to literal
def str2 = lazy(str1); // str2 will be bound when evaluated
def str3 = str1; // str3 is bound to value of str1
str1 = "I am changed"; // str1 is bound to new literal
Write($"$(str1)\n$(str2)\n$(str3)\n"); // str2 is bound to value of str1
// Output: I am changed
// I am changed
// I am not changed
}
} |
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.
| #Haskell | Haskell | import Data.List
import Control.Monad
import Control.Arrow
import Rosetta.Knuthshuffle
task = do
let blanco = replicate (31*31) " "
cs = sequence [[-15,-14..15],[-15,-14..15]] :: [[Int]]
constraint = uncurry(&&).((<= 15*15) &&& (10*10 <=)). sum. map (join (*))
-- select and randomize all circle points
pts <- knuthShuffle $ filter constraint cs
-- 'paint' first 100 randomized circle points on canvas
let canvas = foldl (\cs [x,y] -> replaceAt (31*(x+15)+y+15) "/ " cs ) blanco (take 100 pts)
-- show canvas
mapM_ (putStrLn.concat). takeWhile(not.null). unfoldr (Just . splitAt 31) $ canvas |
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/
| #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | hullPoints[data_] := MeshCoordinates[ConvexHullMesh[data]];
hullPoints[{{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).
| #Perl | Perl | use strict;
use warnings;
sub compound_duration {
my $sec = shift;
no warnings 'numeric';
return join ', ', grep { $_ > 0 }
int($sec/60/60/24/7) . " wk",
int($sec/60/60/24) % 7 . " d",
int($sec/60/60) % 24 . " hr",
int($sec/60) % 60 . " min",
int($sec) % 60 . " sec";
}
for (7259, 86400, 6000000) {
printf "%7d sec = %s\n", $_, compound_duration($_)
} |
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.
| #Crystal | Crystal | require "channel"
require "fiber"
require "random"
done = Channel(Nil).new
"Enjoy Rosetta Code".split.map do |x|
spawn do
sleep Random.new.rand(0..500).milliseconds
puts x
done.send nil
end
end
3.times do
done.receive
end |
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.
| #D | D | import std.stdio, std.random, std.parallelism, core.thread, core.time;
void main() {
foreach (s; ["Enjoy", "Rosetta", "Code"].parallel(1)) {
Thread.sleep(uniform(0, 1000).dur!"msecs");
s.writeln;
}
} |
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
| #J | J | ct =: +@|: NB. Conjugate transpose (ct A is A_ct) |
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
| #jq | jq | # transpose/0 expects its input to be a rectangular matrix
# (an array of equal-length arrays):
def transpose:
if (.[0] | length) == 0 then []
else [map(.[0])] + (map(.[1:]) | transpose)
end ; |
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
| #BBC_BASIC | BBC BASIC | DIM Point{x%, 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
| #Bracmat | Bracmat | ( ( Point
= (x=)
(y=)
(new=.!arg:(?(its.x).?(its.y)))
)
& new$(Point,(3.4)):?pt
& out$(!(pt..x) !(pt..y))
{ Show independcy by changing x, but not y }
& 7:?(pt..x)
& out$(!(pt..x) !(pt..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.
| #Perl | Perl | use strict;
use warnings;
no warnings 'recursion';
use experimental 'signatures';
sub continued_fraction ($a, $b, $n = 100) {
$a->() + ($n and $b->() / continued_fraction($a, $b, $n-1));
}
printf "√2 ≈ %.9f\n", continued_fraction do { my $n; sub { $n++ ? 2 : 1 } }, sub { 1 };
printf "e ≈ %.9f\n", continued_fraction do { my $n; sub { $n++ or 2 } }, do { my $n; sub { $n++ or 1 } };
printf "π ≈ %.9f\n", continued_fraction do { my $n; sub { $n++ ? 6 : 3 } }, do { my $n; sub { (2*$n++ + 1)**2 } }, 1000;
printf "π/2 ≈ %.9f\n", continued_fraction do { my $n; sub { 1/($n++ or 1) } }, sub { 1 }, 1000; |
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
| #NetRexx | NetRexx | /* NetRexx */
options replace format comments java crossref symbols nobinary
s1 = 'This is a Rexx string'
s2 = s1
s2 = s2.changestr(' ', '_')
say s1
say s2 |
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
| #NewLISP | NewLISP | (define (assert f msg) (if (not f) (println msg)))
(setq s "Greetings!" c (copy s))
(reverse c) ; Modifies c in place.
(assert (= s c) "Strings not equal.")
; another way
; Nehal-Singhal 2018-05-25
> (setq a "abcd")
"abcd"
> (setq b a)
"abcd"
> b
"abcd"
> (= a b)
true
|
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.
| #Hy | Hy | (import
math [sqrt]
random [choice]
matplotlib.pyplot :as plt)
(setv possible-points
(lfor
x (range -15 16)
y (range -15 16)
:if (<= 10 (sqrt (+ (** x 2) (** y 2))) 15)
[x y]))
(setv [xs ys] (zip #* (map (fn [_] (choice possible-points)) (range 100))))
; We can't use random.sample because that samples without replacement.
; #* is also known as unpack-iterable
(plt.plot xs ys "bo")
(plt.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/
| #Mercury | Mercury | :- module convex_hull_task.
:- interface.
:- import_module io.
:- pred main(io, io).
:- mode main(di, uo) is det.
:- implementation.
:- import_module exception.
:- import_module float.
:- import_module int.
:- import_module list.
:- import_module pair.
:- import_module string.
:- import_module version_array.
%%--------------------------------------------------------------------
%% fetch_items/3 for version_array, similar to the library function
%% for regular array.
:- func fetch_items(version_array(T), int, int) = list(T).
fetch_items(Arr, I, J) = fetch_items_(Arr, I, J, []).
:- func fetch_items_(version_array(T), int, int, list(T)) = list(T).
fetch_items_(Arr, I, J, Lst0) = Lst :-
if (J < I) then (Lst = Lst0)
else (J1 = J - 1,
Lst = fetch_items_(Arr, I, J1, [Arr^elem(J) | Lst0])).
%%--------------------------------------------------------------------
:- type point == pair(float).
:- type point_list == list(point).
:- type point_array == version_array(point).
:- pred point_comes_before(point, point).
:- mode point_comes_before(in, in) is semidet.
point_comes_before(P, Q) :-
(fst(P) < fst(Q); fst(P) - fst(Q) = (0.0),
snd(P) < snd(Q)).
:- pred point_compare(point, point, comparison_result).
:- mode point_compare(in, in, out) is det.
point_compare(P, Q, Cmp) :-
if (point_comes_before(P, Q)) then (Cmp = (<))
else if (point_comes_before(Q, P)) then (Cmp = (>))
else (Cmp = (=)).
:- func point_subtract(point, point) = point.
point_subtract(P, Q) = pair(fst(P) - fst(Q),
snd(P) - snd(Q)).
:- func point_cross_product(point, point) = float.
point_cross_product(P, Q) = (fst(P) * snd(Q)) - (snd(P) * fst(Q)).
:- func point_to_string(point) = string.
point_to_string(P) = ("(" ++ from_float(fst(P)) ++
" " ++ from_float(snd(P)) ++ ")").
%%--------------------------------------------------------------------
:- func convex_hull(point_list) = point_list.
convex_hull(Pt) = Hull :-
Pt1 = unique_points_sorted(Pt),
(if (Pt1 = []; Pt1 = [_]; Pt1 = [_, _]) then (Hull = Pt1)
else (Hull = construct_hull(Pt1))).
:- func unique_points_sorted(point_list) = point_list.
unique_points_sorted(Pt0) = Pt :-
sort_and_remove_dups(point_compare, Pt0, Pt).
:- func construct_hull(point_list) = point_list.
construct_hull(Pt) = (construct_lower_hull(Pt) ++
construct_upper_hull(Pt)).
:- func construct_lower_hull(point_list) = point_list.
construct_lower_hull(Pt) = Hull :-
if (Pt = [P0, P1 | Rest])
then (N = length(Pt),
Arr0 = (version_array.init(N, P0)),
Arr1 = (Arr0^elem(1) := P1),
hull_construction(Rest, Arr1, Arr2, 1, N_Hull),
%% In the fetch_items/3 call, we leave out the last item. It
%% is redundant with the first item of the upper hull.
N_Hull2 = N_Hull - 2,
Hull = fetch_items(Arr2, 0, N_Hull2))
else throw("construct_lower_hull expects list of length >= 3").
:- func construct_upper_hull(point_list) = point_list.
%% An upper hull is merely a lower hull for points going the other
%% way.
construct_upper_hull(Pt) = construct_lower_hull(reverse(Pt)).
:- pred hull_construction(point_list, point_array, point_array,
int, int).
:- mode hull_construction(in, in, out, in, out) is det.
hull_construction([], Arr0, Arr, J, N_Hull) :-
Arr = Arr0,
N_Hull = J + 1.
hull_construction([P | Rest], Arr0, Arr, J, N_Hull) :-
if cross_test(P, Arr0, J)
then (J1 = J + 1,
Arr1 = (Arr0^elem(J1) := P),
hull_construction(Rest, Arr1, Arr, J1, N_Hull))
else (J1 = J - 1,
hull_construction([P | Rest], Arr0, Arr, J1, N_Hull)).
:- pred cross_test(point, point_array, int).
:- mode cross_test(in, in, in) is semidet.
cross_test(P, Arr, J) :-
if (J = 0) then true
else (Elem_J = Arr^elem(J),
J1 = J - 1,
Elem_J1 = Arr^elem(J1),
0.0 < point_cross_product(point_subtract(Elem_J, Elem_J1),
point_subtract(P, Elem_J1))).
%%--------------------------------------------------------------------
main(!IO) :-
Example_points = [pair(16.0, 3.0),
pair(12.0, 17.0),
pair(0.0, 6.0),
pair(-4.0, -6.0),
pair(16.0, 6.0),
pair(16.0, -7.0),
pair(16.0, -3.0),
pair(17.0, -4.0),
pair(5.0, 19.0),
pair(19.0, -8.0),
pair(3.0, 16.0),
pair(12.0, 13.0),
pair(3.0, -4.0),
pair(17.0, 5.0),
pair(-3.0, 15.0),
pair(-3.0, -9.0),
pair(0.0, 11.0),
pair(-9.0, -3.0),
pair(-4.0, -2.0),
pair(12.0, 10.0)],
Hull = convex_hull(Example_points),
HullStr = join_list(" ", map(point_to_string, Hull)),
write_string(HullStr, !IO),
nl(!IO).
%%%-------------------------------------------------------------------
%%% local variables:
%%% mode: mercury
%%% prolog-indent-width: 2
%%% 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).
| #Phix | Phix | with javascript_semantics
?elapsed(7259)
?elapsed(86400)
?elapsed(6000000)
|
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).
| #PicoLisp | PicoLisp | (for Sec (7259 86400 6000000)
(tab (-10 -30)
Sec
(glue ", "
(extract
'((N Str)
(when (gt0 (/ Sec N))
(setq Sec (% Sec N))
(pack @ " " Str) ) )
(604800 86400 3600 60 1)
'("wk" "d" "hr" "min" "sec") ) ) ) ) |
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.
| #Dart | Dart | import 'dart:math' show Random;
main(){
enjoy() .then( (e) => print(e) );
rosetta() .then( (r) => print(r) );
code() .then( (c) => print(c) );
}
// Create random number generator
var rng = Random();
// Each function returns a future that starts after a delay
// Like using setTimeout with a Promise in Javascript
enjoy() => Future.delayed( Duration( milliseconds: rng.nextInt( 10 ) ), () => "Enjoy");
rosetta() => Future.delayed( Duration( milliseconds: rng.nextInt( 10 ) ), () => "Rosetta");
code() => Future.delayed( Duration( milliseconds: rng.nextInt( 10 ) ), () => "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.
| #Delphi | Delphi | program ConcurrentComputing;
{$APPTYPE CONSOLE}
uses SysUtils, Classes, Windows;
type
TRandomThread = class(TThread)
private
FString: string;
protected
procedure Execute; override;
public
constructor Create(const aString: string); overload;
end;
constructor TRandomThread.Create(const aString: string);
begin
inherited Create(False);
FreeOnTerminate := True;
FString := aString;
end;
procedure TRandomThread.Execute;
begin
Sleep(Random(5) * 100);
Writeln(FString);
end;
var
lThreadArray: Array[0..2] of THandle;
begin
Randomize;
lThreadArray[0] := TRandomThread.Create('Enjoy').Handle;
lThreadArray[1] := TRandomThread.Create('Rosetta').Handle;
lThreadArray[2] := TRandomThread.Create('Stone').Handle;
WaitForMultipleObjects(Length(lThreadArray), @lThreadArray, True, INFINITE);
end. |
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
| #Julia | Julia | A' |
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
| #Kotlin | Kotlin | // version 1.1.3
typealias C = Complex
typealias Vector = Array<C>
typealias Matrix = Array<Vector>
class Complex(val real: Double, val imag: Double) {
operator fun plus(other: Complex) =
Complex(this.real + other.real, this.imag + other.imag)
operator fun times(other: Complex) =
Complex(this.real * other.real - this.imag * other.imag,
this.real * other.imag + this.imag * other.real)
fun conj() = Complex(this.real, -this.imag)
/* tolerable equality allowing for rounding of Doubles */
infix fun teq(other: Complex) =
Math.abs(this.real - other.real) <= 1e-14 &&
Math.abs(this.imag - other.imag) <= 1e-14
override fun toString() = "${"%.3f".format(real)} " + when {
imag > 0.0 -> "+ ${"%.3f".format(imag)}i"
imag == 0.0 -> "+ 0.000i"
else -> "- ${"%.3f".format(-imag)}i"
}
}
fun Matrix.conjTranspose(): Matrix {
val rows = this.size
val cols = this[0].size
return Matrix(cols) { i -> Vector(rows) { j -> this[j][i].conj() } }
}
operator fun Matrix.times(other: Matrix): Matrix {
val rows1 = this.size
val cols1 = this[0].size
val rows2 = other.size
val cols2 = other[0].size
require(cols1 == rows2)
val result = Matrix(rows1) { Vector(cols2) { C(0.0, 0.0) } }
for (i in 0 until rows1) {
for (j in 0 until cols2) {
for (k in 0 until rows2) {
result[i][j] += this[i][k] * other[k][j]
}
}
}
return result
}
/* tolerable matrix equality using the same concept as for complex numbers */
infix fun Matrix.teq(other: Matrix): Boolean {
if (this.size != other.size || this[0].size != other[0].size) return false
for (i in 0 until this.size) {
for (j in 0 until this[0].size) if (!(this[i][j] teq other[i][j])) return false
}
return true
}
fun Matrix.isHermitian() = this teq this.conjTranspose()
fun Matrix.isNormal(): Boolean {
val ct = this.conjTranspose()
return (this * ct) teq (ct * this)
}
fun Matrix.isUnitary(): Boolean {
val ct = this.conjTranspose()
val prod = this * ct
val ident = identityMatrix(prod.size)
val prod2 = ct * this
return (prod teq ident) && (prod2 teq ident)
}
fun Matrix.print() {
val rows = this.size
val cols = this[0].size
for (i in 0 until rows) {
for (j in 0 until cols) {
print(this[i][j])
print(if(j < cols - 1) ", " else "\n")
}
}
println()
}
fun identityMatrix(n: Int): Matrix {
require(n >= 1)
val ident = Matrix(n) { Vector(n) { C(0.0, 0.0) } }
for (i in 0 until n) ident[i][i] = C(1.0, 0.0)
return ident
}
fun main(args: Array<String>) {
val x = Math.sqrt(2.0) / 2.0
val matrices = arrayOf(
arrayOf(
arrayOf(C(3.0, 0.0), C(2.0, 1.0)),
arrayOf(C(2.0, -1.0), C(1.0, 0.0))
),
arrayOf(
arrayOf(C(1.0, 0.0), C(1.0, 0.0), C(0.0, 0.0)),
arrayOf(C(0.0, 0.0), C(1.0, 0.0), C(1.0, 0.0)),
arrayOf(C(1.0, 0.0), C(0.0, 0.0), C(1.0, 0.0))
),
arrayOf(
arrayOf(C(x, 0.0), C(x, 0.0), C(0.0, 0.0)),
arrayOf(C(0.0, -x), C(0.0, x), C(0.0, 0.0)),
arrayOf(C(0.0, 0.0), C(0.0, 0.0), C(0.0, 1.0))
)
)
for (m in matrices) {
println("Matrix:")
m.print()
val mct = m.conjTranspose()
println("Conjugate transpose:")
mct.print()
println("Hermitian? ${mct.isHermitian()}")
println("Normal? ${mct.isNormal()}")
println("Unitary? ${mct.isUnitary()}\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
| #Brlcad | Brlcad | c lamp base stem bulb shade chord plug
|
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
| #C | C | typedef struct Point
{
int x;
int y;
} Point; |
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.
| #Phix | Phix | with javascript_semantics
constant precision = 10000
function continued_fraction(integer f, steps=precision)
atom a, b, res = 0
for n=steps to 1 by -1 do
{a, b} = f(n)
res := b / (a + res)
end for
{a} = f(0)
return a + res
end function
function sqr2(integer n) return {iff(n=0?1:2),1} end function
function nap(integer n) return {iff(n=0?2:n),iff(n=1?1:n-1)} end function
function pi(integer n) return {iff(n=0?3:6),power(2*n-1,2)} end function
printf(1,"Precision: %d\n", {precision})
printf(1,"Sqr(2): %.10g\n", {continued_fraction(sqr2)})
printf(1,"Napier: %.10g\n", {continued_fraction(nap)})
printf(1,"Pi: %.10g\n", {continued_fraction(pi)})
|
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
| #Nim | Nim | var
c = "This is a string"
d = c # Copy c into a new string |
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
| #NS-HUBASIC | NS-HUBASIC | 10 A$ = "HELLO"
20 B$ = A$
30 A$ = "HI"
40 PRINT A$, B$ |
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.
| #Icon_and_Unicon | Icon and Unicon | link graphics
procedure main(A) # points, inside r, outside r in pixels - default to task values
if \A[1] == "help" then stop("Usage: plot #points inside-radius outside-radius")
points := \A[1] | 100
outside := \A[2] | 15
inside := \A[3] | 10
if inside > outside then inside :=: outside
wsize := integer(2.2*outside)
wsize <:= 150
center := wsize/2
WOpen("size="||wsize||","||wsize,"bg=black","fg=white") | stop("Unable to open window")
until(points -:= 1) <= 0 do {
x := ?(2*outside)-outside # random x
y := ?(2*outside)-outside # and y
if (inside <= integer(sqrt(x^2+y^2)) ) <= outside then
DrawPoint(x + center,y + center)
}
WDone()
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/
| #Modula-2 | Modula-2 | MODULE ConvexHull;
FROM FormatString IMPORT FormatString;
FROM Storage IMPORT ALLOCATE, DEALLOCATE;
FROM SYSTEM IMPORT TSIZE;
FROM Terminal IMPORT WriteString,WriteLn,ReadChar;
PROCEDURE WriteInt(n : INTEGER);
VAR buf : ARRAY[0..15] OF CHAR;
BEGIN
FormatString("%i", buf, n);
WriteString(buf);
END WriteInt;
TYPE
Point = RECORD
x, y : INTEGER;
END;
PROCEDURE WritePoint(pt : Point);
BEGIN
WriteString("(");
WriteInt(pt.x);
WriteString(", ");
WriteInt(pt.y);
WriteString(")");
END WritePoint;
TYPE
NextNode = POINTER TO PNode;
PNode = RECORD
value : Point;
next : NextNode;
END;
PROCEDURE WriteNode(it : NextNode);
BEGIN
IF it = NIL THEN
RETURN
END;
WriteString("[");
WritePoint(it^.value);
it := it^.next;
WHILE it # NIL DO
WriteString(", ");
WritePoint(it^.value);
it := it^.next
END;
WriteString("]")
END WriteNode;
PROCEDURE AppendNode(pn : NextNode; p : Point) : NextNode;
VAR it,nx : NextNode;
BEGIN
IF pn = NIL THEN
ALLOCATE(it,TSIZE(PNode));
it^.value := p;
it^.next := NIL;
RETURN it
END;
it := pn;
WHILE it^.next # NIL DO
it := it^.next
END;
ALLOCATE(nx,TSIZE(PNode));
nx^.value := p;
nx^.next := NIL;
it^.next := nx;
RETURN pn
END AppendNode;
PROCEDURE DeleteNode(VAR pn : NextNode);
BEGIN
IF pn = NIL THEN RETURN END;
DeleteNode(pn^.next);
DEALLOCATE(pn,TSIZE(PNode));
pn := NIL
END DeleteNode;
PROCEDURE SortNode(VAR pn : NextNode);
VAR
it : NextNode;
tmp : Point;
done : BOOLEAN;
BEGIN
REPEAT
done := TRUE;
it := pn;
WHILE (it # NIL) AND (it^.next # NIL) DO
IF it^.next^.value.x < it^.value.x THEN
tmp := it^.value;
it^.value := it^.next^.value;
it^.next^.value := tmp;
done := FALSE
END;
it := it^.next;
END
UNTIL done;
END SortNode;
PROCEDURE NodeLength(it : NextNode) : INTEGER;
VAR length : INTEGER;
BEGIN
length := 0;
WHILE it # NIL DO
INC(length);
it := it^.next;
END;
RETURN length
END NodeLength;
PROCEDURE ReverseNode(fp : NextNode) : NextNode;
VAR rp,tmp : NextNode;
BEGIN
IF fp = NIL THEN RETURN NIL END;
ALLOCATE(tmp,TSIZE(PNode));
tmp^.value := fp^.value;
tmp^.next := NIL;
rp := tmp;
fp := fp^.next;
WHILE fp # NIL DO
ALLOCATE(tmp,TSIZE(PNode));
tmp^.value := fp^.value;
tmp^.next := rp;
rp := tmp;
fp := fp^.next;
END;
RETURN rp
END ReverseNode;
(* ccw returns true if the three points make a counter-clockwise turn *)
PROCEDURE CCW(a,b,c : Point) : BOOLEAN;
BEGIN
RETURN ((b.x - a.x) * (c.y - a.y)) > ((b.y - a.y) * (c.x - a.x))
END CCW;
PROCEDURE ConvexHull(p : NextNode) : NextNode;
VAR
hull,it,h1,h2 : NextNode;
t : INTEGER;
BEGIN
IF p = NIL THEN RETURN NIL END;
SortNode(p);
hull := NIL;
(* lower hull *)
it := p;
WHILE it # NIL DO
IF hull # NIL THEN
WHILE hull^.next # NIL DO
(* At least two points in the list *)
h2 := hull;
h1 := hull^.next;
WHILE h1^.next # NIL DO
h2 := h1;
h1 := h2^.next;
END;
IF CCW(h2^.value, h1^.value, it^.value) THEN
BREAK
ELSE
h2^.next := NIL;
DeleteNode(h1);
h1 := NIL
END
END
END;
hull := AppendNode(hull, it^.value);
it := it^.next;
END;
(* upper hull *)
t := NodeLength(hull) + 1;
p := ReverseNode(p);
it := p;
WHILE it # NIL DO
WHILE NodeLength(hull) >= t DO
h2 := hull;
h1 := hull^.next;
WHILE h1^.next # NIL DO
h2 := h1;
h1 := h2^.next;
END;
IF CCW(h2^.value, h1^.value, it^.value) THEN
BREAK
ELSE
h2^.next := NIL;
DeleteNode(h1);
h1 := NIL
END
END;
hull := AppendNode(hull, it^.value);
it := it^.next;
END;
DeleteNode(p);
h2 := hull;
h1 := h2^.next;
WHILE h1^.next # NIL DO
h2 := h1;
h1 := h1^.next;
END;
h2^.next := NIL;
DeleteNode(h1);
RETURN hull
END ConvexHull;
(* Main *)
VAR nodes,hull : NextNode;
BEGIN
nodes := AppendNode(NIL, Point{16, 3});
AppendNode(nodes, Point{12,17});
AppendNode(nodes, Point{ 0, 6});
AppendNode(nodes, Point{-4,-6});
AppendNode(nodes, Point{16, 6});
AppendNode(nodes, Point{16,-7});
AppendNode(nodes, Point{16,-3});
AppendNode(nodes, Point{17,-4});
AppendNode(nodes, Point{ 5,19});
AppendNode(nodes, Point{19,-8});
AppendNode(nodes, Point{ 3,16});
AppendNode(nodes, Point{12,13});
AppendNode(nodes, Point{ 3,-4});
AppendNode(nodes, Point{17, 5});
AppendNode(nodes, Point{-3,15});
AppendNode(nodes, Point{-3,-9});
AppendNode(nodes, Point{ 0,11});
AppendNode(nodes, Point{-9,-3});
AppendNode(nodes, Point{-4,-2});
AppendNode(nodes, Point{12,10});
hull := ConvexHull(nodes);
WriteNode(hull);
DeleteNode(hull);
DeleteNode(nodes);
ReadChar
END ConvexHull. |
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).
| #PL.2FI | PL/I |
/* Convert seconds to Compound Duration (weeks, days, hours, minutes, seconds). */
cvt: procedure options (main); /* 5 August 2015 */
declare interval float (15);
declare (unit, i, q controlled) fixed binary;
declare done bit (1) static initial ('0'b);
declare name (5) character (4) varying static initial (' wk', ' d', ' hr', ' min', ' sec' );
get (interval);
put edit (interval, ' seconds = ') (f(10), a);
if interval = 0 then do; put skip list ('0 sec'); stop; end;
do unit = 60, 60, 24, 7;
allocate q;
q = mod(interval, unit);
interval = interval / unit;
end;
allocate q; q = interval;
do i = 1 to 5;
if q > 0 then
do;
if done then put edit (', ') (a);
put edit (trim(q), name(i)) (a, a); done = '1'b;
end;
if i < 5 then free q;
end;
end cvt;
|
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).
| #PowerShell | PowerShell |
function Get-Time
{
<#
.SYNOPSIS
Gets a time string in the form: # wk, # d, # hr, # min, # sec
.DESCRIPTION
Gets a time string in the form: # wk, # d, # hr, # min, # sec
(Values of 0 are not displayed in the string.)
Days, Hours, Minutes or Seconds in any combination may be used
as well as Start and End dates.
When used with the -AsObject switch an object containing properties
similar to a System.TimeSpan object is returned.
.INPUTS
DateTime or Int32
.OUTPUTS
String or PSCustomObject
.EXAMPLE
Get-Time -Seconds 7259
.EXAMPLE
Get-Time -Days 31 -Hours 4 -Minutes 8 -Seconds 16
.EXAMPLE
Get-Time -Days 31 -Hours 4 -Minutes 8 -Seconds 16 -AsObject
.EXAMPLE
Get-Time -Start 3/10/2016 -End 1/20/2017
.EXAMPLE
Get-Time -Start (Get-Date) -End (Get-Date).AddSeconds(6000000)
#>
[CmdletBinding(DefaultParameterSetName='Date')]
Param
(
# Start date
[Parameter(Mandatory=$false, ParameterSetName='Date',
Position=0)]
[datetime]
$Start = (Get-Date),
# End date
[Parameter(Mandatory=$false, ParameterSetName='Date',
Position=1)]
[datetime]
$End = (Get-Date),
# Days in the time span
[Parameter(Mandatory=$false, ParameterSetName='Time')]
[int]
$Days = 0,
# Hours in the time span
[Parameter(Mandatory=$false, ParameterSetName='Time')]
[int]
$Hours = 0,
# Minutes in the time span
[Parameter(Mandatory=$false, ParameterSetName='Time')]
[int]
$Minutes = 0,
# Seconds in the time span
[Parameter(Mandatory=$false, ParameterSetName='Time')]
[int]
$Seconds = 0,
[switch]
$AsObject
)
Begin
{
[PSCustomObject]$timeObject = "PSCustomObject" |
Select-Object -Property Weeks,RemainingDays,
Days,Hours,Minutes,Seconds,Milliseconds,Ticks,
TotalDays,TotalHours,TotalMinutes,TotalSeconds,TotalMilliseconds
[int]$remainingDays = 0
[int]$weeks = 0
[string[]]$timeString = @()
}
Process
{
switch ($PSCmdlet.ParameterSetName)
{
'Date' { $timeSpan = New-TimeSpan -Start $Start -End $End }
'Time' { $timeSpan = New-TimeSpan -Days $Days -Hours $Hours -Minutes $Minutes -Seconds $Seconds }
}
$weeks = [System.Math]::DivRem($timeSpan.Days, 7, [ref]$remainingDays)
$timeObject.Weeks = $weeks
$timeObject.RemainingDays = $remainingDays
$timeObject.Days = $timeSpan.Days
$timeObject.Hours = $timeSpan.Hours
$timeObject.Minutes = $timeSpan.Minutes
$timeObject.Seconds = $timeSpan.Seconds
$timeObject.Milliseconds = $timeSpan.Milliseconds
$timeObject.Ticks = $timeSpan.Ticks
$timeObject.TotalDays = $timeSpan.TotalDays
$timeObject.TotalHours = $timeSpan.TotalHours
$timeObject.TotalMinutes = $timeSpan.TotalMinutes
$timeObject.TotalSeconds = $timeSpan.TotalSeconds
$timeObject.TotalMilliseconds = $timeSpan.TotalMilliseconds
}
End
{
if ($AsObject) { return $timeObject }
if ($timeObject.Weeks) { $timeString += "$($timeObject.Weeks) wk" }
if ($timeObject.RemainingDays) { $timeString += "$($timeObject.RemainingDays) d" }
if ($timeObject.Hours) { $timeString += "$($timeObject.Hours) hr" }
if ($timeObject.Minutes) { $timeString += "$($timeObject.Minutes) min" }
if ($timeObject.Seconds) { $timeString += "$($timeObject.Seconds) sec" }
return ($timeString -join ", ")
}
}
|
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.
| #dodo0 | dodo0 | fun parprint -> text, return
(
fork() -> return, throw
println(text, return)
| x
return()
)
| parprint
parprint("Enjoy") ->
parprint("Rosetta") ->
parprint("Code") ->
exit() |
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.
| #E | E | def base := timer.now()
for string in ["Enjoy", "Rosetta", "Code"] {
timer <- whenPast(base + entropy.nextInt(1000), fn { println(string) })
} |
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
| #Maple | Maple | M:=<<3|2+I>,<2-I|1>>:
with(LinearAlgebra):
IsNormal:=A->EqualEntries(A^%H.A,A.A^%H):
M^%H;
HermitianTranspose(M);
type(M,'Matrix'(hermitian));
IsNormal(M);
IsUnitary(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
| #C.23 | C# | struct Point
{
public int x, y;
public Point(int x, int y) {
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
| #C.2B.2B | C++ | struct Point
{
int x;
int 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.
| #Picat | Picat | go =>
% square root 2
continued_fraction(200, sqrt_2_ab, V1),
printf("sqrt(2) = %w (diff: %0.15f)\n", V1, V1-sqrt(2)),
% napier
continued_fraction(200, napier_ab, V2),
printf("e = %w (diff: %0.15f)\n", V2, V2-math.e),
% pi
continued_fraction(200, pi_ab, V3),
printf("pi = %w (diff: %0.15f)\n", V3, V3-math.pi),
% get a better precision
continued_fraction(20000, pi_ab, V3b),
printf("pi = %w (diff: %0.15f)\n", V3b, V3b-math.pi),
nl.
continued_fraction(N, Compute_ab, V) ?=>
continued_fraction(N, Compute_ab, 0, V).
continued_fraction(0, Compute_ab, Temp, V) ?=>
call(Compute_ab, 0, A, _),
V = A + Temp.
continued_fraction(N, Compute_ab, Tmp, V) =>
call(Compute_ab, N, A, B),
Tmp1 = B / (A + Tmp),
N1 = N - 1,
continued_fraction(N1, Compute_ab, Tmp1, V).
% definitions for square root of 2
sqrt_2_ab(0, 1, 1).
sqrt_2_ab(_, 2, 1).
% definitions for napier
napier_ab(0, 2, _).
napier_ab(1, 1, 1).
napier_ab(N, N, V) :-
V is N - 1.
% definitions for pi
pi_ab(0, 3, _).
pi_ab(N, 6, V) :-
V is (2 * N - 1)*(2 * N - 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.
| #PicoLisp | PicoLisp | (scl 49)
(de fsqrt2 (N A)
(default A 1)
(cond
((> A (inc N)) 2)
(T
(+
(if (=1 A) 1.0 2.0)
(*/ `(* 1.0 1.0) (fsqrt2 N (inc A))) ) ) ) )
(de pi (N A)
(default A 1)
(cond
((> A (inc N)) 6.0)
(T
(+
(if (=1 A) 3.0 6.0)
(*/
(* (** (dec (* 2 A)) 2) 1.0)
1.0
(pi N (inc A)) ) ) ) ) )
(de napier (N A)
(default A 0)
(cond
((> A N) (* A 1.0))
(T
(+
(if (=0 A) 2.0 (* A 1.0))
(*/
(if (> 1 A) 1.0 (* A 1.0))
1.0
(napier N (inc A)) ) ) ) ) )
(prinl (format (fsqrt2 200) *Scl))
(prinl (format (napier 200) *Scl))
(prinl (format (pi 200) *Scl)) |
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
| #Oberon-2 | Oberon-2 | MODULE CopyString;
TYPE
String = ARRAY 128 OF CHAR;
VAR
a,b: String;
BEGIN
a := "plain string";
COPY(a,b);
END CopyString. |
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
| #Objeck | Objeck | a := "GoodBye!";
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.
| #J | J | gen=: ({~ 100?#)bind((#~ 1=99 225 I.+/"1@:*:),/,"0/~i:15) |
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/
| #Nim | Nim | type
Point = object
x: float
y: float
# Calculate orientation for 3 points
# 0 -> Straight line
# 1 -> Clockwise
# 2 -> Counterclockwise
proc orientation(p, q, r: Point): int =
let val = (q.y - p.y) * (r.x - q.x) -
(q.x - p.x) * (r.y - q.y)
if val == 0: 0
elif val > 0: 1
else: 2
proc calculateConvexHull(points: openArray[Point]): seq[Point] =
result = newSeq[Point]()
# There must be at least 3 points
if len(points) < 3:
for i in points: result.add(i)
# Find the leftmost point
var indexMinX = 0
for i, _ in points:
if points[i].x < points[indexMinX].x:
indexMinX = i
var p = indexMinX
var q = 0
while true:
# The leftmost point must be part of the hull.
result.add(points[p])
q = (p + 1) mod len(points)
for i in 0..<len(points):
if orientation(points[p], points[i], points[q]) == 2:
q = i
p = q
# Break from loop once we reach the first point again
if p == indexMinX:
break
var points = @[Point(x: 16, y: 3),
Point(x: 12, y: 17),
Point(x: 0, y: 6),
Point(x: -4, y: -6),
Point(x: 16, y: 6),
Point(x: 16, y: -7),
Point(x: 17, y: -4),
Point(x: 5, y: 19),
Point(x: 19, y: -8),
Point(x: 3, y: 16),
Point(x: 12, y: 13),
Point(x: 3, y: -4),
Point(x: 17, y: 5),
Point(x: -3, y: 15),
Point(x: -3, y: -9),
Point(x: 0, y: 11),
Point(x: -9, y: -3),
Point(x: -4, y: -2),
Point(x: 12, y: 10)]
let hull = calculateConvexHull(points)
for i in hull:
echo i |
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).
| #Prolog | Prolog | :- use_module(library(clpfd)).
% helper to perform the operation with just a number.
compound_time(N) :-
times(N, R),
format('~p: ', N),
write_times(R).
% write out the results in the 'special' format.
write_times([[Tt, Val]|T]) :-
dif(T, []),
format('~w ~w, ', [Val, Tt]),
write_times(T).
write_times([[Tt, Val]|[]]) :-
format('~w ~w~n', [Val, Tt]).
% this predicate is the main predicate, it takes either N
% or a list of split values to get N, or both.
times(N, R) :-
findall(T, time_type(T,_), TTs),
times(TTs, N, R).
% do the split, if there is a 1 or greater add to a list of results.
times([], _, []).
times([Tt|T], N, Rest) :-
time_type(Tt, Div),
Val #= N // Div,
Val #< 1,
times(T, N, Rest).
times([Tt|T], N, [[Tt,Val]|Rest]) :-
time_type(Tt, Div),
Val #= N // Div,
Val #>= 1,
Rem #= N mod Div,
times(T, Rem, Rest).
% specifify the different time split types
time_type(wk, 60 * 60 * 24 * 7).
time_type(d, 60 * 60 * 24).
time_type(hr, 60 * 60).
time_type(min, 60).
time_type(sec, 1). |
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.
| #EchoLisp | EchoLisp |
(lib 'tasks) ;; use the tasks library
(define (tprint line ) ;; task definition
(writeln _TASK line)
#f )
(for-each task-run ;; run three // tasks
(map (curry make-task tprint) '(Enjoy Rosetta code )))
→
#task:id:66:running Rosetta
#task:id:67:running code
#task:id:65:running Enjoy
|
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.
| #Egel | Egel |
import "prelude.eg"
import "io.ego"
using System
using IO
def main =
let _ = par (par [_ -> print "enjoy\n"]
[_ -> print "rosetta\n"])
[_ -> print "code\n"] in nop
|
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
| #Mathematica_.2F_Wolfram_Language | Mathematica / Wolfram Language | NormalMatrixQ[a_List?MatrixQ] := Module[{b = Conjugate@Transpose@a},a.b === b.a]
UnitaryQ[m_List?MatrixQ] := (Conjugate@[email protected] == IdentityMatrix@Length@m)
m = {{1, 2I, 3}, {3+4I, 5, I}};
m //MatrixForm
->
(1 2I 3
3+4I 5 I)
ConjugateTranspose[m] //MatrixForm
->
(1 3-4I
-2I 5
3 -I)
{HermitianMatrixQ@#, NormalMatrixQ@#, UnitaryQ@#}&@m
-> {False, False, False} |
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
| #Nim | Nim | import complex, strformat
type Matrix[M, N: static Positive] = array[M, array[N, Complex[float]]]
const Eps = 1e-10 # Tolerance used for float comparisons.
####################################################################################################
# Templates.
template `[]`(m: Matrix; i, j: Natural): Complex[float] =
## Allow to get value of an element using m[i, j] syntax.
m[i][j]
template `[]=`(m: var Matrix; i, j: Natural; val: Complex[float]) =
## Allow to set value of an element using m[i, j] syntax.
m[i][j] = val
####################################################################################################
# General operations.
func `$`(m: Matrix): string =
## Return the string representation of a matrix using one line per row.
for i, row in m:
result.add(if i == 0: '[' else: ' ')
for j, val in row:
if j != 0: result.add(' ')
result.add(&"({val.re:7.4f}, {val.im:7.4f})")
result.add(if i == m.high: ']' else: '\n')
#---------------------------------------------------------------------------------------------------
func conjugateTransposed[M, N: static int](m: Matrix[M, N]): Matrix[N, M] =
## Return the conjugate transpose of a matrix.
for i in 0..<m.M:
for j in 0..<m.N:
result[j, i] = m[i, j].conjugate()
#---------------------------------------------------------------------------------------------------
func `*`[M, K, N: static int](m1: Matrix[M, K]; m2: Matrix[K, N]): Matrix[M, N] =
# Compute the product of two matrices.
for i in 0..<M:
for j in 0..<N:
for k in 0..<K:
result[i, j] = result[i, j] + m1[i, k] * m2[k, j]
####################################################################################################
# Properties.
func isHermitian(m: Matrix): bool =
## Check if a matrix is hermitian.
when m.M != m.N:
{.error: "hermitian test only allowed for square matrices".}
else:
for i in 0..<m.M:
for j in i..<m.N:
if m[i, j] != m[j, i].conjugate:
return false
result = true
#---------------------------------------------------------------------------------------------------
func isNormal(m: Matrix): bool =
## Check if a matrix is normal.
when m.M != m.N:
{.error: "normal test only allowed for square matrices".}
else:
let h = m.conjugateTransposed
result = m * h == h * m
#---------------------------------------------------------------------------------------------------
func isIdentity(m: Matrix): bool =
## Check if a matrix is the identity matrix.
when m.M != m.N:
{.error: "identity test only allowed for square matrices".}
else:
for i in 0..<m.M:
for j in 0..<m.N:
if i == j:
if abs(m[i, j] - 1.0) > Eps:
return false
else:
if abs(m[i, j]) > Eps:
return false
result = true
#---------------------------------------------------------------------------------------------------
func isUnitary(m: Matrix): bool =
## Check if a matrix is unitary.
when m.M != m.N:
{.error: "unitary test only allowed for square matrices".}
else:
let h = m.conjugateTransposed
result = (m * h).isIdentity and (h * m).isIdentity
#———————————————————————————————————————————————————————————————————————————————————————————————————
when isMainModule:
import math
proc test(m: Matrix) =
echo "\n"
echo "Matrix"
echo "------"
echo m
echo ""
echo "Conjugate transposed"
echo "--------------------"
echo m.conjugateTransposed
when m.M == m.N:
# Only for squares matrices.
echo ""
echo "Hermitian: ", m.isHermitian
echo "Normal: ", m.isNormal
echo "Unitary: ", m.isUnitary
#-------------------------------------------------------------------------------------------------
# Non square matrix.
const M1: Matrix[2, 3] = [[1.0 + im 2.0, 3.0 + im 0.0, 2.0 + im 5.0],
[3.0 - im 1.0, 2.0 + im 0.0, 0.0 + im 3.0]]
# Square matrices.
const M2: Matrix[2, 2] = [[3.0 + im 0.0, 2.0 + im 1.0],
[2.0 - im 1.0, 1.0 + im 0.0]]
const M3: Matrix[3, 3] = [[1.0 + im 0.0, 1.0 + im 0.0, 0.0 + im 0.0],
[0.0 + im 0.0, 1.0 + im 0.0, 1.0 + im 0.0],
[1.0 + im 0.0, 0.0 + im 0.0, 1.0 + im 0.0]]
const SR2 = 1 / sqrt(2.0)
const M4: Matrix[3, 3] = [[SR2 + im 0.0, SR2 + im 0.0, 0.0 + im 0.0],
[0.0 + im SR2, 0.0 - im SR2, 0.0 + im 0.0],
[0.0 + im 0.0, 0.0 + im 0.0, 0.0 + im 1.0]]
test(M1)
test(M2)
test(M3)
test(M4) |
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
| #Clean | Clean | :: Point = { x :: Int, y :: Int } |
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
| #Clojure | Clojure | (defrecord Point [x 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.
| #PL.2FI | PL/I | /* Version for SQRT(2) */
test: proc options (main);
declare n fixed;
denom: procedure (n) recursive returns (float (18));
declare n fixed;
n = n + 1;
if n > 100 then return (2);
return (2 + 1/denom(n));
end denom;
put (1 + 1/denom(2));
end test; |
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
| #Objective-C | Objective-C | NSString *original = @"Literal String";
NSString *new = [original copy];
NSString *anotherNew = [NSString stringWithString:original];
NSString *newMutable = [original mutableCopy]; |
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
| #OCaml | OCaml | let src = "foobar" |
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.
| #Java | Java | import java.util.Random;
public class FuzzyCircle {
static final Random rnd = new Random();
public static void main(String[] args){
char[][] field = new char[31][31];
for(int i = 0; i < field.length; i++){
for(int j = 0; j < field[i].length; j++){
field[i][j] = ' ';
}
}
int pointsInDisc = 0;
while(pointsInDisc < 100){
int x = rnd.nextInt(31) - 15;
int y = rnd.nextInt(31) - 15;
double dist = Math.hypot(x, y);
if(dist >= 10 && dist <= 15 && field[x + 15][y + 15] == ' '){
field[x + 15][y + 15] = 'X';
pointsInDisc++;
}
}
for(char[] row:field){
for(char space:row){
System.out.print(space);
}
System.out.println();
}
}
} |
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/
| #ObjectIcon | ObjectIcon | # -*- ObjectIcon -*-
#
# 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
#
import io
import ipl.sort
class PlanePoint () # Enough plane geometry for our purpose.
private readable x, y
public new (x, y)
self.x := x
self.y := y
return
end
public equals (other)
if self.x = other.x & self.y = other.y then
return
else
fail
end
# Impose a total order on points, making it one that will work for
# Andrew's monotone chain algorithm. *)
public comes_before (other)
if (self.x < other.x) | (self.x = other.x & self.y < other.y) then
return
else
fail
end
# Subtraction is really a vector or multivector operation.
public minus (other)
return PlanePoint (self.x - other.x, self.y - other.y)
end
# Cross product is really a multivector operation.
public cross (other)
return (self.x * other.y) - (self.y * other.x)
end
public to_string ()
return "(" || string (self.x) || " " || string (self.y) || ")"
end
end
# Comparison like C's strcmp(3).
procedure compare_points (p, q)
local cmp
if p.comes_before (q) then
cmp := -1
else if q.comes_before (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 {
unless 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 &
(hull[j].minus (hull[j - 1])).cross (pt[i].minus (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 &
(hull[j].minus (hull[j - 1])).cross (pt[-i].minus (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 points_equal (p, q)
if p.equals (q) then
return
else
fail
end
procedure find_convex_hull (points)
local pt, hull
if *points = 0 then {
hull := []
} else {
pt := delete_neighbor_dups (sort_points (points), points_equal)
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 ((!hull).to_string ())
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).
| #PureBasic | PureBasic |
EnableExplicit
Procedure.s ConvertSeconds(NbSeconds)
Protected weeks, days, hours, minutes, seconds
Protected divisor, remainder
Protected duration$ = ""
divisor = 7 * 24 * 60 * 60 ; seconds in a week
weeks = NbSeconds / divisor
remainder = NbSeconds % divisor
divisor / 7 ; seconds in a day
days = remainder / divisor
remainder % divisor
divisor / 24 ; seconds in an hour
hours = remainder / divisor
remainder % divisor
divisor / 60 ; seconds in a minute
minutes = remainder / divisor
seconds = remainder % divisor
If weeks > 0
duration$ + Str(weeks) + " wk, "
EndIf
If days > 0
duration$ + Str(days) + " d, "
EndIf
If hours > 0
duration$ + Str(hours) + " hr, "
EndIf
If minutes > 0
duration$ + Str(minutes) + " min, "
EndIf
If seconds > 0
duration$ + Str(seconds) + " sec"
EndIf
If Right(duration$, 2) = ", "
duration$ = Mid(duration$, 0, Len(duration$) - 2)
EndIf
ProcedureReturn duration$
EndProcedure
If OpenConsole()
PrintN(ConvertSeconds(7259))
PrintN(ConvertSeconds(86400))
PrintN(ConvertSeconds(6000000))
PrintN("")
PrintN("Press any key to close the console")
Repeat: Delay(10) : Until Inkey() <> ""
CloseConsole()
EndIf
|
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.
| #Elixir | Elixir | defmodule Concurrent do
def computing(xs) do
Enum.each(xs, fn x ->
spawn(fn ->
Process.sleep(:rand.uniform(1000))
IO.puts x
end)
end)
Process.sleep(1000)
end
end
Concurrent.computing ["Enjoy", "Rosetta", "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.
| #Erlang | Erlang | -module(hw).
-export([start/0]).
start() ->
[ spawn(fun() -> say(self(), X) end) || X <- ['Enjoy', 'Rosetta', 'Code'] ],
wait(2),
ok.
say(Pid,Str) ->
io:fwrite("~s~n",[Str]),
Pid ! done.
wait(N) ->
receive
done -> case N of
0 -> 0;
_N -> wait(N-1)
end
end. |
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
| #PARI.2FGP | PARI/GP | conjtranspose(M)=conj(M~)
isHermitian(M)=M==conj(M~)
isnormal(M)=my(H=conj(M~));H*M==M*H
isunitary(M)=M*conj(M~)==1 |
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
| #Perl | Perl | use strict;
use English;
use Math::Complex;
use Math::MatrixReal;
my @examples = (example1(), example2(), example3());
foreach my $m (@examples) {
print "Starting matrix:\n", cmat_as_string($m), "\n";
my $m_ct = conjugate_transpose($m);
print "Its conjugate transpose:\n", cmat_as_string($m_ct), "\n";
print "Is Hermitian? ", (cmats_are_equal($m, $m_ct) ? 'TRUE' : 'FALSE'), "\n";
my $product = $m_ct * $m;
print "Is normal? ", (cmats_are_equal($product, $m * $m_ct) ? 'TRUE' : 'FALSE'), "\n";
my $I = identity(($m->dim())[0]);
print "Is unitary? ", (cmats_are_equal($product, $I) ? 'TRUE' : 'FALSE'), "\n";
print "\n";
}
exit 0;
sub cmats_are_equal {
my ($m1, $m2) = @ARG;
my $max_norm = 1.0e-7;
return abs($m1 - $m2) < $max_norm; # Math::MatrixReal overloads abs().
}
# Note that Math::Complex and Math::MatrixReal both overload '~', for
# complex conjugates and matrix transpositions respectively.
sub conjugate_transpose {
my $m_T = ~ shift;
my $result = $m_T->each(sub {~ $ARG[0]});
return $result;
}
sub cmat_as_string {
my $m = shift;
my $n_rows = ($m->dim())[0];
my @row_strings = map { q{[} . join(q{, }, $m->row($ARG)->as_list) . q{]} }
(1 .. $n_rows);
return join("\n", @row_strings);
}
sub identity {
my $N = shift;
my $m = new Math::MatrixReal($N, $N);
$m->one();
return $m;
}
sub example1 {
my $m = new Math::MatrixReal(2, 2);
$m->assign(1, 1, cplx(3, 0));
$m->assign(1, 2, cplx(2, 1));
$m->assign(2, 1, cplx(2, -1));
$m->assign(2, 2, cplx(1, 0));
return $m;
}
sub example2 {
my $m = new Math::MatrixReal(3, 3);
$m->assign(1, 1, cplx(1, 0));
$m->assign(1, 2, cplx(1, 0));
$m->assign(1, 3, cplx(0, 0));
$m->assign(2, 1, cplx(0, 0));
$m->assign(2, 2, cplx(1, 0));
$m->assign(2, 3, cplx(1, 0));
$m->assign(3, 1, cplx(1, 0));
$m->assign(3, 2, cplx(0, 0));
$m->assign(3, 3, cplx(1, 0));
return $m;
}
sub example3 {
my $m = new Math::MatrixReal(3, 3);
$m->assign(1, 1, cplx(0.70710677, 0));
$m->assign(1, 2, cplx(0.70710677, 0));
$m->assign(1, 3, cplx(0, 0));
$m->assign(2, 1, cplx(0, -0.70710677));
$m->assign(2, 2, cplx(0, 0.70710677));
$m->assign(2, 3, cplx(0, 0));
$m->assign(3, 1, cplx(0, 0));
$m->assign(3, 2, cplx(0, 0));
$m->assign(3, 3, cplx(0, 1));
return $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
| #CLU | CLU | % Definitions
point = struct[x, y: int]
mutable_point = record[x, y: int]
% Initialization
p: point := point${x: 10, y: 20}
mp: mutable_point := mutable_point${x: 10, y: 20} |
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
| #COBOL | COBOL |
01 Point.
05 x pic 9(3).
05 y pic 9(3).
|
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.
| #Prolog | Prolog | continued_fraction :-
% square root 2
continued_fraction(200, sqrt_2_ab, V1),
format('sqrt(2) = ~w~n', [V1]),
% napier
continued_fraction(200, napier_ab, V2),
format('e = ~w~n', [V2]),
% pi
continued_fraction(200, pi_ab, V3),
format('pi = ~w~n', [V3]).
% code for continued fractions
continued_fraction(N, Compute_ab, V) :-
continued_fraction(N, Compute_ab, 0, V).
continued_fraction(0, Compute_ab, Temp, V) :-
call(Compute_ab, 0, A, _),
V is A + Temp.
continued_fraction(N, Compute_ab, Tmp, V) :-
call(Compute_ab, N, A, B),
Tmp1 is B / (A + Tmp),
N1 is N - 1,
continued_fraction(N1, Compute_ab, Tmp1, V).
% specific codes for examples
% definitions for square root of 2
sqrt_2_ab(0, 1, 1).
sqrt_2_ab(_, 2, 1).
% definitions for napier
napier_ab(0, 2, _).
napier_ab(1, 1, 1).
napier_ab(N, N, V) :-
V is N - 1.
% definitions for pi
pi_ab(0, 3, _).
pi_ab(N, 6, V) :-
V is (2 * N - 1)*(2 * N - 1). |
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
| #Octave | Octave | str2 = 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
| #Oforth | Oforth | "abcde" dup |
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.
| #JavaScript | JavaScript | <html><head><title>Circle</title></head>
<body>
<canvas id="cv" width="320" height="320"></canvas>
<script type="application/javascript">
var cv = document.getElementById('cv');
var ctx = cv.getContext('2d');
var w = cv.width;
var h = cv.height;
//draw circles
ctx.fillStyle = 'rgba(0, 255, 200, .3)';
ctx.strokeStyle = 'rgba(0,0,0,.1)';
ctx.beginPath();
ctx.arc(w/2, h/2, 150, 0, Math.PI*2, true);
ctx.arc(w/2, h/2, 100, 0, Math.PI*2, false);
ctx.closePath();
ctx.fill();
// draw grids
ctx.beginPath();
for (var i = 10; i < w; i += 10) {
ctx.moveTo(i, 0);
ctx.lineTo(i, h);
ctx.moveTo(0, i);
ctx.lineTo(w, i);
}
ctx.closePath();
ctx.stroke();
//draw points
ctx.fillStyle = 'navy';
var pts = 0;
while (pts < 100) {
var x = Math.floor(Math.random() * 31) - 15;
var y = Math.floor(Math.random() * 31) - 15;
var r = x * x + y * y;
if (r < 100 || r > 225) continue;
x = x * 10 + w/2;
y = y * 10 + h/2;
ctx.fillRect(x - 2, y - 2, 4, 4);
pts++;
}
</script></body></html> |
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/
| #OCaml | OCaml | (*
* 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
*)
(*------------------------------------------------------------------*)
(* Just enough plane geometry for our purpose. *)
module Plane_point =
struct
type t = float * float
let make (xy : t) = xy
let to_tuple ((x, y) : t) = (x, y)
let x ((x, _) : t) = x
let y ((_, y) : t) = y
let equal (u : t) (v : t) = (x u = x v && y u = y v)
(* Impose a total order on points, making it one that will work
for Andrew's monotone chain algorithm. *)
let order (u : t) (v : t) =
(x u < x v) || (x u = x v && y u < y v)
(* The Array module's sort routines expect a "cmp" function. *)
let cmp u v =
if order u v then
(-1)
else if order v u then
(1)
else
(0)
(* Subtraction is really a vector or multivector operation. *)
let sub (u : t) (v : t) = make (x u -. x v, y u -. y v)
(* Cross product is really a multivector operation. *)
let cross (u : t) (v : t) = (x u *. y v) -. (y u *. x v)
let to_string ((x, y) : t) =
"(" ^ string_of_float x ^ " " ^ string_of_float y ^ ")"
end
;;
(*------------------------------------------------------------------*)
(* We want something akin to array_delete_neighbor_dups of Scheme's
SRFI-132. *)
let array_delete_neighbor_dups equal arr =
(* Returns a Seq.t rather than an array. *)
let rec loop i lst =
(* Cons a list of non-duplicates, going backwards through the
array so the list will be in forwards order. *)
if i = 0 then
arr.(i) :: lst
else if equal arr.(i - 1) arr.(i) then
loop (i - 1) lst
else
loop (i - 1) (arr.(i) :: lst)
in
let n = Array.length arr in
List.to_seq (if n = 0 then [] else loop (n - 1) [])
;;
(*------------------------------------------------------------------*)
(* The convex hull algorithm. *)
let cross_test pt_i hull j =
let hull_j = hull.(j)
and hull_j1 = hull.(j - 1) in
0.0 < Plane_point.(cross (sub hull_j hull_j1)
(sub pt_i hull_j1))
let construct_lower_hull n pt =
let hull = Array.make n (Plane_point.make (0.0, 0.0)) in
let () = hull.(0) <- pt.(0)
and () = hull.(1) <- pt.(1) in
let rec outer_loop i j =
if i = n then
j + 1
else
let pt_i = pt.(i) in
let rec inner_loop j =
if j = 0 || cross_test pt_i hull j then
begin
hull.(j + 1) <- pt_i;
j + 1
end
else
inner_loop (j - 1)
in
outer_loop (i + 1) (inner_loop j)
in
let hull_size = outer_loop 2 1 in
(hull_size, hull)
let construct_upper_hull n pt =
let hull = Array.make n (Plane_point.make (0.0, 0.0)) in
let () = hull.(0) <- pt.(n - 1)
and () = hull.(1) <- pt.(n - 2) in
let rec outer_loop i j =
if i = (-1) then
j + 1
else
let pt_i = pt.(i) in
let rec inner_loop j =
if j = 0 || cross_test pt_i hull j then
begin
hull.(j + 1) <- pt_i;
j + 1
end
else
inner_loop (j - 1)
in
outer_loop (i - 1) (inner_loop j)
in
let hull_size = outer_loop (n - 3) 1 in
(hull_size, hull)
let construct_hull n pt =
(* Side note: Construction of the lower and upper hulls can be done
in parallel. *)
let (lower_hull_size, lower_hull) = construct_lower_hull n pt
and (upper_hull_size, upper_hull) = construct_upper_hull n pt in
let hull_size = lower_hull_size + upper_hull_size - 2 in
let hull = Array.make hull_size (Plane_point.make (0.0, 0.0)) in
begin
Array.blit lower_hull 0 hull 0 (lower_hull_size - 1);
Array.blit upper_hull 0 hull (lower_hull_size - 1)
(upper_hull_size - 1);
hull
end
let plane_convex_hull points =
(* Takes an arbitrary sequence of points, which may be in any order
and may contain duplicates. Returns an ordered array of points
that make up the convex hull. If the sequence of points is empty,
the returned array is empty. *)
let pt = Array.of_seq points in
let () = Array.fast_sort Plane_point.cmp pt in
let pt = Array.of_seq
(array_delete_neighbor_dups Plane_point.equal pt) in
let n = Array.length pt in
if n <= 2 then
pt
else
construct_hull n pt
;;
(*------------------------------------------------------------------*)
let example_points =
[Plane_point.make (16.0, 3.0);
Plane_point.make (12.0, 17.0);
Plane_point.make (0.0, 6.0);
Plane_point.make (-4.0, -6.0);
Plane_point.make (16.0, 6.0);
Plane_point.make (16.0, -7.0);
Plane_point.make (16.0, -3.0);
Plane_point.make (17.0, -4.0);
Plane_point.make (5.0, 19.0);
Plane_point.make (19.0, -8.0);
Plane_point.make (3.0, 16.0);
Plane_point.make (12.0, 13.0);
Plane_point.make (3.0, -4.0);
Plane_point.make (17.0, 5.0);
Plane_point.make (-3.0, 15.0);
Plane_point.make (-3.0, -9.0);
Plane_point.make (0.0, 11.0);
Plane_point.make (-9.0, -3.0);
Plane_point.make (-4.0, -2.0);
Plane_point.make (12.0, 10.0)]
;;
let hull = plane_convex_hull (List.to_seq example_points)
;;
Array.iter
(fun p -> (print_string (Plane_point.to_string p);
print_string " "))
hull;
print_newline ()
;;
(*------------------------------------------------------------------*) |
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).
| #Python | Python | >>> def duration(seconds):
t= []
for dm in (60, 60, 24, 7):
seconds, m = divmod(seconds, dm)
t.append(m)
t.append(seconds)
return ', '.join('%d %s' % (num, unit)
for num, unit in zip(t[::-1], 'wk d hr min sec'.split())
if num)
>>> for seconds in [7259, 86400, 6000000]:
print("%7d sec = %s" % (seconds, duration(seconds)))
7259 sec = 2 hr, 59 sec
86400 sec = 1 d
6000000 sec = 9 wk, 6 d, 10 hr, 40 min
>>> |
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.
| #Euphoria | Euphoria | procedure echo(sequence s)
puts(1,s)
puts(1,'\n')
end procedure
atom task1,task2,task3
task1 = task_create(routine_id("echo"),{"Enjoy"})
task_schedule(task1,1)
task2 = task_create(routine_id("echo"),{"Rosetta"})
task_schedule(task2,1)
task3 = task_create(routine_id("echo"),{"Code"})
task_schedule(task3,1)
task_yield() |
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.
| #F.23 | F# | module Seq =
let piter f xs =
seq { for x in xs -> async { f x } }
|> Async.Parallel
|> Async.RunSynchronously
|> ignore
let main() = Seq.piter
(System.Console.WriteLine:string->unit)
["Enjoy"; "Rosetta"; "Code";]
main() |
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
| #Phix | Phix | with javascript_semantics
include complex.e
procedure m_print(sequence a)
a = deep_copy(a)
integer l = length(a)
for i=1 to l do
for j=1 to l do
a[i][j] = complex_sprint(a[i][j])
end for
a[i] = "["&join(a[i],",")&"]"
end for
puts(1,join(a,"\n")&"\n")
end procedure
function conjugate_transpose(sequence a)
sequence res = deep_copy(a)
integer l = length(a)
for i=1 to l do
for j=1 to l do
res[i][j] = complex_conjugate(a[j][i])
end for
end for
return res
end function
function m_unitary(sequence act)
-- note: a was normal and act = a*ct already
integer l = length(act)
for i=1 to l do
for j=1 to l do
atom {re,im} = act[i,j]
-- round to nearest billionth
-- (powers of 2 help the FPU out)
re = round(re,1024*1024*1024)
im = round(im,1024*1024*1024)
if im!=0
or (i=j and re!=1)
or (i!=j and re!=0) then
return 0
end if
end for
end for
return 1
end function
function m_mul(sequence a, sequence b)
sequence res = sq_mul(a,0)
integer l = length(a)
for i=1 to l do
for j=1 to l do
for k=1 to l do
res[i][j] = complex_add(res[i][j],complex_mul(a[i][k],b[k][j]))
end for
end for
end for
return res
end function
procedure test(sequence a)
sequence ct = conjugate_transpose(a)
printf(1,"Original matrix:\n")
m_print(a)
printf(1,"Conjugate transpose:\n")
m_print(ct)
-- note: rounding similar to that in m_unitary may be rqd (in a similar
-- loop in a new m_equal function) on these two equality tests,
-- but as it is, all tests pass with the builtin = operator.
printf(1,"Hermitian?: %t\n",a=ct) -- (this one)
sequence act = m_mul(a,ct), cta = m_mul(ct,a)
bool normal = act=cta -- (&this one)
printf(1,"Normal?: %t\n",normal)
printf(1,"Unitary?: %t\n\n",normal and m_unitary(act))
end procedure
constant x = sqrt(2)/2,
tests = {{{{3, 0},{2,1}},
{{2,-1},{1,0}}},
{{{ 1, 0},{ 1, 1},{ 0, 2}},
{{ 1,-1},{ 5, 0},{-3, 0}},
{{ 0,-2},{-3, 0},{ 0, 0}}},
{{{0.5,+0.5},{0.5,-0.5}},
{{0.5,-0.5},{0.5,+0.5}}},
{{{ 1, 0},{ 1, 0},{ 0, 0}},
{{ 0, 0},{ 1, 0},{ 1, 0}},
{{ 1, 0},{ 0, 0},{ 1, 0}}},
{{{x, 0},{x, 0},{0, 0}},
{{0,-x},{0, x},{0, 0}},
{{0, 0},{0, 0},{0, 1}}},
{{{2,7},{9,-5}},
{{3,4},{8,-6}}}}
papply(tests,test)
|
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
| #CoffeeScript | CoffeeScript |
# Lightweight JS objects (with CS sugar).
point =
x: 5
y: 3
console.log point.x, point.y # 5 3
# Heavier OO style
class Point
constructor: (@x, @y) ->
distance_from: (p2) ->
dx = p2.x - @x
dy = p2.y - @y
Math.sqrt dx*dx + dy*dy
p1 = new Point(1, 6)
p2 = new Point(6, 18)
console.log p1 # { x: 1, y: 6 }
console.log p1.distance_from # [Function]
console.log p1.distance_from p2 # 13
|
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
| #Common_Lisp | Common Lisp | CL-USER> (defstruct point (x 0) (y 0)) ;If not provided, x or y default to 0
POINT |
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.
| #Python | Python | from fractions import Fraction
import itertools
try: zip = itertools.izip
except: pass
# The Continued Fraction
def CF(a, b, t):
terms = list(itertools.islice(zip(a, b), t))
z = Fraction(1,1)
for a, b in reversed(terms):
z = a + b / z
return z
# Approximates a fraction to a string
def pRes(x, d):
q, x = divmod(x, 1)
res = str(q)
res += "."
for i in range(d):
x *= 10
q, x = divmod(x, 1)
res += str(q)
return res
# Test the Continued Fraction for sqrt2
def sqrt2_a():
yield 1
for x in itertools.repeat(2):
yield x
def sqrt2_b():
for x in itertools.repeat(1):
yield x
cf = CF(sqrt2_a(), sqrt2_b(), 950)
print(pRes(cf, 200))
#1.41421356237309504880168872420969807856967187537694807317667973799073247846210703885038753432764157273501384623091229702492483605585073721264412149709993583141322266592750559275579995050115278206057147
# Test the Continued Fraction for Napier's Constant
def Napier_a():
yield 2
for x in itertools.count(1):
yield x
def Napier_b():
yield 1
for x in itertools.count(1):
yield x
cf = CF(Napier_a(), Napier_b(), 950)
print(pRes(cf, 200))
#2.71828182845904523536028747135266249775724709369995957496696762772407663035354759457138217852516642742746639193200305992181741359662904357290033429526059563073813232862794349076323382988075319525101901
# Test the Continued Fraction for Pi
def Pi_a():
yield 3
for x in itertools.repeat(6):
yield x
def Pi_b():
for x in itertools.count(1,2):
yield x*x
cf = CF(Pi_a(), Pi_b(), 950)
print(pRes(cf, 10))
#3.1415926532 |
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
| #Ol | Ol |
(define a "The String.")
; copy the string
(define b (runes->string (string->runes a)))
(print "a: " a)
(print "b: " b)
(print "b is an a: " (eq? a b))
(print "b same as a: " (equal? a b))
; another way: marshal the string
(define c (fasl-decode (fasl-encode a) #f))
(print "a: " a)
(print "c: " c)
(print "c is an a: " (eq? a c))
(print "c same as a: " (equal? a c))
|
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.
| #Julia | Julia | function printcircle(lo::Integer, hi::Integer, ndots::Integer; pad::Integer = 2)
canvas = falses(2hi + 1, 2hi + 1)
i = 0
while i < ndots
x, y = rand(-hi:hi, 2)
if lo ^ 2 - 1 < x ^ 2 + y ^ 2 < hi ^ 2 + 1
canvas[x + hi + 1, y + hi + 1] = true
i += 1
end
end
# print
for i in 1:(2hi + 1)
row = map(j -> j ? "\u25cf " : " ", canvas[i, :])
println(" " ^ pad, join(row))
end
return canvas
end
printcircle(10, 15, 100) |
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/
| #Pascal | Pascal | {$mode ISO}
program convex_hull_task (output);
{ 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 }
const max_points = 1000;
type points_range = 0 .. max_points - 1;
type point =
record
x, y : real
end;
type point_array = array [points_range] of point;
var ciura_gaps : array [1 .. 8] of integer;
var example_points : point_array;
var hull : point_array;
var hull_size : integer;
var index : integer;
function make_point (x, y : real) : point;
begin
make_point.x := x;
make_point.y := y;
end;
{ The cross product as a signed scalar. }
function cross (u, v : point) : real;
begin
cross := (u.x * v.y) - (u.y * v.x)
end;
function point_subtract (u, v : point) : point;
begin
point_subtract := make_point (u.x - v.x, u.y - v.y)
end;
function point_equal (u, v : point) : boolean;
begin
point_equal := (u.x = v.x) and (u.y = v.y)
end;
procedure sort_points (num_points : integer;
var points : point_array);
{ Sort first in ascending order by x-coordinates, then in
ascending order by y-coordinates. Any decent sort algorithm will
suffice; for the sake of interest, here is the Shell sort of
https://en.wikipedia.org/w/index.php?title=Shellsort&oldid=1084744510 }
var
i, j, k, gap, offset : integer;
temp : point;
done : boolean;
begin
for k := 1 to 8 do
begin
gap := ciura_gaps[k];
for offset := 0 to gap - 1 do
begin
i := offset;
while i <= num_points - 1 do
begin
temp := points[i];
j := i;
done := false;
while not done do
begin
if j < gap then
done := true
else if points[j - gap].x < temp.x then
done := true
else if ((points[j - gap].x = temp.x)
and (points[j - gap].y < temp.y)) then
done := true
else
begin
points[j] := points[j - gap];
j := j - gap
end
end;
points[j] := temp;
i := i + gap
end
end
end
end; { sort_points }
procedure delete_neighbor_duplicates (var n : integer;
var pt : point_array);
procedure delete_trailing_duplicates;
var
i : integer;
done : boolean;
begin
i := n - 1;
done := false;
while not done do
begin
if i = 0 then
begin
n := 1;
done := true
end
else if not point_equal (pt[i - 1], pt[i]) then
begin
n := i + 1;
done := true
end
else
i := i + 1
end
end;
procedure delete_nontrailing_duplicates;
var
i, j, num_deleted : integer;
done : boolean;
begin
i := 0;
while i < n - 1 do
begin
j := i + 1;
done := false;
while not done do
begin
if j = n then
done := true
else if not point_equal (pt[j], pt[i]) then
done := true
else
j := j + 1
end;
if j <> i + 1 then
begin
num_deleted := j - i - 1;
while j <> n do
begin
pt[j - num_deleted] := pt[j];
j := j + 1
end;
n := n - num_deleted
end;
i := i + 1
end
end;
begin
delete_trailing_duplicates;
delete_nontrailing_duplicates
end; { delete_neighbor_duplicates }
procedure construct_lower_hull (n : integer;
pt : point_array;
var hull_size : integer;
var hull : point_array);
var
i, j : integer;
done : boolean;
begin
j := 1;
hull[0] := pt[0];
hull[1] := pt[1];
for i := 2 to n - 1 do
begin
done := false;
while not done do
begin
if j = 0 then
begin
j := j + 1;
hull[j] := pt[i];
done := true
end
else if 0.0 < cross (point_subtract (hull[j],
hull[j - 1]),
point_subtract (pt[i],
hull[j - 1])) then
begin
j := j + 1;
hull[j] := pt[i];
done := true
end
else
j := j - 1
end
end;
hull_size := j + 1
end; { construct_lower_hull }
procedure construct_upper_hull (n : integer;
pt : point_array;
var hull_size : integer;
var hull : point_array);
var
i, j : integer;
done : boolean;
begin
j := 1;
hull[0] := pt[n - 1];
hull[1] := pt[n - 2];
for i := n - 3 downto 0 do
begin
done := false;
while not done do
begin
if j = 0 then
begin
j := j + 1;
hull[j] := pt[i];
done := true
end
else if 0.0 < cross (point_subtract (hull[j],
hull[j - 1]),
point_subtract (pt[i],
hull[j - 1])) then
begin
j := j + 1;
hull[j] := pt[i];
done := true
end
else
j := j - 1
end
end;
hull_size := j + 1
end; { construct_upper_hull }
procedure contruct_hull (n : integer;
pt : point_array;
var hull_size : integer;
var hull : point_array);
var
i : integer;
lower_hull_size, upper_hull_size : integer;
lower_hull, upper_hull : point_array;
begin
{ A side note: the calls to construct_lower_hull and
construct_upper_hull could be done in parallel. }
construct_lower_hull (n, pt, lower_hull_size, lower_hull);
construct_upper_hull (n, pt, upper_hull_size, upper_hull);
hull_size := lower_hull_size + upper_hull_size - 2;
for i := 0 to lower_hull_size - 2 do
hull[i] := lower_hull[i];
for i := 0 to upper_hull_size - 2 do
hull[lower_hull_size - 1 + i] := upper_hull[i]
end; { contruct_hull }
procedure find_convex_hull (n : integer;
points : point_array;
var hull_size : integer;
var hull : point_array);
var
pt : point_array;
numpt : integer;
i : integer;
begin
for i := 0 to n - 1 do
pt[i] := points[i];
numpt := n;
sort_points (numpt, pt);
delete_neighbor_duplicates (numpt, pt);
if numpt = 0 then
hull_size := 0
else if numpt <= 2 then
begin
hull_size := numpt;
for i := 0 to numpt - 1 do
hull[i] := pt[i]
end
else
contruct_hull (numpt, pt, hull_size, hull)
end; { find_convex_hull }
begin
ciura_gaps[1] := 701;
ciura_gaps[2] := 301;
ciura_gaps[3] := 132;
ciura_gaps[4] := 57;
ciura_gaps[5] := 23;
ciura_gaps[6] := 10;
ciura_gaps[7] := 4;
ciura_gaps[8] := 1;
example_points[0] := make_point (16, 3);
example_points[1] := make_point (12, 17);
example_points[2] := make_point (0, 6);
example_points[3] := make_point (-4, -6);
example_points[4] := make_point (16, 6);
example_points[5] := make_point (16, -7);
example_points[6] := make_point (16, -3);
example_points[7] := make_point (17, -4);
example_points[8] := make_point (5, 19);
example_points[9] := make_point (19, -8);
example_points[10] := make_point (3, 16);
example_points[11] := make_point (12, 13);
example_points[12] := make_point (3, -4);
example_points[13] := make_point (17, 5);
example_points[14] := make_point (-3, 15);
example_points[15] := make_point (-3, -9);
example_points[16] := make_point (0, 11);
example_points[17] := make_point (-9, -3);
example_points[18] := make_point (-4, -2);
example_points[19] := make_point (12, 10);
find_convex_hull (19, example_points, hull_size, hull);
for index := 0 to hull_size - 1 do
writeln (hull[index].x, ' ', hull[index].y)
end.
{--------------------------------------------------------------------}
{ The Emacs Pascal mode is intolerable.
Until I can find a substitute: }
{ local variables: }
{ mode: fundamental }
{ 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).
| #Quackery | Quackery | [ ' [ 60 60 24 7 ]
witheach [ /mod swap ]
$ ""
' [ $ " wk, " $ " d, "
$ " hr, " $ " min, "
$ " sec, " ]
witheach
[ do rot dup iff
[ number$
swap join join ]
else 2drop ]
-2 split drop ] is duration$ ( n--> $ )
' [ 7259 86400 6000000 ]
witheach
[ dup echo
say " seconds is "
duration$ echo$
say "." cr ] |
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.
| #Factor | Factor | USE: concurrency.combinators
{ "Enjoy" "Rosetta" "Code" } [ print ] parallel-each |
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.
| #Forth | Forth | require tasker.fs
require random.fs
: task ( str len -- )
64 NewTask 2 swap pass
( str len -- )
10 0 do
100 random ms
pause 2dup cr type
loop 2drop ;
: main
s" Enjoy" task
s" Rosetta" task
s" Code" task
begin pause single-tasking? until ;
main |
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
| #PL.2FI | PL/I |
test: procedure options (main); /* 1 October 2012 */
declare n fixed binary;
put ('Conjugate a complex square matrix.');
put skip list ('What is the order of the matrix?:');
get (n);
begin;
declare (M, MH, MM, MM_MMH, MM_MHM, IDENTITY)(n,n) fixed complex;
declare i fixed binary;
IDENTITY = 0; do i = 1 to n; IDENTITY(I,I) = 1; end;
put skip list ('Please type the matrix:');
get list (M);
do i = 1 to n;
put skip list (M(i,*));
end;
do i = 1 to n;
MH(i,*) = conjg(M(*,i));
end;
put skip list ('The conjugate transpose is:');
do i = 1 to n;
put skip list (MH(i,*));
end;
if all(M=MH) then
put skip list ('Matrix is Hermitian');
call MMULT(M, MH, MM_MMH);
call MMULT(MH, M, MM_MHM);
if all(MM_MMH = MM_MHM) then
put skip list ('Matrix is Normal');
if all(ABS(MM_MMH - IDENTITY) < 0.0001) then
put skip list ('Matrix is unitary');
if all(ABS(MM_MHM - IDENTITY) < 0.0001) then
put skip list ('Matrix is unitary');
end;
MMULT: procedure (M, MH, MM);
declare (M, MH, MM)(*,*) fixed complex;
declare (i, j, n) fixed binary;
n = hbound(M,1);
do i = 1 to n;
do j = 1 to n;
MM(i,j) = sum(M(i,*) * MH(*,j) );
end;
end;
end MMULT;
end test;
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.