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/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
| #PowerShell | PowerShell |
function conjugate-transpose($a) {
$arr = @()
if($a) {
$n = $a.count - 1
if(0 -lt $n) {
$m = ($a | foreach {$_.count} | measure-object -Minimum).Minimum - 1
if( 0 -le $m) {
if (0 -lt $m) {
$arr =@(0)*($m+1)
foreach($i in 0..$m) {
$arr[$i] = foreach($j in 0..$n) {@([System.Numerics.complex]::Conjugate($a[$j][$i]))}
}
} else {$arr = foreach($row in $a) {[System.Numerics.complex]::Conjugate($row[0])}}
}
} else {$arr = foreach($row in $a) {[System.Numerics.complex]::Conjugate($row[0])}}
}
$arr
}
function multarrays-complex($a, $b) {
$c = @()
if($a -and $b) {
$n = $a.count - 1
$m = $b[0].count - 1
$c = @([System.Numerics.complex]::new(0,0))*($n+1)
foreach ($i in 0..$n) {
$c[$i] = foreach ($j in 0..$m) {
[System.Numerics.complex]$sum = [System.Numerics.complex]::new(0,0)
foreach ($k in 0..$n){$sum = [System.Numerics.complex]::Add($sum, ([System.Numerics.complex]::Multiply($a[$i][$k],$b[$k][$j])))}
$sum
}
}
}
$c
}
function identity-complex($n) {
if(0 -lt $n) {
$array = @(0) * $n
foreach ($i in 0..($n-1)) {
$array[$i] = @([System.Numerics.complex]::new(0,0)) * $n
$array[$i][$i] = [System.Numerics.complex]::new(1,0)
}
$array
} else { @() }
}
function are-eq ($a,$b) { -not (Compare-Object $a $b -SyncWindow 0)}
function show($a) {
if($a) {
0..($a.Count - 1) | foreach{ if($a[$_]){"$($a[$_])"}else{""} }
}
}
function complex($a,$b) {[System.Numerics.complex]::new($a,$b)}
$id2 = identity-complex 2
$m = @(@((complex 2 7), (complex 9 -5)),@((complex 3 4), (complex 8 -6)))
$hm = conjugate-transpose $m
$mhm = multarrays-complex $m $hm
$hmm = multarrays-complex $hm $m
"`$m ="
show $m
""
"`$hm = conjugate-transpose `$m ="
show $hm
""
"`$m * `$hm ="
show $mhm
""
"`$hm * `$m ="
show $hmm
""
"Hermitian? `$m = $(are-eq $m $hm)"
"Normal? `$m = $(are-eq $mhm $hmm)"
"Unitary? `$m = $((are-eq $id2 $hmm) -and (are-eq $id2 $mhm))"
|
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
| #Crystal | Crystal | struct Point(T)
getter x : T
getter y : T
def initialize(@x, @y)
end
end
puts Point(Int32).new 13, 12 #=> Point(Int32)(@x=13, @y=12) |
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
| #D | D | void main() {
// A normal POD struct
// (if it's nested and it's not static then it has a hidden
// field that points to the enclosing function):
static struct Point {
int x, y;
}
auto p1 = Point(10, 20);
// It can also be parametrized on the coordinate type:
static struct Pair(T) {
T x, y;
}
// A pair with integer coordinates:
auto p2 = Pair!int(3, 5);
// A pair with floating point coordinates:
auto p3 = Pair!double(3, 5);
// Classes (static inner):
static class PointClass {
int x, y;
this(int x_, int y_) {
this.x = x_;
this.y = y_;
}
}
auto p4 = new PointClass(1, 2);
// There are also library-defined tuples:
import std.typecons;
alias Tuple!(int,"x", int,"y") PointXY;
auto p5 = PointXY(3, 5);
// And even built-in "type tuples":
import std.typetuple;
alias TypeTuple!(int, 5) p6;
static assert(is(p6[0] == int));
static assert(p6[1] == 5);
} |
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.
| #Quackery | Quackery | [ $ "bigrat.qky" loadfile ] now!
[ 1 min
[ table
[ 1 1 ]
[ 2 1 ] ] do ] is sqrt2 ( n --> n/d )
[ dup 2 min
[ table
[ drop 2 1 ]
[ 1 ]
[ dup 1 - ] ] do ] is napier ( n --> n/d )
[ dup 1 min
[ table
[ drop 3 1 ]
[ 2 * 1 - dup *
6 swap ] ] do ] is pi ( n --> n/d )
[ ]'[ temp put
0 1
rot times
[ i 1+
temp share do
v+ 1/v ]
0 temp take do v+ ] is cf ( n --> n/d )
1000 cf sqrt2 10 point$ echo$ cr
1000 cf napier 10 point$ echo$ cr
1000 cf pi 10 point$ echo$ cr |
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.
| #Racket | Racket |
#lang racket
(define (calc cf n)
(match/values (cf 0)
[(a0 b0)
(+ a0
(for/fold ([t 0.0]) ([i (in-range (+ n 1) 0 -1)])
(match/values (cf i)
[(a b) (/ b (+ a t))])))]))
(define (cf-sqrt i) (values (if (> i 0) 2 1) 1))
(define (cf-napier i) (values (if (> i 0) i 2) (if (> i 1) (- i 1) 1)))
(define (cf-pi i) (values (if (> i 0) 6 3) (sqr (- (* 2 i) 1))))
(calc cf-sqrt 200)
(calc cf-napier 200)
(calc cf-pi 200)
|
http://rosettacode.org/wiki/Copy_a_string | Copy a string | This task is about copying a string.
Task
Where it is relevant, distinguish between copying the contents of a string
versus making an additional reference to an existing string.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #ooRexx | ooRexx | /* Rexx ***************************************************************
* 16.05.2013 Walter Pachl
**********************************************************************/
s1 = 'This is a Rexx string'
s2 = s1 /* does not copy the string */
Say 's1='s1
Say 's2='s2
i1=s1~identityhash; Say 's1~identityhash='i1
i2=s2~identityhash; Say 's2~identityhash='i2
s2 = s2~changestr('*', '*') /* creates a modified copy */
Say 's1='s1
Say 's2='s2
i1=s1~identityhash; Say 's1~identityhash='i1
i2=s2~identityhash; Say 's2~identityhash='i2 |
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
| #OxygenBasic | OxygenBasic |
string s, t="hello"
s=t
|
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.
| #Kotlin | Kotlin | // version 1.1.3
fun main(args: Array<String>) {
val r = java.util.Random()
val points = Array(31) { CharArray(31) { ' ' } }
var count = 0
while (count < 100) {
val x = r.nextInt(31) - 15
val y = r.nextInt(31) - 15
val h = x * x + y * y
if (h in 100..225) {
points[x + 15][y + 15] = 'o'
count++
}
}
for (i in 0..30) println(points[i].joinToString(""))
} |
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/
| #Perl | Perl | use strict;
use warnings;
use feature 'say';
{
package Point;
use Class::Struct;
struct( x => '$', y => '$',);
sub print { '(' . $_->x . ', ' . $_->y . ')' }
}
sub ccw {
my($a, $b, $c) = @_;
($b->x - $a->x)*($c->y - $a->y) - ($b->y - $a->y)*($c->x - $a->x);
}
sub tangent {
my($a, $b) = @_;
my $opp = $b->x - $a->x;
my $adj = $b->y - $a->y;
$adj != 0 ? $opp / $adj : 1E99;
}
sub graham_scan {
our @coords; local *coords = shift;
my @sp = sort { $a->y <=> $b->y or $a->x <=> $b->x } map { Point->new( x => $_->[0], y => $_->[1] ) } @coords;
# need at least 3 points to make a hull
return @sp if @sp < 3;
# first point on hull is minimum y point
my @h = shift @sp;
# re-sort the points by angle, secondary on x (classic Schwartzian)
@sp =
map { $sp[$_->[0]] }
sort { $b->[1] <=> $a->[1] or $a->[2] <=> $b->[2] }
map { [$_, tangent($h[0], $sp[$_]), $sp[$_]->x] }
0..$#sp;
# first point of re-sorted list is guaranteed to be on hull
push @h, shift @sp;
# check through the remaining list making sure that there is always a positive angle
for my $point (@sp) {
if (ccw( @h[-2,-1], $point ) >= 0) {
push @h, $point;
} else {
pop @h;
redo;
}
}
@h
}
my @hull_1 = graham_scan(
[[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]]
);
my @hull_2 = graham_scan(
[[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], [14,-9], [1,-9]]
);
my $list = join ' ', map { Point::print($_) } @hull_1;
say "Convex Hull (@{[scalar @hull_1]} points): [$list]";
$list = join ' ', map { Point::print($_) } @hull_2;
say "Convex Hull (@{[scalar @hull_2]} points): [$list]";
|
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).
| #Racket | Racket | #lang racket/base
(require racket/string
racket/list)
(define (seconds->compound-durations s)
(define-values (w d.h.m.s)
(for/fold ((prev-q s) (rs (list))) ((Q (in-list (list 60 60 24 7))))
(define-values (q r) (quotient/remainder prev-q Q))
(values q (cons r rs))))
(cons w d.h.m.s))
(define (maybe-suffix v n)
(and (positive? v)
(format "~a ~a" v n)))
(define (seconds->compound-duration-string s)
(string-join (filter-map maybe-suffix
(seconds->compound-durations s)
'("wk" "d" "hr" "min" "sec"))
", "))
(module+ test
(require rackunit)
(check-equal? (seconds->compound-durations 7259) (list 0 0 2 0 59))
(check-equal? (seconds->compound-durations 86400) (list 0 1 0 0 0))
(check-equal? (seconds->compound-durations 6000000) (list 9 6 10 40 0))
(check-equal? (seconds->compound-duration-string 7259) "2 hr, 59 sec")
(check-equal? (seconds->compound-duration-string 86400) "1 d")
(check-equal? (seconds->compound-duration-string 6000000) "9 wk, 6 d, 10 hr, 40 min"))
;; Tim Brown 2015-07-21 |
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).
| #Raku | Raku | sub compound-duration ($seconds) {
($seconds.polymod(60, 60, 24, 7) Z <sec min hr d wk>)
.grep(*[0]).reverse.join(", ")
}
# Demonstration:
for 7259, 86400, 6000000 {
say "{.fmt: '%7d'} sec = {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.
| #Fortran | Fortran | program concurrency
implicit none
character(len=*), parameter :: str1 = 'Enjoy'
character(len=*), parameter :: str2 = 'Rosetta'
character(len=*), parameter :: str3 = 'Code'
integer :: i
real :: h
real, parameter :: one_third = 1.0e0/3
real, parameter :: two_thirds = 2.0e0/3
interface
integer function omp_get_thread_num
end function omp_get_thread_num
end interface
interface
integer function omp_get_num_threads
end function omp_get_num_threads
end interface
! Use OpenMP to create a team of threads
!$omp parallel do private(i,h)
do i=1,20
! First time through the master thread output the number of threads
! in the team
if (omp_get_thread_num() == 0 .and. i == 1) then
write(*,'(a,i0,a)') 'Using ',omp_get_num_threads(),' threads'
end if
! Randomize the order
call random_number(h)
!$omp critical
if (h < one_third) then
write(*,'(a)') str1
else if (h < two_thirds) then
write(*,'(a)') str2
else
write(*,'(a)') str3
end if
!$omp end critical
end do
!$omp end parallel do
end program concurrency |
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
| #Python | Python | def conjugate_transpose(m):
return tuple(tuple(n.conjugate() for n in row) for row in zip(*m))
def mmul( ma, mb):
return tuple(tuple(sum( ea*eb for ea,eb in zip(a,b)) for b in zip(*mb)) for a in ma)
def mi(size):
'Complex Identity matrix'
sz = range(size)
m = [[0 + 0j for i in sz] for j in sz]
for i in range(size):
m[i][i] = 1 + 0j
return tuple(tuple(row) for row in m)
def __allsame(vector):
first, rest = vector[0], vector[1:]
return all(i == first for i in rest)
def __allnearsame(vector, eps=1e-14):
first, rest = vector[0], vector[1:]
return all(abs(first.real - i.real) < eps and abs(first.imag - i.imag) < eps
for i in rest)
def isequal(matrices, eps=1e-14):
'Check any number of matrices for equality within eps'
x = [len(m) for m in matrices]
if not __allsame(x): return False
y = [len(m[0]) for m in matrices]
if not __allsame(y): return False
for s in range(x[0]):
for t in range(y[0]):
if not __allnearsame([m[s][t] for m in matrices], eps): return False
return True
def ishermitian(m, ct):
return isequal([m, ct])
def isnormal(m, ct):
return isequal([mmul(m, ct), mmul(ct, m)])
def isunitary(m, ct):
mct, ctm = mmul(m, ct), mmul(ct, m)
mctx, mcty, cmx, ctmy = len(mct), len(mct[0]), len(ctm), len(ctm[0])
ident = mi(mctx)
return isequal([mct, ctm, ident])
def printm(comment, m):
print(comment)
fields = [['%g%+gj' % (f.real, f.imag) for f in row] for row in m]
width = max(max(len(f) for f in row) for row in fields)
lines = (', '.join('%*s' % (width, f) for f in row) for row in fields)
print('\n'.join(lines))
if __name__ == '__main__':
for matrix in [
((( 3.000+0.000j), (+2.000+1.000j)),
(( 2.000-1.000j), (+1.000+0.000j))),
((( 1.000+0.000j), (+1.000+0.000j), (+0.000+0.000j)),
(( 0.000+0.000j), (+1.000+0.000j), (+1.000+0.000j)),
(( 1.000+0.000j), (+0.000+0.000j), (+1.000+0.000j))),
((( 2**0.5/2+0.000j), (+2**0.5/2+0.000j), (+0.000+0.000j)),
(( 0.000+2**0.5/2j), (+0.000-2**0.5/2j), (+0.000+0.000j)),
(( 0.000+0.000j), (+0.000+0.000j), (+0.000+1.000j)))]:
printm('\nMatrix:', matrix)
ct = conjugate_transpose(matrix)
printm('Its conjugate transpose:', ct)
print('Hermitian? %s.' % ishermitian(matrix, ct))
print('Normal? %s.' % isnormal(matrix, ct))
print('Unitary? %s.' % isunitary(matrix, ct)) |
http://rosettacode.org/wiki/Compound_data_type | Compound data type |
Data Structure
This illustrates a data structure, a means of storing data within a program.
You may see other such structures in the Data Structures category.
Task
Create a compound data type:
Point(x,y)
A compound data type is one that holds multiple independent values.
Related task
Enumeration
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
| #Delphi | Delphi | TPoint = record
X: Longint;
Y: Longint;
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
| #E | E | def makePoint(x, y) {
def point {
to getX() { return x }
to getY() { return y }
}
return 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.
| #Raku | Raku | sub continued-fraction(:@a, :@b, Int :$n = 100)
{
my $x = @a[$n - 1];
$x = @a[$_ - 1] + @b[$_] / $x for reverse 1 ..^ $n;
$x;
}
printf "√2 ≈%.9f\n", continued-fraction(:a(1, |(2 xx *)), :b(Nil, |(1 xx *)));
printf "e ≈%.9f\n", continued-fraction(:a(2, |(1 .. *)), :b(Nil, 1, |(1 .. *)));
printf "π ≈%.9f\n", continued-fraction(:a(3, |(6 xx *)), :b(Nil, |((1, 3, 5 ... *) X** 2))); |
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
| #PARI.2FGP | PARI/GP | s1=s |
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
| #Pascal | Pascal | program in,out;
type
pString = ^string;
var
s1,s2 : string ;
pStr : pString ;
begin
/* direct copy */
s1 := 'Now is the time for all good men to come to the aid of their party.'
s2 := s1 ;
writeln(s1);
writeln(s2);
/* By Reference */
pStr := @s1 ;
writeln(pStr^);
pStr := @s2 ;
writeln(pStr^);
end; |
http://rosettacode.org/wiki/Constrained_random_points_on_a_circle | Constrained random points on a circle | Task
Generate 100 <x,y> coordinate pairs such that x and y are integers sampled from the uniform distribution with the condition that
10
≤
x
2
+
y
2
≤
15
{\displaystyle 10\leq {\sqrt {x^{2}+y^{2}}}\leq 15}
.
Then display/plot them. The outcome should be a "fuzzy" circle. The actual number of points plotted may be less than 100, given that some pairs may be generated more than once.
There are several possible approaches to accomplish this. Here are two possible algorithms.
1) Generate random pairs of integers and filter out those that don't satisfy this condition:
10
≤
x
2
+
y
2
≤
15
{\displaystyle 10\leq {\sqrt {x^{2}+y^{2}}}\leq 15}
.
2) Precalculate the set of all possible points (there are 404 of them) and select randomly from this set.
| #Lambdatalk | Lambdatalk |
{def circ
{lambda {:cx :cy :r}
{div {@ style="position:absolute;
top: {- :cy :r}px; left: {- :cx :r}px;
width: {* 2 :r}px; height: {* 2 :r}px;
border: 1px solid #000; border-radius: :rpx;"}} }}
-> circ
{def fuzzy_circle
{lambda {:cx :cy :rmin :rmax :n}
{circ :cx :cy :rmax}
{circ :cx :cy :rmin}
{S.map {{lambda {:cx :cy :rmin :rmax :i}
{let { {:cx :cx} {:cy :cy}
{:rmin :rmin} {:rmax :rmax}
{:x {- {round {* {random} {* 2 :rmax}}} :rmax}}
{:y {- {round {* {random} {* 2 :rmax}}} :rmax}}
} {let { {:x {+ :cx :x }}
{:y {+ :cy :y }}
{:rr {+ {* :x :x} {* :y :y}}}
{:r2min {* :rmin :rmin}}
{:r2max {* :rmax :rmax}}
} {if {or {< :rr :r2min} {> :rr :r2max}}
then else {circ :x :y 2}}
}}} :cx :cy :rmin :rmax}
{S.serie 1 :n}} }}
-> fuzzy_circle
{fuzzy_circle 200 700 80 120 1000}
-> plots 1000 dots between the circles r=80 and r=120 centered at [200,700]
directly in the wiki page (out of any canvas or svg contexts) as it
can be seen in http://lambdaway.free.fr/lambdawalks/?view=fuzzy_circle
|
http://rosettacode.org/wiki/Convex_hull | Convex hull | Find the points which form a convex hull from a set of arbitrary two dimensional points.
For example, given the points (16,3), (12,17), (0,6), (-4,-6), (16,6), (16,-7), (16,-3), (17,-4), (5,19), (19,-8), (3,16), (12,13), (3,-4), (17,5), (-3,15), (-3,-9), (0,11), (-9,-3), (-4,-2) and (12,10) the convex hull would be (-9,-3), (-3,-9), (19,-8), (17,5), (12,17), (5,19) and (-3,15).
See also
Convex Hull (youtube)
http://www.geeksforgeeks.org/convex-hull-set-2-graham-scan/
| #Phix | Phix | --
-- demo/rosetta/Convex_hull.exw
-- ============================
--
with javascript_semantics
constant tests = {{{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}},
{{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}, {1,-9}, {1,-9}},
{{0,0}, {5,5}, {5,0}, {0,5}},
{{0,0}, {0,1}, {0,2},
{1,0}, {1,1}, {1,2},
{2,0}, {2,1}, {2,2}},
{{-8,-8}, {-8,4}, {-8,16},
{ 4,-8}, { 4,4}, { 4,16},
{16,-8}, {16,4}, {16,16}}}
integer t = 1 -- idx to tests, for the GTITLE.
enum x, y
function ccw(sequence a, b, c)
return (b[x] - a[x]) * (c[y] - a[y])
> (b[y] - a[y]) * (c[x] - a[x])
end function
function convex_hull(sequence points)
sequence h = {}
points = sort(deep_copy(points))
/* lower hull */
for i=1 to length(points) do
while length(h)>=2
and not ccw(h[$-1], h[$], points[i]) do
h = h[1..$-1]
end while
h = append(h, points[i])
end for
/* upper hull */
integer t = length(h)+1
for i=length(points) to 1 by -1 do
while length(h)>=t
and not ccw(h[$-1],h[$],points[i]) do
h = h[1..$-1]
end while
h = append(h, points[i])
end for
h = h[1..$-1]
return h
end function
for i=1 to length(tests) do
printf(1,"For test set: ")
pp(tests[i],{pp_Indent,13,pp_Maxlen,111})
printf(1,"Convex Hull is: ")
pp(convex_hull(tests[i]))
end for
-- plots the test points in red crosses and the convex hull in green circles
include pGUI.e
include IupGraph.e
Ihandle dlg, graph
function get_data(Ihandle /*graph*/)
IupSetStrAttribute(graph, "GTITLE", "Marks Mode (%d/%d)", {t, length(tests)})
sequence tt = tests[t],
{x,y} = columnize(tt),
{cx,cy} = columnize(convex_hull(tt))
-- and close the loop:
cx &= cx[1]
cy &= cy[1]
return {{x,y,CD_RED},
{cx,cy,CD_GREEN,"HOLLOW_CIRCLE","MARKLINE"}}
end function
function key_cb(Ihandle /*ih*/, atom c)
if c=K_ESC then return IUP_CLOSE end if -- (standard practice for me)
if c=K_F5 then return IUP_DEFAULT end if -- (let browser reload work)
if c=K_LEFT then t = iff(t=1?length(tests):t-1) end if
if c=K_RIGHT then t = iff(t=length(tests)?1:t+1) end if
IupUpdate(graph)
return IUP_CONTINUE
end function
IupOpen()
graph = IupGraph(get_data,"RASTERSIZE=640x480,MODE=MARK")
dlg = IupDialog(graph,`TITLE="Convex Hull",MINSIZE=270x430`)
IupSetAttributes(graph,"XTICK=2,XMIN=-12,XMAX=20,XMARGIN=25,YTICK=2,YMIN=-12,YMAX=20")
IupSetInt(graph,"GRIDCOLOR",CD_LIGHT_GREY)
IupShow(dlg)
IupSetCallback(dlg, "K_ANY", Icallback("key_cb"))
IupSetAttribute(graph,`RASTERSIZE`,NULL)
if platform()!=JS then
IupMainLoop()
IupClose()
end if
|
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).
| #REXX | REXX | /* REXX ---------------------------------------------------------------
* Format seconds into a time string
*--------------------------------------------------------------------*/
Call test 7259 ,'2 hr, 59 sec'
Call test 86400 ,'1 d'
Call test 6000000 ,'9 wk, 6 d, 10 hr, 40 min'
Call test 123.50 ,'2 min, 3.5 sec'
Call test 123.00 ,'2 min, 3 sec'
Call test 0.00 ,'0 sec'
Exit
test:
Parse arg secs,xres
res=sec2ct(secs)
Say res
If res<>xres Then Say '**ERROR**'
Return
sec2ct:
Parse Arg s
/*
m=s%60; s=s//60
h=m%60; m=m//60
d=h%24; h=h//24
w=d%7; d=d//7
*/
If s=0 Then Return '0 sec'
Parse Value split(s,60) with m s
Parse Value split(m,60) with h m
Parse Value split(h,24) with d h
Parse Value split(d, 7) with w d
ol=''
If w>0 Then ol=ol w 'wk,'
If d>0 Then ol=ol d 'd,'
If h>0 Then ol=ol h 'hr,'
If m>0 Then ol=ol m 'min,'
If s>0 Then ol=ol (s/1) 'sec'
ol=strip(ol)
ol=strip(ol,,',')
Return ol
split: Procedure
Parse Arg what,how
a=what%how
b=what//how
Return a b |
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.
| #FreeBASIC | FreeBASIC | ' FB 1.05.0 Win64
' Compiled with -mt switch (to use threadsafe runtiume)
' The 'ThreadCall' functionality in FB is based internally on LibFFi (see [https://github.com/libffi/libffi/blob/master/LICENSE] for license)
Sub thread1()
Print "Enjoy"
End Sub
Sub thread2()
Print "Rosetta"
End Sub
Sub thread3()
Print "Code"
End Sub
Print "Press any key to print next batch of 3 strings or ESC to quit"
Print
Do
Dim t1 As Any Ptr = ThreadCall thread1
Dim t2 As Any Ptr = ThreadCall thread2
Dim t3 As Any Ptr = ThreadCall thread3
ThreadWait t1
ThreadWait t2
ThreadWait t3
Print
Sleep
Loop While Inkey <> Chr(27) |
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.
| #Go | Go | package main
import (
"fmt"
"golang.org/x/exp/rand"
"time"
)
func main() {
words := []string{"Enjoy", "Rosetta", "Code"}
seed := uint64(time.Now().UnixNano())
q := make(chan string)
for i, w := range words {
go func(w string, seed uint64) {
r := rand.New(rand.NewSource(seed))
time.Sleep(time.Duration(r.Int63n(1e9)))
q <- w
}(w, seed+uint64(i))
}
for i := 0; i < len(words); i++ {
fmt.Println(<-q)
}
} |
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
| #Racket | Racket |
#lang racket
(require math)
(define H matrix-hermitian)
(define (normal? M)
(define MH (H M))
(equal? (matrix* MH M)
(matrix* M MH)))
(define (unitary? M)
(define MH (H M))
(and (matrix-identity? (matrix* MH M))
(matrix-identity? (matrix* M MH))))
(define (hermitian? M)
(equal? (H M) M))
|
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
| #Raku | Raku | for [ # Test Matrices
[ 1, 1+i, 2i],
[ 1-i, 5, -3],
[0-2i, -3, 0]
],
[
[1, 1, 0],
[0, 1, 1],
[1, 0, 1]
],
[
[0.707 , 0.707, 0],
[0.707i, 0-0.707i, 0],
[0 , 0, i]
]
-> @m {
say "\nMatrix:";
@m.&say-it;
my @t = @m».conj.&mat-trans;
say "\nTranspose:";
@t.&say-it;
say "Is Hermitian?\t{is-Hermitian(@m, @t)}";
say "Is Normal?\t{is-Normal(@m, @t)}";
say "Is Unitary?\t{is-Unitary(@m, @t)}";
}
sub is-Hermitian (@m, @t, --> Bool) {
so @m».Complex eqv @t».Complex
}
sub is-Normal (@m, @t, --> Bool) {
so mat-mult(@m, @t)».Complex eqv mat-mult(@t, @m)».Complex
}
sub is-Unitary (@m, @t, --> Bool) {
so mat-mult(@m, @t, 1e-3)».Complex eqv mat-ident(+@m)».Complex;
}
sub mat-trans (@m) { map { [ @m[*;$_] ] }, ^@m[0] }
sub mat-ident ($n) { [ map { [ flat 0 xx $_, 1, 0 xx $n - 1 - $_ ] }, ^$n ] }
sub mat-mult (@a, @b, \ε = 1e-15) {
my @p;
for ^@a X ^@b[0] -> ($r, $c) {
@p[$r][$c] += @a[$r][$_] * @b[$_][$c] for ^@b;
@p[$r][$c].=round(ε); # avoid floating point math errors
}
@p
}
sub say-it (@array) { $_».fmt("%9s").say for @array } |
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
| #EchoLisp | EchoLisp |
(lib 'struct)
(struct Point (x y))
(Point 3 4)
→ #<Point> (3 4)
;; run-time type checking is possible
(lib 'types)
(struct Point (x y))
(struct-type Point Number Number)
(Point 3 4)
(Point 3 'albert)
❌ error: #number? : type-check failure : albert → 'Point: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
| #Ela | Ela | type Maybe = None | Some a |
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.
| #REXX | REXX | /*REXX program calculates and displays values of various continued fractions. */
parse arg terms digs .
if terms=='' | terms=="," then terms=500
if digs=='' | digs=="," then digs=100
numeric digits digs /*use 100 decimal digits for display.*/
b.=1 /*omitted ß terms are assumed to be 1.*/
/*══════════════════════════════════════════════════════════════════════════════════════*/
a.=2; call tell '√2', cf(1)
/*══════════════════════════════════════════════════════════════════════════════════════*/
a.=1; do N=2 by 2 to terms; a.N=2; end; call tell '√3', cf(1) /*also: 2∙sin(π/3) */
/*══════════════════════════════════════════════════════════════════════════════════════*/
a.=2 /* ___ */
do N=2 to 17 /*generalized √ N */
b.=N-1; NN=right(N, 2); call tell 'gen √'NN, cf(1)
end /*N*/
/*══════════════════════════════════════════════════════════════════════════════════════*/
a.=2; b.=-1/2; call tell 'gen √ ½', cf(1)
/*══════════════════════════════════════════════════════════════════════════════════════*/
do j=1 for terms; a.j=j; if j>1 then b.j=a.p; p=j; end; call tell 'e', cf(2)
/*══════════════════════════════════════════════════════════════════════════════════════*/
a.=1; call tell 'φ, phi', cf(1)
/*══════════════════════════════════════════════════════════════════════════════════════*/
a.=1; do j=1 for terms; if j//2 then a.j=j; end; call tell 'tan(1)', cf(1)
/*══════════════════════════════════════════════════════════════════════════════════════*/
do j=1 for terms; a.j=2*j+1; end; call tell 'coth(1)', cf(1)
/*══════════════════════════════════════════════════════════════════════════════════════*/
do j=1 for terms; a.j=4*j+2; end; call tell 'coth(½)', cf(2) /*also: [e+1]÷[e-1] */
/*══════════════════════════════════════════════════════════════════════════════════════*/
terms=100000
a.=6; do j=1 for terms; b.j=(2*j-1)**2; end; call tell 'π, pi', cf(3)
exit /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
cf: procedure expose a. b. terms; parse arg C; !=0; numeric digits 9+digits()
do k=terms by -1 for terms; d=a.k+!; !=b.k/d
end /*k*/
return !+C
/*──────────────────────────────────────────────────────────────────────────────────────*/
tell: parse arg ?,v; $=left(format(v)/1,1+digits()); w=50 /*50 bytes of terms*/
aT=; do k=1; _=space(aT a.k); if length(_)>w then leave; aT=_; end /*k*/
bT=; do k=1; _=space(bT b.k); if length(_)>w then leave; bT=_; end /*k*/
say right(?,8) "=" $ ' α terms='aT ...
if b.1\==1 then say right("",12+digits()) ' ß terms='bT ...
a=; b.=1; return /*only 50 bytes of α & ß terms ↑ are displayed. */ |
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
| #Perl | Perl | my $original = 'Hello.';
my $new = $original;
$new = 'Goodbye.';
print "$original\n"; # prints "Hello." |
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
| #Phix | Phix | string one = "feed"
string two = one -- (two becomes "feed", one remains "feed")
two[2..3] = "oo" -- (two becomes "food", one remains "feed")
one[1] = 'n' -- (two remains "food", one becomes "need")
?{one,two}
|
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.
| #Liberty_BASIC | Liberty BASIC | ' RC Constrained Random Points on a Circle
nomainwin
WindowWidth =400
WindowHeight =430
open "Constrained Random Points on a Circle" for graphics_nsb as #w
#w "trapclose [quit]"
#w "down ; size 7 ; color red ; fill black"
for i =1 to 1000
do
x =int( 30 *rnd( 1)) -15
y =int( 30 *rnd( 1)) -15
loop until IsInRange( x, y) =1
#w "set "; 200 +10 *x; " "; 200 - 10 *y
next
wait
function IsInRange( x, y)
z =sqr( x*x +y*y)
if 10 <=z and z <=15 then IsInRange =1 else IsInRange =0
end function
[quit]
close #w
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/
| #Python | Python | from __future__ import print_function
from shapely.geometry import MultiPoint
if __name__=="__main__":
pts = MultiPoint([(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)])
print (pts.convex_hull) |
http://rosettacode.org/wiki/Convert_seconds_to_compound_duration | Convert seconds to compound duration | Task
Write a function or program which:
takes a positive integer representing a duration in seconds as input (e.g., 100), and
returns a string which shows the same duration decomposed into:
weeks,
days,
hours,
minutes, and
seconds.
This is detailed below (e.g., "2 hr, 59 sec").
Demonstrate that it passes the following three test-cases:
Test Cases
input number
output string
7259
2 hr, 59 sec
86400
1 d
6000000
9 wk, 6 d, 10 hr, 40 min
Details
The following five units should be used:
unit
suffix used in output
conversion
week
wk
1 week = 7 days
day
d
1 day = 24 hours
hour
hr
1 hour = 60 minutes
minute
min
1 minute = 60 seconds
second
sec
However, only include quantities with non-zero values in the output (e.g., return "1 d" and not "0 wk, 1 d, 0 hr, 0 min, 0 sec").
Give larger units precedence over smaller ones as much as possible (e.g., return 2 min, 10 sec and not 1 min, 70 sec or 130 sec)
Mimic the formatting shown in the test-cases (quantities sorted from largest unit to smallest and separated by comma+space; value and unit of each quantity separated by space).
| #Ring | Ring |
sec = 6000005
week = floor(sec/60/60/24/7)
if week > 0 see sec
see " seconds is " + week + " weeks " ok
day = floor(sec/60/60/24) % 7
if day > 0 see day
see " days " ok
hour = floor(sec/60/60) % 24
if hour > 0 see hour
see " hours " ok
minute = floor(sec/60) % 60
if minute > 0 see minute
see " minutes " ok
second = sec % 60
if second > 0 see second
see " seconds" + nl ok
|
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.
| #Groovy | Groovy | 'Enjoy Rosetta Code'.tokenize().collect { w ->
Thread.start {
Thread.sleep(1000 * Math.random() as int)
println w
}
}.each { it.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.
| #Haskell | Haskell | import Control.Concurrent
main = mapM_ forkIO [process1, process2, process3] where
process1 = putStrLn "Enjoy"
process2 = putStrLn "Rosetta"
process3 = putStrLn "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
| #REXX | REXX | /*REXX program performs a conjugate transpose on a complex square matrix. */
parse arg N elements; if N==''|N=="," then N=3 /*Not specified? Then use the default.*/
k= 0; do r=1 for N
do c=1 for N; k= k+1; M.r.c= word( word(elements, k) 1, 1)
end /*c*/
end /*r*/
call showCmat 'M' ,N /*display a nicely formatted matrix. */
identity.= 0; do d=1 for N; identity.d.d= 1; end /*d*/
call conjCmat 'MH', "M" ,N /*conjugate the M matrix ───► MH */
call showCmat 'MH' ,N /*display a nicely formatted matrix. */
say 'M is Hermitian: ' word('no yes', isHermitian('M', "MH", N) + 1)
call multCmat 'M', 'MH', 'MMH', N /*multiple the two matrices together. */
call multCmat 'MH', 'M', 'MHM', N /* " " " " " */
say ' M is Normal: ' word('no yes', isHermitian('MMH', "MHM", N) + 1)
say ' M is Unary: ' word('no yes', isUnary('M', N) + 1)
say 'MMH is Unary: ' word('no yes', isUnary('MMH', N) + 1)
say 'MHM is Unary: ' word('no yes', isUnary('MHM', N) + 1)
exit /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
cP: procedure; arg ',' c; return word( strip( translate(c, , 'IJ') ) 0, 1)
rP: procedure; parse arg r ','; return word( r 0, 1) /*◄──maybe return a 0 ↑ */
/*──────────────────────────────────────────────────────────────────────────────────────*/
conjCmat: parse arg matX,matY,rows 1 cols; call normCmat matY, rows
do r=1 for rows; _=
do c=1 for cols; v= value(matY'.'r"."c)
rP= rP(v); cP= -cP(v); call value matX'.'c"."r, rP','cP
end /*c*/
end /*r*/; return
/*──────────────────────────────────────────────────────────────────────────────────────*/
isHermitian: parse arg matX,matY,rows 1 cols; call normCmat matX, rows
call normCmat matY, rows
do r=1 for rows; _=
do c=1 for cols
if value(matX'.'r"."c) \= value(matY'.'r"."c) then return 0
end /*c*/
end /*r*/; return 1
/*──────────────────────────────────────────────────────────────────────────────────────*/
isUnary: parse arg matX,rows 1 cols
do r=1 for rows; _=
do c=1 for cols; z= value(matX'.'r"."c); rP= rP(z); cP= cP(z)
if abs( sqrt( rP(z) **2 + cP(z)**2) - (r==c)) >= .0001 then return 0
end /*c*/
end /*r*/; return 1
/*──────────────────────────────────────────────────────────────────────────────────────*/
multCmat: parse arg matA,matB,matT,rows 1 cols; call value matT'.', 0
do r=1 for rows; _=
do c=1 for cols
do k=1 for cols; T= value(matT'.'r"."c); Tr= rP(T); Tc= cP(T)
A= value(matA'.'r"."k); Ar= rP(A); Ac= cP(A)
B= value(matB'.'k"."c); Br= rP(B); Bc= cP(B)
Pr= Ar*Br - Ac*Bc; Pc= Ac*Br + Ar*Bc; Tr= Tr+Pr; Tc= Tc+Pc
call value matT'.'r"."c,Tr','Tc
end /*k*/
end /*c*/
end /*r*/; return
/*──────────────────────────────────────────────────────────────────────────────────────*/
normCmat: parse arg matN,rows 1 cols
do r=1 to rows; _=
do c=1 to cols; v= translate( value(matN'.'r"."c), , "IiJj")
parse upper var v real ',' cplx
if real\=='' then real= real / 1
if cplx\=='' then cplx= cplx / 1; if cplx=0 then cplx=
if cplx\=='' then cplx= cplx"j"
call value matN'.'r"."c, strip(real','cplx, "T", ',')
end /*c*/
end /*r*/; return
/*──────────────────────────────────────────────────────────────────────────────────────*/
showCmat: parse arg matX,rows,cols; if cols=='' then cols= rows; @@= left('', 6)
say; say center('matrix' matX, 79, '─'); call normCmat matX, rows, cols
do r=1 to rows; _=
do c=1 to cols; _= _ @@ left( value(matX'.'r"."c), 9)
end /*c*/
say _
end /*r*/; say; return
/*──────────────────────────────────────────────────────────────────────────────────────*/
sqrt: procedure; parse arg x; if x=0 then return 0; d=digits(); numeric form; h=d+6
numeric digits; parse value format(x,2,1,,0) 'E0' with g 'E' _ .; g=g *.5'e'_ % 2
m.=9; do j=0 while h>9; m.j=h; h=h%2+1; end /*j*/
do k=j+5 to 0 by -1; numeric digits m.k; g=(g+x/g)*.5; end /*k*/; return g |
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
| #Elena | Elena | struct Point
{
prop int X;
prop int Y;
constructor new(int x, int y)
{
X := x;
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
| #Elixir | Elixir | iex(1)> defmodule Point do
...(1)> defstruct x: 0, y: 0
...(1)> end
{:module, Point, <<70, 79, 82, ...>>, %Point{x: 0, y: 0}}
iex(2)> origin = %Point{}
%Point{x: 0, y: 0}
iex(3)> pa = %Point{x: 10, y: 20}
%Point{x: 10, y: 20}
iex(4)> pa.x
10
iex(5)> %Point{pa | y: 30}
%Point{x: 10, y: 30}
iex(6)> %Point{x: px, y: py} = pa # pattern matching
%Point{x: 10, y: 20}
iex(7)> px
10
iex(8)> py
20 |
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.
| #Ring | Ring |
# Project : Continued fraction
see "SQR(2) = " + contfrac(1, 1, "2", "1") + nl
see " e = " + contfrac(2, 1, "n", "n") + nl
see " PI = " + contfrac(3, 1, "6", "(2*n+1)^2") + nl
func contfrac(a0, b1, a, b)
expr = ""
n = 0
while len(expr) < (700 - n)
n = n + 1
eval("temp1=" + a)
eval("temp2=" + b)
expr = expr + string(temp1) + char(43) + string(temp2) + "/("
end
str = copy(")",n)
eval("temp3=" + expr + "1" + str)
return a0 + b1 / temp3
|
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.
| #Ruby | Ruby | require 'bigdecimal'
# square root of 2
sqrt2 = Object.new
def sqrt2.a(n); n == 1 ? 1 : 2; end
def sqrt2.b(n); 1; end
# Napier's constant
napier = Object.new
def napier.a(n); n == 1 ? 2 : n - 1; end
def napier.b(n); n == 1 ? 1 : n - 1; end
pi = Object.new
def pi.a(n); n == 1 ? 3 : 6; end
def pi.b(n); (2*n - 1)**2; end
# Estimates the value of a continued fraction _cfrac_, to _prec_
# decimal digits of precision. Returns a BigDecimal. _cfrac_ must
# respond to _cfrac.a(n)_ and _cfrac.b(n)_ for integer _n_ >= 1.
def estimate(cfrac, prec)
last_result = nil
terms = prec
loop do
# Estimate continued fraction for _n_ from 1 to _terms_.
result = cfrac.a(terms)
(terms - 1).downto(1) do |n|
a = BigDecimal cfrac.a(n)
b = BigDecimal cfrac.b(n)
digits = [b.div(result, 1).exponent + prec, 1].max
result = a + b.div(result, digits)
end
result = result.round(prec)
if result == last_result
return result
else
# Double _terms_ and try again.
last_result = result
terms *= 2
end
end
end
puts estimate(sqrt2, 50).to_s('F')
puts estimate(napier, 50).to_s('F')
puts estimate(pi, 10).to_s('F') |
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
| #PHP | PHP | $src = "Hello";
$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
| #Picat | Picat | go =>
S1 = "string",
println(s1=S1),
S2 = S1,
S2[1] := 'x', % also changes S1
println(s1=S1),
println(s2=S2),
nl,
S3 = "string",
S4 = copy_term(S3),
S4[1] := 'x', % no change of S3
println(s3=S3),
println(s4=S4),
nl. |
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.
| #Locomotive_Basic | Locomotive Basic | 10 MODE 1:RANDOMIZE TIME
20 FOR J=1 TO 100
30 X=INT(RND*30-15)
40 Y=INT(RND*30-15)
50 D=X*X+Y*Y
60 IF D<100 OR D>225 THEN GOTO 40
70 PLOT 320+10*X,200+10*Y:LOCATE 1,1:PRINT J
80 NEXT
90 CALL &BB06 ' wait for key press |
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/
| #Racket | Racket | #lang typed/racket
(define-type Point (Pair Real Real))
(define-type Points (Listof Point))
(: ⊗ (Point Point Point -> Real))
(define/match (⊗ o a b)
[((cons o.x o.y) (cons a.x a.y) (cons b.x b.y))
(- (* (- a.x o.x) (- b.y o.y)) (* (- a.y o.y) (- b.x o.x)))])
(: Point<? (Point Point -> Boolean))
(define (Point<? a b)
(cond [(< (car a) (car b)) #t] [(> (car a) (car b)) #f] [else (< (cdr a) (cdr b))]))
;; Input: a list P of points in the plane.
(define (convex-hull [P:unsorted : Points])
;; Sort the points of P by x-coordinate (in case of a tie, sort by y-coordinate).
(define P (sort P:unsorted Point<?))
;; for i = 1, 2, ..., n:
;; while L contains at least two points and the sequence of last two points
;; of L and the point P[i] does not make a counter-clockwise turn:
;; remove the last point from L
;; append P[i] to L
;; TB: U is identical with (reverse P)
(define (upper/lower-hull [P : Points])
(reverse
(for/fold ((rev : Points null))
((P.i (in-list P)))
(let u/l : Points ((rev rev))
(match rev
[(list p-2 p-1 ps ...) #:when (not (positive? (⊗ p-2 P.i p-1))) (u/l (list* p-1 ps))]
[(list ps ...) (cons P.i ps)])))))
;; Initialize U and L as empty lists.
;; The lists will hold the vertices of upper and lower hulls respectively.
(let ((U (upper/lower-hull (reverse P)))
(L (upper/lower-hull P)))
;; Remove the last point of each list (it's the same as the first point of the other list).
;; Concatenate L and U to obtain the convex hull of P.
(append (drop-right L 1) (drop-right U 1)))) ; Points in the result will be listed in CCW order.)
(module+ test
(require typed/rackunit)
(check-equal?
(convex-hull
(list '(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)))
(list '(-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).
| #Ruby | Ruby | MINUTE = 60
HOUR = MINUTE*60
DAY = HOUR*24
WEEK = DAY*7
def sec_to_str(sec)
w, rem = sec.divmod(WEEK)
d, rem = rem.divmod(DAY)
h, rem = rem.divmod(HOUR)
m, s = rem.divmod(MINUTE)
units = ["#{w} wk", "#{d} d", "#{h} h", "#{m} min", "#{s} sec"]
units.reject{|str| str.start_with?("0")}.join(", ")
end
[7259, 86400, 6000000].each{|t| puts "#{t}\t: #{sec_to_str(t)}"} |
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.
| #Icon_and_Unicon | Icon and Unicon | procedure main()
L:=[ thread write("Enjoy"), thread write("Rosetta"), thread write("Code") ]
every wait(!L)
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.
| #J | J | smoutput&>({~?~@#);:'Enjoy Rosetta Code'
Rosetta
Code
Enjoy |
http://rosettacode.org/wiki/Compile-time_calculation | Compile-time calculation | Some programming languages allow calculation of values at compile time.
Task
Calculate 10! (ten factorial) at compile time.
Print the result when the program is run.
Discuss what limitations apply to compile-time calculations in your language.
| #360_Assembly | 360 Assembly | COMPCALA CSECT
L R1,=A(FACT10) r1=10!
XDECO R1,PG
XPRNT PG,L'PG print buffer
BR R14 exit
FACT10 EQU 10*9*8*7*6*5*4*3*2*1 factorial computation
PG DS CL12 |
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
| #Ruby | Ruby | require 'matrix'
# Start with some matrix.
i = Complex::I
matrix = Matrix[[i, 0, 0],
[0, i, 0],
[0, 0, i]]
# Find the conjugate transpose.
# Matrix#conjugate appeared in Ruby 1.9.2.
conjt = matrix.conj.t # aliases for matrix.conjugate.tranpose
print 'conjugate tranpose: '; puts conjt
if matrix.square?
# These predicates appeared in Ruby 1.9.3.
print 'Hermitian? '; puts matrix.hermitian?
print ' normal? '; puts matrix.normal?
print ' unitary? '; puts matrix.unitary?
else
# Matrix is not square. These predicates would
# raise ExceptionForMatrix::ErrDimensionMismatch.
print 'Hermitian? false'
print ' normal? false'
print ' unitary? false'
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
| #Elm | Elm |
--Compound Data type can hold multiple independent values
--In Elm data can be compounded using List, Tuple, Record
--In a List
point = [2,5]
--This creates a list having x and y which are independent and can be accessed by List functions
--Note that x and y must be of same data type
--Tuple is another useful data type that stores different independent values
point = (3,4)
--Here we can have multiple data types
point1 = ("x","y")
point2 = (3,4.5)
--The order of addressing matters
--Using a Record is the best option
point = {x=3,y=4}
--To access
point.x
point.y
--Or Use it as a function
.x point
.y point
--Also to alter the value
{point | x=7}
{point | y=2}
{point | x=3,y=4}
--Each time a new record is generated
--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
| #Erlang | Erlang |
-module(records_test).
-compile(export_all).
-record(point,{x,y}).
test() ->
P1 = #point{x=1.0,y=2.0}, % creates a new point record
io:fwrite("X: ~f, Y: ~f~n",[P1#point.x,P1#point.y]),
P2 = P1#point{x=3.0}, % creates a new point record with x set to 3.0, y is copied from P1
io:fwrite("X: ~f, Y: ~f~n",[P2#point.x,P2#point.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.
| #Rust | Rust |
use std::iter;
// Calculating a continued fraction is quite easy with iterators, however
// writing a proper iterator adapter is less so. We settle for a macro which
// for most purposes works well enough.
//
// One limitation with this iterator based approach is that we cannot reverse
// input iterators since they are not usually DoubleEnded. To circumvent this
// we can collect the elements and then reverse them, however this isn't ideal
// as we now have to store elements equal to the number of iterations.
//
// Another is that iterators cannot be resused once consumed, so it is often
// required to make many clones of iterators.
macro_rules! continued_fraction {
($a:expr, $b:expr ; $iterations:expr) => (
($a).zip($b)
.take($iterations)
.collect::<Vec<_>>().iter()
.rev()
.fold(0 as f64, |acc: f64, &(x, y)| {
x as f64 + (y as f64 / acc)
})
);
($a:expr, $b:expr) => (continued_fraction!($a, $b ; 1000));
}
fn main() {
// Sqrt(2)
let sqrt2a = (1..2).chain(iter::repeat(2));
let sqrt2b = iter::repeat(1);
println!("{}", continued_fraction!(sqrt2a, sqrt2b));
// Napier's Constant
let napiera = (2..3).chain(1..);
let napierb = (1..2).chain(1..);
println!("{}", continued_fraction!(napiera, napierb));
// Pi
let pia = (3..4).chain(iter::repeat(6));
let pib = (1i64..).map(|x| (2 * x - 1).pow(2));
println!("{}", continued_fraction!(pia, pib));
}
|
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
| #PicoLisp | PicoLisp | (setq Str1 "abcdef")
(setq Str2 Str1) # Create a reference to that symbol
(setq Str3 (name Str1)) # Create new symbol with name "abcdef" |
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
| #Pike | Pike | int main(){
string hi = "Hello World.";
string ih = hi;
} |
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.
| #Lua | Lua | t, n = {}, 0
for y=1,31 do t[y]={} for x=1,31 do t[y][x]=" " end end
repeat
x, y = math.random(-15,15), math.random(-15,15)
rsq = x*x + y*y
if rsq>=100 and rsq<=225 and t[y+16][x+16]==" " then
t[y+16][x+16], n = "██", n+1
end
until n==100
for y=1,31 do print(table.concat(t[y])) 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/
| #Raku | Raku | class Point {
has Real $.x is rw;
has Real $.y is rw;
method gist { [~] '(', self.x,', ', self.y, ')' };
}
sub ccw (Point $a, Point $b, Point $c) {
($b.x - $a.x)*($c.y - $a.y) - ($b.y - $a.y)*($c.x - $a.x);
}
sub tangent (Point $a, Point $b) {
my $opp = $b.x - $a.x;
my $adj = $b.y - $a.y;
$adj != 0 ?? $opp / $adj !! Inf
}
sub graham-scan (**@coords) {
# sort points by y, secondary sort on x
my @sp = @coords.map( { Point.new( :x($_[0]), :y($_[1]) ) } )
.sort: {.y, .x};
# need at least 3 points to make a hull
return @sp if +@sp < 3;
# first point on hull is minimum y point
my @h = @sp.shift;
# re-sort the points by angle, secondary on x
@sp = @sp.map( { $++ => [tangent(@h[0], $_), $_.x] } )
.sort( {-$_.value[0], $_.value[1] } )
.map: { @sp[$_.key] };
# first point of re-sorted list is guaranteed to be on hull
@h.push: @sp.shift;
# check through the remaining list making sure that
# there is always a positive angle
for @sp -> $point {
if ccw( |@h.tail(2), $point ) > 0 {
@h.push: $point;
} else {
@h.pop;
@h.push: $point and next if +@h < 2;
redo;
}
}
@h
}
my @hull = graham-scan(
(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)
);
say "Convex Hull ({+@hull} points): ", @hull;
@hull = graham-scan(
(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), (20,-9), (1,-9)
);
say "Convex Hull ({+@hull} points): ", @hull; |
http://rosettacode.org/wiki/Convert_seconds_to_compound_duration | Convert seconds to compound duration | Task
Write a function or program which:
takes a positive integer representing a duration in seconds as input (e.g., 100), and
returns a string which shows the same duration decomposed into:
weeks,
days,
hours,
minutes, and
seconds.
This is detailed below (e.g., "2 hr, 59 sec").
Demonstrate that it passes the following three test-cases:
Test Cases
input number
output string
7259
2 hr, 59 sec
86400
1 d
6000000
9 wk, 6 d, 10 hr, 40 min
Details
The following five units should be used:
unit
suffix used in output
conversion
week
wk
1 week = 7 days
day
d
1 day = 24 hours
hour
hr
1 hour = 60 minutes
minute
min
1 minute = 60 seconds
second
sec
However, only include quantities with non-zero values in the output (e.g., return "1 d" and not "0 wk, 1 d, 0 hr, 0 min, 0 sec").
Give larger units precedence over smaller ones as much as possible (e.g., return 2 min, 10 sec and not 1 min, 70 sec or 130 sec)
Mimic the formatting shown in the test-cases (quantities sorted from largest unit to smallest and separated by comma+space; value and unit of each quantity separated by space).
| #Run_BASIC | Run BASIC | sec = 6000005
week = int(sec/60/60/24/7)
day = int(sec/60/60/24) mod 7
hour = int(sec/60/60) mod 24
minute = int(sec/60) mod 60
second = sec mod 60
print sec;" seconds is ";
if week > 0 then print week;" weeks ";
if day > 0 then print day;" days ";
if hour > 0 then print hour;" hours ";
if minute > 0 then print minute;" minutes ";
if second > 0 then print second;" seconds" |
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).
| #Rust | Rust | use std::fmt;
struct CompoundTime {
w: usize,
d: usize,
h: usize,
m: usize,
s: usize,
}
macro_rules! reduce {
($s: ident, $(($from: ident, $to: ident, $factor: expr)),+) => {{
$(
$s.$to += $s.$from / $factor;
$s.$from %= $factor;
)+
}}
}
impl CompoundTime {
#[inline]
fn new(w: usize, d: usize, h: usize, m: usize, s: usize) -> Self{
CompoundTime { w: w, d: d, h: h, m: m, s: s, }
}
#[inline]
fn balance(&mut self) {
reduce!(self, (s, m, 60), (m, h, 60),
(h, d, 24), (d, w, 7));
}
}
impl fmt::Display for CompoundTime {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}w {}d {}h {}m {}s",
self.w, self.d, self.h, self.m, self.s)
}
}
fn main() {
let mut ct = CompoundTime::new(0,3,182,345,2412);
println!("Before: {}", ct);
ct.balance();
println!("After: {}", ct);
} |
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.
| #Java | Java | import java.util.concurrent.CyclicBarrier;
public class Threads
{
public static class DelayedMessagePrinter implements Runnable
{
private CyclicBarrier barrier;
private String msg;
public DelayedMessagePrinter(CyclicBarrier barrier, String msg)
{
this.barrier = barrier;
this.msg = msg;
}
public void run()
{
try
{ barrier.await(); }
catch (Exception e)
{ }
System.out.println(msg);
}
}
public static void main(String[] args)
{
CyclicBarrier barrier = new CyclicBarrier(3);
new Thread(new DelayedMessagePrinter(barrier, "Enjoy")).start();
new Thread(new DelayedMessagePrinter(barrier, "Rosetta")).start();
new Thread(new DelayedMessagePrinter(barrier, "Code")).start();
}
} |
http://rosettacode.org/wiki/Concurrent_computing | Concurrent computing | Task
Using either native language concurrency syntax or freely available libraries, write a program to display the strings "Enjoy" "Rosetta" "Code", one string per line, in random order.
Concurrency syntax must use threads, tasks, co-routines, or whatever concurrency is called in your language.
| #JavaScript | JavaScript | self.addEventListener('message', function (event) {
self.postMessage(event.data);
self.close();
}, false); |
http://rosettacode.org/wiki/Compile-time_calculation | Compile-time calculation | Some programming languages allow calculation of values at compile time.
Task
Calculate 10! (ten factorial) at compile time.
Print the result when the program is run.
Discuss what limitations apply to compile-time calculations in your language.
| #6502_Assembly | 6502 Assembly | ; Display the value of 10!, which is precomputed at assembly time
; on any Commodore 8-bit.
.ifndef __CBM__
.error "Target must be a Commodore system."
.endif
; zero-page work pointer
temp = $fb
; ROM routines used
chrout = $ffd2
.code
lda #<tenfactorial
sta temp
lda #>tenfactorial
sta temp+1
ldy #0
loop:
lda (temp),y
beq done
jsr chrout
iny
bne loop
done:
rts
.data
; the actual value to print
tenfactorial: .byte 13,"10! = ",.string(10*9*8*7*6*5*4*3*2*1),13,0 |
http://rosettacode.org/wiki/Compile-time_calculation | Compile-time calculation | Some programming languages allow calculation of values at compile time.
Task
Calculate 10! (ten factorial) at compile time.
Print the result when the program is run.
Discuss what limitations apply to compile-time calculations in your language.
| #68000_Assembly | 68000 Assembly | tenfactorial equ 10*9*8*7*6*5*4*3*2
MOVE.L #tenfactorial,D1 ;load the constant integer 10! into D1
LEA tenfactorial,A1 ;load into A1 the memory address 10! = 0x375F00
ADD.L #tenfactorial,D2 ;add 10! to whatever is stored in D2 and store the result in D2 |
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
| #Rust | Rust |
extern crate num; // crate for complex numbers
use num::complex::Complex;
use std::ops::Mul;
use std::fmt;
#[derive(Debug, PartialEq)]
struct Matrix<f32> {
grid: [[Complex<f32>; 2]; 2], // used to represent matrix
}
impl Matrix<f32> { // implements a method call for calculating the conjugate transpose
fn conjugate_transpose(&self) -> Matrix<f32> {
Matrix {grid: [[self.grid[0][0].conj(), self.grid[1][0].conj()],
[self.grid[0][1].conj(), self.grid[1][1].conj()]]}
}
}
impl Mul for Matrix<f32> { // implements '*' (multiplication) for the matrix
type Output = Matrix<f32>;
fn mul(self, other: Matrix<f32>) -> Matrix<f32> {
Matrix {grid: [[self.grid[0][0]*other.grid[0][0] + self.grid[0][1]*other.grid[1][0],
self.grid[0][0]*other.grid[0][1] + self.grid[0][1]*other.grid[1][1]],
[self.grid[1][0]*other.grid[0][0] + self.grid[1][1]*other.grid[1][0],
self.grid[1][0]*other.grid[1][0] + self.grid[1][1]*other.grid[1][1]]]}
}
}
impl Copy for Matrix<f32> {} // implemented to prevent 'moved value' errors in if statements below
impl Clone for Matrix<f32> {
fn clone(&self) -> Matrix<f32> {
*self
}
}
impl fmt::Display for Matrix<f32> { // implemented to make output nicer
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "({}, {})\n({}, {})", self.grid[0][0], self.grid[0][1], self.grid[1][0], self.grid[1][1])
}
}
fn main() {
let a = Matrix {grid: [[Complex::new(3.0, 0.0), Complex::new(2.0, 1.0)],
[Complex::new(2.0, -1.0), Complex::new(1.0, 0.0)]]};
let b = Matrix {grid: [[Complex::new(0.5, 0.5), Complex::new(0.5, -0.5)],
[Complex::new(0.5, -0.5), Complex::new(0.5, 0.5)]]};
test_type(a);
test_type(b);
}
fn test_type(mat: Matrix<f32>) {
let identity = Matrix {grid: [[Complex::new(1.0, 0.0), Complex::new(0.0, 0.0)],
[Complex::new(0.0, 0.0), Complex::new(1.0, 0.0)]]};
let mat_conj = mat.conjugate_transpose();
println!("Matrix: \n{}\nConjugate transpose: \n{}", mat, mat_conj);
if mat == mat_conj {
println!("Hermitian?: TRUE");
} else {
println!("Hermitian?: FALSE");
}
if mat*mat_conj == mat_conj*mat {
println!("Normal?: TRUE");
} else {
println!("Normal?: FALSE");
}
if mat*mat_conj == identity {
println!("Unitary?: TRUE");
} else {
println!("Unitary?: 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
| #Scala | Scala | object ConjugateTranspose {
case class Complex(re: Double, im: Double) {
def conjugate(): Complex = Complex(re, -im)
def +(other: Complex) = Complex(re + other.re, im + other.im)
def *(other: Complex) = Complex(re * other.re - im * other.im, re * other.im + im * other.re)
override def toString(): String = {
if (im < 0) {
s"${re}${im}i"
} else {
s"${re}+${im}i"
}
}
}
case class Matrix(val entries: Vector[Vector[Complex]]) {
def *(other: Matrix): Matrix = {
new Matrix(
Vector.tabulate(entries.size, other.entries(0).size)((r, c) => {
val rightRow = entries(r)
val leftCol = other.entries.map(_(c))
rightRow.zip(leftCol)
.map{ case (x, y) => x * y } // multiply pair-wise
.foldLeft(new Complex(0,0)){ case (x, y) => x + y } // sum over all
})
)
}
def conjugateTranspose(): Matrix = {
new Matrix(
Vector.tabulate(entries(0).size, entries.size)((r, c) => entries(c)(r).conjugate)
)
}
def isHermitian(): Boolean = {
this == conjugateTranspose()
}
def isNormal(): Boolean = {
val ct = conjugateTranspose()
this * ct == ct * this
}
def isIdentity(): Boolean = {
val entriesWithIndexes = for (r <- 0 until entries.size; c <- 0 until entries(r).size) yield (r, c, entries(r)(c))
entriesWithIndexes.forall { case (r, c, x) =>
if (r == c) {
x == Complex(1.0, 0.0)
} else {
x == Complex(0.0, 0.0)
}
}
}
def isUnitary(): Boolean = {
(this * conjugateTranspose()).isIdentity()
}
override def toString(): String = {
entries.map(" " + _.mkString("[", ",", "]")).mkString("[\n", "\n", "\n]")
}
}
def main(args: Array[String]): Unit = {
val m = new Matrix(
Vector.fill(3, 3)(new Complex(Math.random() * 2 - 1.0, Math.random() * 2 - 1.0))
)
println("Matrix: " + m)
println("Conjugate Transpose: " + m.conjugateTranspose())
println("Hermitian: " + m.isHermitian())
println("Normal: " + m.isNormal())
println("Unitary: " + m.isUnitary())
}
} |
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
| #Euphoria | Euphoria |
enum x, y
sequence point = {0,0}
printf(1,"x = %d, y = %3.3f\n",point)
point[x] = 'A'
point[y] = 53.42
printf(1,"x = %d, y = %3.3f\n",point)
printf(1,"x = %s, y = %3.3f\n",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.
| #Scala | Scala | object CF extends App {
import Stream._
val sqrt2 = 1 #:: from(2,0) zip from(1,0)
val napier = 2 #:: from(1) zip (1 #:: from(1))
val pi = 3 #:: from(6,0) zip (from(1,2) map {x=>x*x})
// reference values, source: wikipedia
val refPi = "3.14159265358979323846264338327950288419716939937510"
val refNapier = "2.71828182845904523536028747135266249775724709369995"
val refSQRT2 = "1.41421356237309504880168872420969807856967187537694"
def calc(cf: Stream[(Int, Int)], numberOfIters: Int=200): BigDecimal = {
(cf take numberOfIters toList).foldRight[BigDecimal](1)((a, z) => a._1+a._2/z)
}
def approx(cfV: BigDecimal, cfRefV: String): String = {
val p: Pair[Char,Char] => Boolean = pair =>(pair._1==pair._2)
((cfV.toString+" "*34).substring(0,34) zip cfRefV.toString.substring(0,34))
.takeWhile(p).foldRight[String]("")((a:Pair[Char,Char],z)=>a._1+z)
}
List(("sqrt2",sqrt2,50,refSQRT2),("napier",napier,50,refNapier),("pi",pi,3000,refPi)) foreach {t=>
val (name,cf,iters,refV) = t
val cfV = calc(cf,iters)
println(name+":")
println("ref value: "+refV.substring(0,34))
println("cf value: "+(cfV.toString+" "*34).substring(0,34))
println("precision: "+approx(cfV,refV))
println()
}
} |
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
| #PL.2FI | PL/I | declare (s1, s2) character (20) varying;
s1 = 'now is the time';
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
| #Pop11 | Pop11 | vars src, dst;
'Hello' -> src;
copy(src) -> dst; |
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.
| #Maple | Maple | a := table():
i := 1:
while i < 100 do
ba := (rand(-15 .. 15))():
bb := (rand(-15 .. 15))():
b := evalf(sqrt(ba^2+bb^2)):
if b <= 15 and b >= 10
then a[i] := [ba, bb]:
i := i+1:
end if:
end do:
plots:-pointplot(convert(a,list)); |
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/
| #RATFOR | RATFOR | #
# 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
#
# As in the Fortran 2018 version upon which this code is based, I
# shall use the built-in "complex" type to represent "points" in the
# plane. This is merely for convenience, rather than to express a
# mathematical equivalence.
#
define(point, complex)
function x (u)
# Return the x-coordinate of "point" u.
implicit none
point u
real x
x = real (u)
end
function y (u)
# Return the y-coordinate of "point" u.
implicit none
point u
real y
y = aimag (u)
end
function cross (u, v)
# Return, as a signed scalar, the cross product of "points" u and v
# (regarded as "vectors" or multivectors).
implicit none
point u, v
real cross, x, y
cross = (x (u) * y (v)) - (y (u) * x (v))
end
subroutine sortpt (numpt, pt)
# Sort "points" in ascending order, first by the x-coordinates and
# then by the 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
implicit none
integer numpt
point pt(0:*)
real x, y
integer i, j, k, gap, offset
point temp
logical done
integer gaps(1:8)
data gaps / 701, 301, 132, 57, 23, 10, 4, 1 /
for (k = 1; k <= 8; k = k + 1)
{
gap = gaps(k)
for (offset = 0; offset <= gap - 1; offset = offset + 1)
for (i = offset; i <= numpt - 1; i = i + gap)
{
temp = pt(i)
j = i
done = .false.
while (!done)
{
if (j < gap)
done = .true.
else if (x (pt(j - gap)) < x (temp))
done = .true.
else if (x (pt(j - gap)) == x (temp) _
&& (y (pt(j - gap)) <= y (temp)))
done = .true.
else
{
pt(j) = pt(j - gap)
j = j - gap
}
}
pt(j) = temp
}
}
end
subroutine deltrd (n, pt)
# Delete trailing neighbor duplicates.
implicit none
integer n
point pt(0:*)
integer i
logical done
i = n - 1
done = .false.
while (!done)
{
if (i == 0)
{
n = 1
done = .true.
}
else if (pt(i - 1) != pt(i))
{
n = i + 1
done = .true.
}
else
i = i - 1
}
end
subroutine delntd (n, pt)
# Delete non-trailing neighbor duplicates.
implicit none
integer n
point pt(0:*)
integer i, j, numdel
logical done
i = 0
while (i < n - 1)
{
j = i + 1
done = .false.
while (!done)
{
if (j == n)
done = .true.
else if (pt(j) != pt(i))
done = .true.
else
j = j + 1
}
if (j != i + 1)
{
numdel = j - i - 1
while (j != n)
{
pt(j - numdel) = pt(j)
j = j + 1
}
n = n - numdel
}
i = i + 1
}
end
subroutine deldup (n, pt)
# Delete neighbor duplicates.
implicit none
integer n
point pt(0:*)
call deltrd (n, pt)
call delntd (n, pt)
end
subroutine cxlhul (n, pt, hullsz, hull)
# Construct the lower hull.
implicit none
integer n # Number of points.
point pt(0:*)
integer hullsz # Output.
point hull(0:*) # Output.
real cross
integer i, j
logical done
j = 1
hull(0) = pt(0)
hull(1) = pt(1)
for (i = 2; i <= n - 1; i = i + 1)
{
done = .false.
while (!done)
{
if (j == 0)
{
j = j + 1
hull(j) = pt(i)
done = .true.
}
else if (0.0 < cross (hull(j) - hull(j - 1), _
pt(i) - hull(j - 1)))
{
j = j + 1
hull(j) = pt(i)
done = .true.
}
else
j = j - 1
}
}
hullsz = j + 1
end
subroutine cxuhul (n, pt, hullsz, hull)
# Construct the upper hull.
implicit none
integer n # Number of points.
point pt(0:*)
integer hullsz # Output.
point hull(0:*) # Output.
real cross
integer i, j
logical done
j = 1
hull(0) = pt(n - 1)
hull(1) = pt(n - 2)
for (i = n - 3; 0 <= i; i = i - 1)
{
done = .false.
while (!done)
{
if (j == 0)
{
j = j + 1
hull(j) = pt(i)
done = .true.
}
else if (0.0 < cross (hull(j) - hull(j - 1), _
pt(i) - hull(j - 1)))
{
j = j + 1
hull(j) = pt(i)
done = .true.
}
else
j = j - 1
}
}
hullsz = j + 1
end
subroutine cxhull (n, pt, hullsz, lhull, uhull)
# Construct the hull.
implicit none
integer n # Number of points.
point pt(0:*) # Overwritten with hull.
integer hullsz # Output.
point lhull(0:*) # Workspace.
point uhull(0:*) # Workspace
integer lhulsz, uhulsz, i
# A side note: the calls to construct_lower_hull and
# construct_upper_hull could be done in parallel.
call cxlhul (n, pt, lhulsz, lhull)
call cxuhul (n, pt, uhulsz, uhull)
hullsz = lhulsz + uhulsz - 2
for (i = 0; i <= lhulsz - 2; i = i + 1)
pt(i) = lhull(i)
for (i = 0; i <= uhulsz - 2; i = i + 1)
pt(lhulsz - 1 + i) = uhull(i)
end
subroutine cvxhul (n, pt, hullsz, lhull, uhull)
# Find a convex hull.
implicit none
integer n # Number of points.
point pt(0:*) # The contents of pt is replaced with the hull.
integer hullsz # Output.
point lhull(0:*) # Workspace.
point uhull(0:*) # Workspace
integer numpt
numpt = n
call sortpt (numpt, pt)
call deldup (numpt, pt)
if (numpt == 0)
hullsz = 0
else if (numpt <= 2)
hullsz = numpt
else
call cxhull (numpt, pt, hullsz, lhull, uhull)
end
program cvxtsk
# The Rosetta Code convex hull task.
implicit none
integer n, i
point points(0:100)
point lhull(0:100)
point uhull(0:100)
character*100 fmt
point exampl(0:19)
data exampl / (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) /
n = 20
for (i = 0; i <= n - 1; i = i + 1)
points(i) = exampl(i)
call cvxhul (n, points, n, lhull, uhull)
write (fmt, '("(", I20, ''("(", F3.0, 1X, F3.0, ") ")'', ")")') n
write (*, fmt) (points(i), i = 0, n - 1)
end |
http://rosettacode.org/wiki/Convert_seconds_to_compound_duration | Convert seconds to compound duration | Task
Write a function or program which:
takes a positive integer representing a duration in seconds as input (e.g., 100), and
returns a string which shows the same duration decomposed into:
weeks,
days,
hours,
minutes, and
seconds.
This is detailed below (e.g., "2 hr, 59 sec").
Demonstrate that it passes the following three test-cases:
Test Cases
input number
output string
7259
2 hr, 59 sec
86400
1 d
6000000
9 wk, 6 d, 10 hr, 40 min
Details
The following five units should be used:
unit
suffix used in output
conversion
week
wk
1 week = 7 days
day
d
1 day = 24 hours
hour
hr
1 hour = 60 minutes
minute
min
1 minute = 60 seconds
second
sec
However, only include quantities with non-zero values in the output (e.g., return "1 d" and not "0 wk, 1 d, 0 hr, 0 min, 0 sec").
Give larger units precedence over smaller ones as much as possible (e.g., return 2 min, 10 sec and not 1 min, 70 sec or 130 sec)
Mimic the formatting shown in the test-cases (quantities sorted from largest unit to smallest and separated by comma+space; value and unit of each quantity separated by space).
| #Scala | Scala | //Converting Seconds to Compound Duration
object seconds{
def main( args:Array[String] ){
println("Enter the no.")
val input = scala.io.StdIn.readInt()
var week_r:Int = input % 604800
var week:Int = (input - week_r)/604800
var day_r:Int = week_r % 86400
var day:Int = (week_r - day_r)/86400
var hour_r:Int = day_r % 3600
var hour:Int = (day_r - hour_r)/3600
var minute_r:Int = hour_r % 60
var minute:Int = (hour_r - minute_r)/60
var sec:Int = minute_r % 60
println("Week = " + week)
println("Day = " + day)
println("Hour = " + hour)
println("Minute = " + minute)
println("Second = " + 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.
| #Julia | Julia | words = ["Enjoy", "Rosetta", "Code"]
function sleepprint(s)
sleep(rand())
println(s)
end
@sync for word in words
@async sleepprint(word)
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.
| #Kotlin | Kotlin | // version 1.1.2
import java.util.concurrent.CyclicBarrier
class DelayedMessagePrinter(val barrier: CyclicBarrier, val msg: String) : Runnable {
override fun run() {
barrier.await()
println(msg)
}
}
fun main(args: Array<String>) {
val msgs = listOf("Enjoy", "Rosetta", "Code")
val barrier = CyclicBarrier(msgs.size)
for (msg in msgs) Thread(DelayedMessagePrinter(barrier, msg)).start()
} |
http://rosettacode.org/wiki/Compile-time_calculation | Compile-time calculation | Some programming languages allow calculation of values at compile time.
Task
Calculate 10! (ten factorial) at compile time.
Print the result when the program is run.
Discuss what limitations apply to compile-time calculations in your language.
| #Ada | Ada |
with Ada.Text_Io;
procedure CompileTimeCalculation is
Factorial : constant Integer := 10*9*8*7*6*5*4*3*2*1;
begin
Ada.Text_Io.Put(Integer'Image(Factorial));
end CompileTimeCalculation;
|
http://rosettacode.org/wiki/Compile-time_calculation | Compile-time calculation | Some programming languages allow calculation of values at compile time.
Task
Calculate 10! (ten factorial) at compile time.
Print the result when the program is run.
Discuss what limitations apply to compile-time calculations in your language.
| #AppleScript | AppleScript | -- This handler must be declared somewhere above the relevant property declaration
-- so that the compiler knows about it when compiling the property.
on factorial(n)
set f to 1
repeat with i from 2 to n
set f to f * i
end repeat
return f
end factorial
property compiledValue : factorial(10)
-- Or of course simply:
-- property compiledValue : 2 * 3 * 4 * 5 * 6 * 7 * 8 * 9 * 10
on run
return compiledValue
end run |
http://rosettacode.org/wiki/Compile-time_calculation | Compile-time calculation | Some programming languages allow calculation of values at compile time.
Task
Calculate 10! (ten factorial) at compile time.
Print the result when the program is run.
Discuss what limitations apply to compile-time calculations in your language.
| #BASIC | BASIC | CONST factorial10 = 2 * 3 * 4 * 5 * 6 * 7 * 8 * 9 * 10 |
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
| #Sidef | Sidef | func is_Hermitian (Array m, Array t) -> Bool { m == t }
func mat_mult (Array a, Array b, Number ε = -3) {
var p = []
for r, c in (^a ~X ^b[0]) {
for k in (^b) {
p[r][c] := 0 += (a[r][k] * b[k][c]) -> round!(ε)
}
}
return p
}
func mat_trans (Array m) {
var r = []
for i,j in (^m ~X ^m[0]) {
r[j][i] = m[i][j]
}
return r
}
func mat_ident (Number n) {
^n -> map {|i|
[i.of(0)..., 1, (n - i - 1).of(0)...]
}
}
func is_Normal (Array m, Array t) -> Bool {
mat_mult(m, t) == mat_mult(t, m)
}
func is_Unitary (Array m, Array t) -> Bool {
mat_mult(m, t) == mat_ident(m.len)
}
func say_it (Array a) {
a.each {|b|
b.map { "%9s" % _ }.join(' ').say
}
}
[
[
[ 1, 1+1i, 2i],
[1-1i, 5, -3],
[0-2i, -3, 0]
],
[
[1, 1, 0],
[0, 1, 1],
[1, 0, 1]
],
[
[0.707 , 0.707, 0],
[0.707i, -0.707i, 0],
[0 , 0, 1i]
]
].each { |m|
say "\nMatrix:"
say_it(m)
var t = mat_trans(m.map{.map{.conj}})
say "\nTranspose:"
say_it(t)
say "Is Hermitian?\t#{is_Hermitian(m, t)}"
say "Is Normal?\t#{is_Normal(m, t)}"
say "Is Unitary?\t#{is_Unitary(m, t)}"
} |
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
| #F.23 | F# | type Point = { x : int; y : int }
let points = [
{x = 1; y = 1};
{x = 5; y = 5} ]
Seq.iter (fun p -> printfn "%d,%d" p.x p.y) points |
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
| #Factor | Factor | TUPLE: 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.
| #Scheme | Scheme | #!r6rs
(import (rnrs base (6))
(srfi :41 streams))
(define nats (stream-cons 0 (stream-map (lambda (x) (+ x 1)) nats)))
(define (build-stream fn) (stream-map fn nats))
(define (stream-cycle s . S)
(cond
((stream-null? (car S)) stream-null)
(else (stream-cons (stream-car s)
(apply stream-cycle (append S (list (stream-cdr s))))))))
(define (cf-floor cf) (stream-car cf))
(define (cf-num cf) (stream-car (stream-cdr cf)))
(define (cf-denom cf) (stream-cdr (stream-cdr cf)))
(define (cf-integer? x) (stream-null? (stream-cdr x)))
(define (cf->real x)
(let refine ((x x) (n 65536))
(cond
((= n 0) +inf.0)
((cf-integer? x) (cf-floor x))
(else (+ (cf-floor x)
(/ (cf-num x)
(refine (cf-denom x) (- n 1))))))))
(define (real->cf x)
(let-values (((integer-part fractional-part) (div-and-mod x 1)))
(if (= fractional-part 0.0)
(stream (exact integer-part))
(stream-cons
(exact integer-part)
(stream-cons
1
(real->cf (/ fractional-part)))))))
(define sqrt2 (stream-cons 1 (stream-constant 1 2)))
(define napier
(stream-append (stream 2 1)
(stream-cycle (stream-cdr nats) (stream-cdr nats))))
(define pi
(stream-cons 3
(stream-cycle (build-stream (lambda (n) (expt (- (* 2 (+ n 1)) 1) 2)))
(stream-constant 6)))) |
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
| #PostScript | PostScript | (hello) dup length string copy |
http://rosettacode.org/wiki/Copy_a_string | Copy a string | This task is about copying a string.
Task
Where it is relevant, distinguish between copying the contents of a string
versus making an additional reference to an existing string.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #PowerShell | PowerShell | $str = "foo"
$dup = $str |
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.
| #Mathematica_.2F_Wolfram_Language | Mathematica / Wolfram Language | sample = Take[Cases[RandomInteger[{-15, 15}, {500, 2}], {x_, y_} /; 10 <= Sqrt[x^2 + y^2] <= 15], 100];
Show[{RegionPlot[10 <= Sqrt[x^2 + y^2] <= 15, {x, -16, 16}, {y, -16, 16}, Axes -> True], ListPlot[sample]}] |
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/
| #REXX | REXX | /* REXX ---------------------------------------------------------------
* Compute the Convex Hull for a set of points
* Format of the input file:
* (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)
*--------------------------------------------------------------------*/
Signal On Novalue
Signal On Syntax
Parse Arg fid
If fid='' Then Do
fid='chullmin.in' /* miscellaneous test data */
fid='chullx.in'
fid='chullt.in'
fid='chulla.in'
fid='chullxx.in'
fid='sq.in'
fid='tri.in'
fid='line.in'
fid='point.in'
fid='chull.in' /* data from task description */
End
g.0debug=''
g.0oid=fn(fid)'.txt'; 'erase' g.0oid
x.=0
yl.=''
Parse Value '1000 -1000' With g.0xmin g.0xmax
Parse Value '1000 -1000' With g.0ymin g.0ymax
/*---------------------------------------------------------------------
* First read the input and store the points' coordinates
* x.0 contains the number of points, x.i contains the x.coordinate
* yl.x contains the y.coordinate(s) of points (x/y)
*--------------------------------------------------------------------*/
Do while lines(fid)>0
l=linein(fid)
Do While l<>''
Parse Var l '(' x ',' y ')' l
Call store x,y
End
End
Call lineout fid
Do i=1 To x.0 /* loop over points */
x=x.i
yl.x=sortv(yl.x) /* sort y-coordinates */
End
Call sho
/*---------------------------------------------------------------------
* Now we look for special border points:
* lefthigh and leftlow: leftmost points with higheste and lowest y
* ritehigh and ritelow: rightmost points with higheste and lowest y
* yl.x contains the y.coordinate(s) of points (x/y)
*--------------------------------------------------------------------*/
leftlow=0
lefthigh=0
Do i=1 To x.0
x=x.i
If maxv(yl.x)=g.0ymax Then Do
If lefthigh=0 Then lefthigh=x'/'g.0ymax
ritehigh=x'/'g.0ymax
End
If minv(yl.x)=g.0ymin Then Do
ritelow=x'/'g.0ymin
If leftlow=0 Then leftlow=x'/'g.0ymin
End
End
Call o 'lefthigh='lefthigh
Call o 'ritehigh='ritehigh
Call o 'ritelow ='ritelow
Call o 'leftlow ='leftlow
/*---------------------------------------------------------------------
* Now we look for special border points:
* leftmost_n and leftmost_s: points with lowest x and highest/lowest y
* ritemost_n and ritemost_s: points with largest x and highest/lowest y
* n and s stand foNorth and South, respectively
*--------------------------------------------------------------------*/
x=g.0xmi; leftmost_n=x'/'maxv(yl.x)
x=g.0xmi; leftmost_s=x'/'minv(yl.x)
x=g.0xma; ritemost_n=x'/'maxv(yl.x)
x=g.0xma; ritemost_s=x'/'minv(yl.x)
/*---------------------------------------------------------------------
* Now we compute the paths from ritehigh to ritelow (n_end)
* and leftlow to lefthigh (s_end), respectively
*--------------------------------------------------------------------*/
x=g.0xma
n_end=''
Do i=words(yl.x) To 1 By -1
n_end=n_end x'/'word(yl.x,i)
End
Call o 'n_end='n_end
x=g.0xmi
s_end=''
Do i=1 To words(yl.x)
s_end=s_end x'/'word(yl.x,i)
End
Call o 's_end='s_end
n_high=''
s_low=''
/*---------------------------------------------------------------------
* Now we compute the upper part of the convex hull (nhull)
*--------------------------------------------------------------------*/
Call o 'leftmost_n='leftmost_n
Call o 'lefthigh ='lefthigh
nhull=leftmost_n
res=mk_nhull(leftmost_n,lefthigh);
nhull=nhull res
Call o 'A nhull='nhull
Do While res<>lefthigh
res=mk_nhull(res,lefthigh); nhull=nhull res
Call o 'B nhull='nhull
End
res=mk_nhull(lefthigh,ritemost_n); nhull=nhull res
Call o 'C nhull='nhull
Do While res<>ritemost_n
res=mk_nhull(res,ritemost_n); nhull=nhull res
Call o 'D nhull='nhull
End
nhull=nhull n_end /* attach the right vertical border */
/*---------------------------------------------------------------------
* Now we compute the lower part of the convex hull (shull)
*--------------------------------------------------------------------*/
res=mk_shull(ritemost_s,ritelow);
shull=ritemost_s res
Call o 'A shull='shull
Do While res<>ritelow
res=mk_shull(res,ritelow)
shull=shull res
Call o 'B shull='shull
End
res=mk_shull(ritelow,leftmost_s)
shull=shull res
Call o 'C shull='shull
Do While res<>leftmost_s
res=mk_shull(res,leftmost_s);
shull=shull res
Call o 'D shull='shull
End
shull=shull s_end
chull=nhull shull /* concatenate upper and lower part */
/* eliminate duplicates */
/* too lazy to take care before :-) */
Parse Var chull chullx chull
have.=0
have.chullx=1
Do i=1 By 1 While chull>''
Parse Var chull xy chull
If have.xy=0 Then Do
chullx=chullx xy
have.xy=1
End
End
/* show the result */
Say 'Points of convex hull in clockwise order:'
Say chullx
/**********************************************************************
* steps that were necessary in previous attempts
/*---------------------------------------------------------------------
* Final polish: Insert points that are not yet in chullx but should be
* First on the upper hull going from left to right
*--------------------------------------------------------------------*/
i=1
Do While i<words(chullx)
xya=word(chullx,i) ; Parse Var xya xa '/' ya
If xa=g.0xmax Then Leave
xyb=word(chullx,i+1); Parse Var xyb xb '/' yb
Do j=1 To x.0
If x.j>xa Then Do
If x.j<xb Then Do
xx=x.j
parse Value kdx(xya,xyb) With k d x
If (k*xx+d)=maxv(yl.xx) Then Do
chullx=subword(chullx,1,i) xx'/'maxv(yl.xx),
subword(chullx,i+1)
i=i+1
End
End
End
Else
i=i+1
End
End
Say chullx
/*---------------------------------------------------------------------
* Final polish: Insert points that are not yet in chullx but should be
* Then on the lower hull going from right to left
*--------------------------------------------------------------------*/
i=wordpos(ritemost_s,chullx)
Do While i<words(chullx)
xya=word(chullx,i) ; Parse Var xya xa '/' ya
If xa=g.0xmin Then Leave
xyb=word(chullx,i+1); Parse Var xyb xb '/' yb
Do j=x.0 To 1 By -1
If x.j<xa Then Do
If x.j>xb Then Do
xx=x.j
parse Value kdx(xya,xyb) With k d x
If (k*xx+d)=minv(yl.xx) Then Do
chullx=subword(chullx,1,i) xx'/'minv(yl.xx),
subword(chullx,i+1)
i=i+1
End
End
End
Else
i=i+1
End
End
Say chullx
**********************************************************************/
Call lineout g.0oid
Exit
store: Procedure Expose x. yl. g.
/*---------------------------------------------------------------------
* arrange the points in ascending order of x (in x.) and,
* for each x in ascending order of y (in yl.x)
* g.0xmin is the smallest x-value, etc.
* g.0xmi is the x-coordinate
* g.0ymin is the smallest y-value, etc.
* g.0ymi is the x-coordinate of such a point
*--------------------------------------------------------------------*/
Parse Arg x,y
Call o 'store' x y
If x<g.0xmin Then Do; g.0xmin=x; g.0xmi=x; End
If x>g.0xmax Then Do; g.0xmax=x; g.0xma=x; End
If y<g.0ymin Then Do; g.0ymin=y; g.0ymi=x; End
If y>g.0ymax Then Do; g.0ymax=y; g.0yma=x; End
Do i=1 To x.0
Select
When x.i>x Then
Leave
When x.i=x Then Do
yl.x=yl.x y
Return
End
Otherwise
Nop
End
End
Do j=x.0 To i By -1
ja=j+1
x.ja=x.j
End
x.i=x
yl.x=y
x.0=x.0+1
Return
sho: Procedure Expose x. yl. g.
Do i=1 To x.0
x=x.i
say format(i,2) 'x='format(x,3) 'yl='yl.x
End
Say ''
Return
maxv: Procedure Expose g.
Call trace 'O'
Parse Arg l
res=-1000
Do While l<>''
Parse Var l v l
If v>res Then res=v
End
Return res
minv: Procedure Expose g.
Call trace 'O'
Parse Arg l
res=1000
Do While l<>''
Parse Var l v l
If v<res Then res=v
End
Return res
sortv: Procedure Expose g.
Call trace 'O'
Parse Arg l
res=''
Do Until l=''
v=minv(l)
res=res v
l=remove(v,l)
End
Return space(res)
lastword: return word(arg(1),words(arg(1)))
kdx: Procedure Expose xy. g.
/*---------------------------------------------------------------------
* Compute slope and y-displacement of a straight line
* that is defined by two points: y=k*x+d
* Specialty; k='*' x=xa if xb=xa
*--------------------------------------------------------------------*/
Call trace 'O'
Parse Arg xya,xyb
Parse Var xya xa '/' ya
Parse Var xyb xb '/' yb
If xa=xb Then
Parse Value '*' '-' xa With k d x
Else Do
k=(yb-ya)/(xb-xa)
d=yb-k*xb
x='*'
End
Return k d x
remove:
/*---------------------------------------------------------------------
* Remove a specified element (e) from a given string (s)
*--------------------------------------------------------------------*/
Parse Arg e,s
Parse Var s sa (e) sb
Return space(sa sb)
o: Procedure Expose g.
/*---------------------------------------------------------------------
* Write a line to the debug file
*--------------------------------------------------------------------*/
If arg(2)=1 Then say arg(1)
Return lineout(g.0oid,arg(1))
is_ok: Procedure Expose x. yl. g. sigl
/*---------------------------------------------------------------------
* Test if a given point (b) is above/on/or below a straight line
* defined by two points (a and c)
*--------------------------------------------------------------------*/
Parse Arg a,b,c,op
Call o 'is_ok' a b c op
Parse Value kdx(a,c) With k d x
Parse Var b x'/'y
If op='U' Then y=maxv(yl.x)
Else y=minv(yl.x)
Call o y x (k*x+d)
If (abs(y-(k*x+d))<1.e-8) Then Return 0
If op='U' Then res=(y<=(k*x+d))
Else res=(y>=(k*x+d))
Return res
mk_nhull: Procedure Expose x. yl. g.
/*---------------------------------------------------------------------
* Compute the upper (north) hull between two points (xya and xyb)
* Move x from xyb back to xya until all points within the current
* range (x and xyb) are BELOW the straight line defined xya and x
* Then make x the new starting point
*--------------------------------------------------------------------*/
Parse Arg xya,xyb
Call o 'mk_nhull' xya xyb
If xya=xyb Then Return xya
Parse Var xya xa '/' ya
Parse Var xyb xb '/' yb
iu=0
iv=0
Do xi=1 To x.0
if x.xi>=xa & iu=0 Then iu=xi
if x.xi<=xb Then iv=xi
If x.xi>xb Then Leave
End
Call o iu iv
xu=x.iu
xyu=xu'/'maxv(yl.xu)
Do h=iv To iu+1 By -1 Until good
Call o 'iv='iv,g.0debug
Call o ' h='h,g.0debug
xh=x.h
xyh=xh'/'maxv(yl.xh)
Call o 'Testing' xyu xyh,g.0debug
good=1
Do hh=h-1 To iu+1 By -1 While good
xhh=x.hh
xyhh=xhh'/'maxv(yl.xhh)
Call o 'iu hh iv=' iu hh h,g.0debug
If is_ok(xyu,xyhh,xyh,'U') Then Do
Call o xyhh 'is under' xyu xyh,g.0debug
Nop
End
Else Do
good=0
Call o xyhh 'is above' xyu xyh '-' xyh 'ist nicht gut'
End
End
End
Call o xyh 'is the one'
Return xyh
p: Return
Say arg(1)
Pull .
Return
mk_shull: Procedure Expose x. yl. g.
/*---------------------------------------------------------------------
* Compute the lower (south) hull between two points (xya and xyb)
* Move x from xyb back to xya until all points within the current
* range (x and xyb) are ABOVE the straight line defined xya and x
* Then make x the new starting point
*-----
---------------------------------------------------------------*/
Parse Arg xya,xyb
Call o 'mk_shull' xya xyb
If xya=xyb Then Return xya
Parse Var xya xa '/' ya
Parse Var xyb xb '/' yb
iu=0
iv=0
Do xi=x.0 To 1 By -1
if x.xi<=xa & iu=0 Then iu=xi
if x.xi>=xb Then iv=xi
If x.xi<xb Then Leave
End
Call o iu iv '_' x.iu x.iv
Call o 'mk_shull iv iu' iv iu
xu=x.iu
xyu=xu'/'minv(yl.xu)
good=0
Do h=iv To iu-1 Until good
xh=x.h
xyh=xh'/'minv(yl.xh)
Call o 'Testing' xyu xyh h iu
good=1
Do hh=h+1 To iu-1 While good
Call o 'iu hh h=' iu hh h
xhh=x.hh
xyhh=xhh'/'minv(yl.xhh)
If is_ok(xyu,xyhh,xyh,'O') Then Do
Call o xyhh 'is above' xyu xyh
Nop
End
Else Do
Call o xyhh 'is under' xyu xyh '-' xyh 'ist nicht gut'
good=0
End
End
End
Call o xyh 'is the one'
Return xyh
Novalue:
Say 'Novalue raised in line' sigl
Say sourceline(sigl)
Say 'Variable' condition('D')
Signal lookaround
Syntax:
Say 'Syntax raised in line' sigl
Say sourceline(sigl)
Say 'rc='rc '('errortext(rc)')'
halt:
lookaround:
Say 'You can look around now.'
Trace ?R
Nop
Exit 12 |
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).
| #Scheme | Scheme |
(import (scheme base)
(scheme write)
(srfi 1)
(only (srfi 13) string-join))
(define *seconds-in-minute* 60)
(define *seconds-in-hour* (* 60 *seconds-in-minute*))
(define *seconds-in-day* (* 24 *seconds-in-hour*))
(define *seconds-in-week* (* 7 *seconds-in-day*))
(define (seconds->duration seconds)
(define (format val unit)
(if (zero? val) "" (string-append (number->string val) " " unit)))
(let*-values (((weeks wk-remainder) (floor/ seconds *seconds-in-week*))
((days dy-remainder) (floor/ wk-remainder *seconds-in-day*))
((hours hr-remainder) (floor/ dy-remainder *seconds-in-hour*))
((minutes mn-remainder) (floor/ hr-remainder *seconds-in-minute*)))
(string-join (delete ""
(list (format weeks "wk")
(format days "d")
(format hours "hr")
(format minutes "min")
(format mn-remainder "sec"))
string=?) ", ")))
(display (seconds->duration 7259)) (newline)
(display (seconds->duration 86400)) (newline)
(display (seconds->duration 6000000)) (newline)
|
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.
| #LFE | LFE |
;;;
;;; This is a straight port of the Erlang version.
;;;
;;; You can run this under the LFE REPL as follows:
;;;
;;; (slurp "concurrent-computing.lfe")
;;; (start)
;;;
(defmodule concurrent-computing
(export (start 0)))
(defun start ()
(lc ((<- word '("Enjoy" "Rosetta" "Code")))
(spawn (lambda () (say (self) word))))
(wait 2)
'ok)
(defun say (pid word)
(lfe_io:format "~p~n" (list word))
(! pid 'done))
(defun wait (n)
(receive
('done (case n
(0 0)
(_n (wait (- n 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.
| #Logtalk | Logtalk | :- object(concurrency).
:- initialization(output).
output :-
threaded((
write('Enjoy'),
write('Rosetta'),
write('Code')
)).
:- end_object. |
http://rosettacode.org/wiki/Compile-time_calculation | Compile-time calculation | Some programming languages allow calculation of values at compile time.
Task
Calculate 10! (ten factorial) at compile time.
Print the result when the program is run.
Discuss what limitations apply to compile-time calculations in your language.
| #C | C | #include <stdio.h>
#include <order/interpreter.h>
#define ORDER_PP_DEF_8fac ORDER_PP_FN( \
8fn(8X, 8seq_fold(8times, 1, 8seq_iota(1, 8inc(8X)))) )
int main(void) {
printf("10! = %d\n", ORDER_PP( 8to_lit( 8fac(10) ) ) );
return 0;
} |
http://rosettacode.org/wiki/Compile-time_calculation | Compile-time calculation | Some programming languages allow calculation of values at compile time.
Task
Calculate 10! (ten factorial) at compile time.
Print the result when the program is run.
Discuss what limitations apply to compile-time calculations in your language.
| #C.23 | C# | using System;
public static class Program
{
public const int FACTORIAL_10 = 10 * 9 * 8 * 7 * 6 * 5 * 4 * 3 * 2 * 1;
static void Main()
{
Console.WriteLine(FACTORIAL_10);
}
} |
http://rosettacode.org/wiki/Compile-time_calculation | Compile-time calculation | Some programming languages allow calculation of values at compile time.
Task
Calculate 10! (ten factorial) at compile time.
Print the result when the program is run.
Discuss what limitations apply to compile-time calculations in your language.
| #C.2B.2B | C++ | #include <iostream>
template<int i> struct Fac
{
static const int result = i * Fac<i-1>::result;
};
template<> struct Fac<1>
{
static const int result = 1;
};
int main()
{
std::cout << "10! = " << Fac<10>::result << "\n";
return 0;
} |
http://rosettacode.org/wiki/Conjugate_transpose | Conjugate transpose | Suppose that a matrix
M
{\displaystyle M}
contains complex numbers. Then the conjugate transpose of
M
{\displaystyle M}
is a matrix
M
H
{\displaystyle M^{H}}
containing the complex conjugates of the matrix transposition of
M
{\displaystyle M}
.
(
M
H
)
j
i
=
M
i
j
¯
{\displaystyle (M^{H})_{ji}={\overline {M_{ij}}}}
This means that row
j
{\displaystyle j}
, column
i
{\displaystyle i}
of the conjugate transpose equals the
complex conjugate of row
i
{\displaystyle i}
, column
j
{\displaystyle j}
of the original matrix.
In the next list,
M
{\displaystyle M}
must also be a square matrix.
A Hermitian matrix equals its own conjugate transpose:
M
H
=
M
{\displaystyle M^{H}=M}
.
A normal matrix is commutative in multiplication with its conjugate transpose:
M
H
M
=
M
M
H
{\displaystyle M^{H}M=MM^{H}}
.
A unitary matrix has its inverse equal to its conjugate transpose:
M
H
=
M
−
1
{\displaystyle M^{H}=M^{-1}}
.
This is true iff
M
H
M
=
I
n
{\displaystyle M^{H}M=I_{n}}
and iff
M
M
H
=
I
n
{\displaystyle MM^{H}=I_{n}}
, where
I
n
{\displaystyle I_{n}}
is the identity matrix.
Task
Given some matrix of complex numbers, find its conjugate transpose.
Also determine if the matrix is a:
Hermitian matrix,
normal matrix, or
unitary matrix.
See also
MathWorld entry: conjugate transpose
MathWorld entry: Hermitian matrix
MathWorld entry: normal matrix
MathWorld entry: unitary matrix
| #Sparkling | Sparkling | # Computes conjugate transpose of M
let conjTransp = function conjTransp(M) {
return map(range(sizeof M[0]), function(row) {
return map(range(sizeof M), function(col) {
return cplx_conj(M[col][row]);
});
});
};
# Helper for cplxMatMul
let cplxVecScalarMul = function cplxVecScalarMul(A, B, row, col) {
var M = { "re": 0.0, "im": 0.0 };
let N = sizeof A;
for (var i = 0; i < N; i++) {
let P = cplx_mul(A[row][i], B[i][col]);
M = cplx_add(M, P);
}
return M;
};
# Multiplies matrices A and B
# A and B are assumed to be square and of the same size,
# this condition is not checked.
let cplxMatMul = function cplxMatMul(A, B) {
var R = {};
let N = sizeof A;
for (var row = 0; row < N; row++) {
R[row] = {};
for (var col = 0; col < N; col++) {
R[row][col] = cplxVecScalarMul(A, B, row, col);
}
}
return R;
};
# Helper for creating an array representing a complex number
# given its textual representation
let _ = function makeComplex(str) {
let sep = indexof(str, "+", 1);
if sep < 0 {
sep = indexof(str, "-", 1);
}
let reStr = substrto(str, sep);
let imStr = substrfrom(str, sep);
return { "re": tofloat(reStr), "im": tofloat(imStr) };
};
# Formats a complex matrix
let printCplxMat = function printCplxMat(M) {
foreach(M, function(i, row) {
foreach(row, function(j, elem) {
printf(" %.2f%+.2fi", elem.re, elem.im);
});
print();
});
};
# A Hermitian matrix
let H = {
{ _("3+0i"), _("2+1i") },
{ _("2-1i"), _("0+0i") }
};
# A normal matrix
let N = {
{ _("1+0i"), _("1+0i"), _("0+0i") },
{ _("0+0i"), _("1+0i"), _("1+0i") },
{ _("1+0i"), _("0+0i"), _("1+0i") }
};
# A unitary matrix
let U = {
{ _("0.70710678118+0i"), _("0.70710678118+0i"), _("0+0i") },
{ _("0-0.70710678118i"), _("0+0.70710678118i"), _("0+0i") },
{ _("0+0i"), _("0+0i"), _("0+1i") }
};
print("Hermitian matrix:\nH = ");
printCplxMat(H);
print("H* = ");
printCplxMat(conjTransp(H));
print();
print("Normal matrix:\nN = ");
printCplxMat(N);
print("N* = ");
printCplxMat(conjTransp(N));
print("N* x N = ");
printCplxMat(cplxMatMul(conjTransp(N), N));
print("N x N* = ");
printCplxMat(cplxMatMul(N, conjTransp(N)));
print();
print("Unitary matrix:\nU = ");
printCplxMat(U);
print("U* = ");
printCplxMat(conjTransp(U));
print("U x U* = ");
printCplxMat(cplxMatMul(U, conjTransp(U)));
print(); |
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
| #Stata | Stata |
: a=1,2i\3i,4
: a
1 2
+-----------+
1 | 1 2i |
2 | 3i 4 |
+-----------+
: a'
1 2
+-------------+
1 | 1 -3i |
2 | -2i 4 |
+-------------+
: transposeonly(a)
1 2
+-----------+
1 | 1 3i |
2 | 2i 4 |
+-----------+
: a*a'==a'*a
0
: a'==a
0
: a'*a==I(rows(a))
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
| #Fantom | Fantom |
// define a class to contain the two fields
// accessors to get/set the field values are automatically generated
class Point
{
Int x
Int y
}
class Main
{
public static Void main ()
{
// empty constructor, so x,y set to 0
point1 := Point()
// constructor uses with-block, to initialise values
point2 := Point { x = 1; y = 2}
echo ("Point 1 = (" + point1.x + ", " + point1.y + ")")
echo ("Point 2 = (" + point2.x + ", " + point2.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
| #Forth | Forth | : pt>x ( point -- x ) ;
: pt>y ( point -- y ) CELL+ ;
: .pt ( point -- ) dup pt>x @ . pt>y @ . ; \ or for this simple structure, 2@ . .
create point 6 , 0 ,
7 point pt>y !
.pt \ 6 7 |
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.
| #Sidef | Sidef | func continued_fraction(a, b, f, n = 1000, r = 1) {
f(func (r) {
r < n ? (a(r) / (b(r) + __FUNC__(r+1))) : 0
}(r))
}
var params = Hash(
"φ" => [ { 1 }, { 1 }, { 1 + _ } ],
"√2" => [ { 1 }, { 2 }, { 1 + _ } ],
"e" => [ { _ }, { _ }, { 1 + 1/_ } ],
"π" => [ { (2*_ - 1)**2 }, { 6 }, { 3 + _ } ],
"τ" => [ { _**2 }, { 2*_ + 1 }, { 8 / (1 + _) } ],
)
for k in (params.keys.sort) {
printf("%2s ≈ %s\n", k, continued_fraction(params{k}...))
} |
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
| #ProDOS | ProDOS | editvar /newvar /value=a /userinput=1 /title=Enter a string to be copied:
editvar /newvar /value=b /userinput=1 /title=Enter current directory of the string:
editvar /newvar /value=c /userinput=1 /title=Enter file to copy to:
copy -a- from -b- to -c- |
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
| #Prolog | Prolog | ?- A = "A test string", A = B.
A = B, B = "A test string". |
http://rosettacode.org/wiki/Constrained_random_points_on_a_circle | Constrained random points on a circle | Task
Generate 100 <x,y> coordinate pairs such that x and y are integers sampled from the uniform distribution with the condition that
10
≤
x
2
+
y
2
≤
15
{\displaystyle 10\leq {\sqrt {x^{2}+y^{2}}}\leq 15}
.
Then display/plot them. The outcome should be a "fuzzy" circle. The actual number of points plotted may be less than 100, given that some pairs may be generated more than once.
There are several possible approaches to accomplish this. Here are two possible algorithms.
1) Generate random pairs of integers and filter out those that don't satisfy this condition:
10
≤
x
2
+
y
2
≤
15
{\displaystyle 10\leq {\sqrt {x^{2}+y^{2}}}\leq 15}
.
2) Precalculate the set of all possible points (there are 404 of them) and select randomly from this set.
| #MATLAB | MATLAB | function [xCoordinates,yCoordinates] = randomDisc(numPoints)
xCoordinates = [];
yCoordinates = [];
%Helper function that samples a random integer from the uniform
%distribution between -15 and 15.
function nums = randInt(n)
nums = round((31*rand(n,1))-15.5);
end
n = numPoints;
while n > 0
x = randInt(n);
y = randInt(n);
norms = sqrt((x.^2) + (y.^2));
inBounds = find((10 <= norms) & (norms <= 15));
xCoordinates = [xCoordinates; x(inBounds)];
yCoordinates = [yCoordinates; y(inBounds)];
n = numPoints - numel(xCoordinates);
end
xCoordinates(numPoints+1:end) = [];
yCoordinates(numPoints+1:end) = [];
end |
http://rosettacode.org/wiki/Convex_hull | Convex hull | Find the points which form a convex hull from a set of arbitrary two dimensional points.
For example, given the points (16,3), (12,17), (0,6), (-4,-6), (16,6), (16,-7), (16,-3), (17,-4), (5,19), (19,-8), (3,16), (12,13), (3,-4), (17,5), (-3,15), (-3,-9), (0,11), (-9,-3), (-4,-2) and (12,10) the convex hull would be (-9,-3), (-3,-9), (19,-8), (17,5), (12,17), (5,19) and (-3,15).
See also
Convex Hull (youtube)
http://www.geeksforgeeks.org/convex-hull-set-2-graham-scan/
| #Ruby | Ruby | class Point
include Comparable
attr :x, :y
def initialize(x, y)
@x = x
@y = y
end
def <=>(other)
x <=> other.x
end
def to_s
"(%d, %d)" % [@x, @y]
end
def to_str
to_s()
end
end
def ccw(a, b, c)
((b.x - a.x) * (c.y - a.y)) > ((b.y - a.y) * (c.x - a.x))
end
def convexHull(p)
if p.length == 0 then
return []
end
p = p.sort
h = []
# Lower hull
p.each { |pt|
while h.length >= 2 and not ccw(h[-2], h[-1], pt)
h.pop()
end
h << pt
}
# upper hull
t = h.length + 1
p.reverse.each { |pt|
while h.length >= t and not ccw(h[-2], h[-1], pt)
h.pop()
end
h << pt
}
h.pop()
h
end
def main
points = [
Point.new(16, 3), Point.new(12, 17), Point.new( 0, 6), Point.new(-4, -6), Point.new(16, 6),
Point.new(16, -7), Point.new(16, -3), Point.new(17, -4), Point.new( 5, 19), Point.new(19, -8),
Point.new( 3, 16), Point.new(12, 13), Point.new( 3, -4), Point.new(17, 5), Point.new(-3, 15),
Point.new(-3, -9), Point.new( 0, 11), Point.new(-9, -3), Point.new(-4, -2), Point.new(12, 10)
]
hull = convexHull(points)
print "Convex Hull: [", hull.join(", "), "]\n"
end
main() |
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).
| #Sidef | Sidef | func polymod(n, *divs) {
gather {
divs.each { |i|
var m = take(n % i)
(n -= m) /= i
}
take(n)
}
}
func compound_duration(seconds) {
(polymod(seconds, 60, 60, 24, 7) ~Z <sec min hr d wk>).grep { |a|
a[0] > 0
}.reverse.map{.join(' ')}.join(', ')
}
[7259, 86400, 6000000].each { |s|
say "#{'%7d' % s} sec = #{compound_duration(s)}"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.