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/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.
| #Lua | Lua | co = {}
co[1] = coroutine.create( function() print "Enjoy" end )
co[2] = coroutine.create( function() print "Rosetta" end )
co[3] = coroutine.create( function() print "Code" end )
math.randomseed( os.time() )
h = {}
i = 0
repeat
j = math.random(3)
if h[j] == nil then
coroutine.resume( co[j] )
h[j] = true
i = i + 1
end
until i == 3 |
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.
| #M2000_Interpreter | M2000 Interpreter |
Thread.Plan Concurrent
Module CheckIt {
Flush \\ empty stack of values
Data "Enjoy", "Rosetta", "Code"
For i=1 to 3 {
Thread {
Print A$
Thread This Erase
} As K
Read M$
Thread K Execute Static A$=M$
Thread K Interval Random(500,1000)
Threads
}
Rem : Wait 3000 ' we can use just a wait loop, or the main.task loop
\\ main.task exit if all threads erased
Main.Task 30 {
}
\\ when module exit all threads from this module get a signal to stop.
\\ we can use Threads Erase to erase all threads.
\\ Also if we press Esc we do the same
}
CheckIt
\\ we can define again the module, and now we get three time each name, but not every time three same names.
\\ if we change to Threads.Plan Sequential we get always the three same names
\\ Also in concurrent plan we can use a block to ensure that statements run without other thread executed in parallel.
Module CheckIt {
Flush \\ empty stack of values
Data "Enjoy", "Rosetta", "Code"
For i=1 to 3 {
Thread {
Print A$
Print A$
Print A$
Thread This Erase
} As K
Read M$
Thread K Execute Static A$=M$
Thread K Interval Random(500,530)
Threads
}
Rem : Wait 3000 ' we can use just a wait loop, or the main.task loop
\\ main.task exit if all threads erased
Main.Task 30 {
}
\\ when module exit all threads from this module get a signal to stop.
\\ we can use Threads Erase to erase all threads.
\\ Also if we press Esc we do the same
}
CheckIt
|
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.
| #Clojure | Clojure |
(defn fac [n] (apply * (range 1 (inc n))))
(defmacro ct-factorial [n] (fac n)) |
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.
| #Common_Lisp | Common Lisp | (eval-when (:compile-toplevel :load-toplevel :execute)
(defun factorial ...)) |
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.
| #D | D | long fact(in long x) pure nothrow @nogc {
long result = 1;
foreach (immutable i; 2 .. x + 1)
result *= i;
return result;
}
void main() {
// enum means "compile-time constant", it forces CTFE.
enum fact10 = fact(10);
import core.stdc.stdio;
printf("%ld\n", fact10);
} |
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
| #Tcl | Tcl | package require struct::matrix
package require math::complexnumbers
proc complexMatrix.equal {m1 m2 {epsilon 1e-14}} {
if {[$m1 rows] != [$m2 rows] || [$m1 columns] != [$m2 columns]} {
return 0
}
# Compute the magnitude of the difference between two complex numbers
set ceq [list apply {{epsilon a b} {
expr {[mod [- $a $b]] < $epsilon}
} ::math::complexnumbers} $epsilon]
for {set i 0} {$i<[$m1 columns]} {incr i} {
for {set j 0} {$j<[$m1 rows]} {incr j} {
if {![{*}$ceq [$m1 get cell $i $j] [$m2 get cell $i $j]]} {
return 0
}
}
}
return 1
}
proc complexMatrix.multiply {a b} {
if {[$a columns] != [$b rows]} {
error "incompatible sizes"
}
# Simplest to use a lambda in the complex NS
set cpm {{sum a b} {
+ $sum [* $a $b]
} ::math::complexnumbers}
set c0 [math::complexnumbers::complex 0.0 0.0]; # Complex zero
set c [struct::matrix]
$c add columns [$b columns]
$c add rows [$a rows]
for {set i 0} {$i < [$a rows]} {incr i} {
for {set j 0} {$j < [$b columns]} {incr j} {
set sum $c0
foreach rv [$a get row $i] cv [$b get column $j] {
set sum [apply $cpm $sum $rv $cv]
}
$c set cell $j $i $sum
}
}
return $c
}
proc complexMatrix.conjugateTranspose {matrix} {
set mat [struct::matrix]
$mat = $matrix
$mat transpose
for {set c 0} {$c < [$mat columns]} {incr c} {
for {set r 0} {$r < [$mat rows]} {incr r} {
set val [$mat get cell $c $r]
$mat set cell $c $r [math::complexnumbers::conj $val]
}
}
return $mat
} |
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
| #Fortran | Fortran | program typedemo
type rational ! Type declaration
integer :: numerator
integer :: denominator
end type rational
type( rational ), parameter :: zero = rational( 0, 1 ) ! Variables initialized
type( rational ), parameter :: one = rational( 1, 1 ) ! by constructor syntax
type( rational ), parameter :: half = rational( 1, 2 )
integer :: n, halfd, halfn
type( rational ) :: &
one_over_n(20) = (/ (rational( 1, n ), n = 1, 20) /) ! Array initialized with
! constructor inside
! implied-do array initializer
integer :: oon_denoms(20)
halfd = half%denominator ! field access with "%" delimiter
halfn = half%numerator
oon_denoms = one_over_n%denominator ! Access denominator field in every
! rational array element & store
end program typedemo ! as integer array |
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.
| #Swift | Swift | extension BinaryInteger {
@inlinable
public func power(_ n: Self) -> Self {
return stride(from: 0, to: n, by: 1).lazy.map({_ in self }).reduce(1, *)
}
}
public struct CycledSequence<WrappedSequence: Sequence> {
private var seq: WrappedSequence
private var iter: WrappedSequence.Iterator
init(seq: WrappedSequence) {
self.seq = seq
self.iter = seq.makeIterator()
}
}
extension CycledSequence: Sequence, IteratorProtocol {
public mutating func next() -> WrappedSequence.Element? {
if let ele = iter.next() {
return ele
} else {
iter = seq.makeIterator()
return iter.next()
}
}
}
extension Sequence {
public func cycled() -> CycledSequence<Self> {
return CycledSequence(seq: self)
}
}
public struct ChainedSequence<Element> {
private var sequences: [AnySequence<Element>]
private var iter: AnyIterator<Element>
private var curSeq = 0
init(chain: ChainedSequence) {
self.sequences = chain.sequences
self.iter = chain.iter
self.curSeq = chain.curSeq
}
init<Seq: Sequence>(_ seq: Seq) where Seq.Element == Element {
sequences = [AnySequence(seq)]
iter = sequences[curSeq].makeIterator()
}
func chained<Seq: Sequence>(with seq: Seq) -> ChainedSequence where Seq.Element == Element {
var res = ChainedSequence(chain: self)
res.sequences.append(AnySequence(seq))
return res
}
}
extension ChainedSequence: Sequence, IteratorProtocol {
public mutating func next() -> Element? {
if let el = iter.next() {
return el
}
curSeq += 1
guard curSeq != sequences.endIndex else {
return nil
}
iter = sequences[curSeq].makeIterator()
return iter.next()
}
}
extension Sequence {
public func chained<Seq: Sequence>(with other: Seq) -> ChainedSequence<Element> where Seq.Element == Element {
return ChainedSequence(self).chained(with: other)
}
}
func continuedFraction<T: Sequence, V: Sequence>(
_ seq1: T,
_ seq2: V,
iterations: Int = 1000
) -> Double where T.Element: BinaryInteger, T.Element == V.Element {
return zip(seq1, seq2).prefix(iterations).reversed().reduce(0.0, { Double($1.0) + (Double($1.1) / $0) })
}
let sqrtA = [1].chained(with: [2].cycled())
let sqrtB = [1].cycled()
print("√2 ≈ \(continuedFraction(sqrtA, sqrtB))")
let napierA = [2].chained(with: 1...)
let napierB = [1].chained(with: 1...)
print("e ≈ \(continuedFraction(napierA, napierB))")
let piA = [3].chained(with: [6].cycled())
let piB = (1...).lazy.map({ (2 * $0 - 1).power(2) })
print("π ≈ \(continuedFraction(piA, piB))")
|
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.
| #Tcl | Tcl | package require Tcl 8.6
# Term generators; yield list of pairs
proc r2 {} {
yield {1 1}
while 1 {yield {2 1}}
}
proc e {} {
yield {2 1}
while 1 {yield [list [incr n] $n]}
}
proc pi {} {
set n 0; set a 3
while 1 {
yield [list $a [expr {(2*[incr n]-1)**2}]]
set a 6
}
}
# Continued fraction calculator
proc cf {generator {termCount 50}} {
# Get the chunk of terms we want to work with
set terms [list [coroutine cf.c $generator]]
while {[llength $terms] < $termCount} {
lappend terms [cf.c]
}
rename cf.c {}
# Merge the terms to compute the result
set val 0.0
foreach pair [lreverse $terms] {
lassign $pair a b
set val [expr {$a + $b/$val}]
}
return $val
}
# Demonstration
puts [cf r2]
puts [cf e]
puts [cf pi 250]; # Converges more slowly |
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
| #PureBasic | PureBasic | 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
| #Python | Python | >>> src = "hello"
>>> a = src
>>> b = src[:]
>>> import copy
>>> c = copy.copy(src)
>>> d = copy.deepcopy(src)
>>> src is a is b is c is d
True |
http://rosettacode.org/wiki/Constrained_random_points_on_a_circle | Constrained random points on a circle | Task
Generate 100 <x,y> coordinate pairs such that x and y are integers sampled from the uniform distribution with the condition that
10
≤
x
2
+
y
2
≤
15
{\displaystyle 10\leq {\sqrt {x^{2}+y^{2}}}\leq 15}
.
Then display/plot them. The outcome should be a "fuzzy" circle. The actual number of points plotted may be less than 100, given that some pairs may be generated more than once.
There are several possible approaches to accomplish this. Here are two possible algorithms.
1) Generate random pairs of integers and filter out those that don't satisfy this condition:
10
≤
x
2
+
y
2
≤
15
{\displaystyle 10\leq {\sqrt {x^{2}+y^{2}}}\leq 15}
.
2) Precalculate the set of all possible points (there are 404 of them) and select randomly from this set.
| #Maxima | Maxima | randomDisc(numPoints):= block([p: []],
local(goodp, random_int),
goodp(x, y):=block([r: sqrt(x^2+y^2)],
r>=10 and r<=15
),
random_int():= block([m: 15], m - random(2*(m+1)-1)),
while length(p)<numPoints do block (
[x: random_int(), y : random_int()],
if goodp(x, y) then (
p: cons([x, y], p)
)
),
p)$
p: randomDisc(100)$
plot2d(['discrete, p], ['style, 'points]); |
http://rosettacode.org/wiki/Convex_hull | Convex hull | Find the points which form a convex hull from a set of arbitrary two dimensional points.
For example, given the points (16,3), (12,17), (0,6), (-4,-6), (16,6), (16,-7), (16,-3), (17,-4), (5,19), (19,-8), (3,16), (12,13), (3,-4), (17,5), (-3,15), (-3,-9), (0,11), (-9,-3), (-4,-2) and (12,10) the convex hull would be (-9,-3), (-3,-9), (19,-8), (17,5), (12,17), (5,19) and (-3,15).
See also
Convex Hull (youtube)
http://www.geeksforgeeks.org/convex-hull-set-2-graham-scan/
| #Rust | Rust |
#[derive(Debug, Clone)]
struct Point {
x: f32,
y: f32
}
fn calculate_convex_hull(points: &Vec<Point>) -> Vec<Point> {
//There must be at least 3 points
if points.len() < 3 { return points.clone(); }
let mut hull = vec![];
//Find the left most point in the polygon
let (left_most_idx, _) = points.iter()
.enumerate()
.min_by(|lhs, rhs| lhs.1.x.partial_cmp(&rhs.1.x).unwrap())
.expect("No left most point");
let mut p = left_most_idx;
let mut q = 0_usize;
loop {
//The left most point must be part of the hull
hull.push(points[p].clone());
q = (p + 1) % points.len();
for i in 0..points.len() {
if orientation(&points[p], &points[i], &points[q]) == 2 {
q = i;
}
}
p = q;
//Break from loop once we reach the first point again
if p == left_most_idx { break; }
}
return hull;
}
//Calculate orientation for 3 points
//0 -> Straight line
//1 -> Clockwise
//2 -> Counterclockwise
fn orientation(p: &Point, q: &Point, r: &Point) -> usize {
let val = (q.y - p.y) * (r.x - q.x) -
(q.x - p.x) * (r.y - q.y);
if val == 0. { return 0 };
if val > 0. { return 1; } else { return 2; }
}
fn main(){
let points = vec![pt(16,3), pt(12,17), pt(0,6), pt(-4,-6), pt(16,6), pt(16,-7), pt(16,-3), pt(17,-4), pt(5,19), pt(19,-8), pt(3,16), pt(12,13), pt(3,-4), pt(17,5), pt(-3,15), pt(-3,-9), pt(0,11), pt(-9,-3), pt(-4,-2), pt(12,10)];
let hull = calculate_convex_hull(&points);
hull.iter()
.for_each(|pt| println!("{:?}", pt));
}
fn pt(x: i32, y: i32) -> Point {
return Point {x:x as f32, y:y as f32};
}
|
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).
| #Standard_ML | Standard ML | local
fun fmtNonZero (0, _, list) = list
| fmtNonZero (n, s, list) = Int.toString n ^ " " ^ s :: list
fun divModHead (_, []) = []
| divModHead (d, head :: tail) = head div d :: head mod d :: tail
in
fun compoundDuration seconds =
let
val digits = foldl divModHead [seconds] [60, 60, 24, 7]
and units = ["wk", "d", "hr", "min", "sec"]
in
String.concatWith ", " (ListPair.foldr fmtNonZero [] (digits, units))
end
end
val () = app (fn s => print (compoundDuration s ^ "\n")) [7259, 86400, 6000000] |
http://rosettacode.org/wiki/Convert_seconds_to_compound_duration | Convert seconds to compound duration | Task
Write a function or program which:
takes a positive integer representing a duration in seconds as input (e.g., 100), and
returns a string which shows the same duration decomposed into:
weeks,
days,
hours,
minutes, and
seconds.
This is detailed below (e.g., "2 hr, 59 sec").
Demonstrate that it passes the following three test-cases:
Test Cases
input number
output string
7259
2 hr, 59 sec
86400
1 d
6000000
9 wk, 6 d, 10 hr, 40 min
Details
The following five units should be used:
unit
suffix used in output
conversion
week
wk
1 week = 7 days
day
d
1 day = 24 hours
hour
hr
1 hour = 60 minutes
minute
min
1 minute = 60 seconds
second
sec
However, only include quantities with non-zero values in the output (e.g., return "1 d" and not "0 wk, 1 d, 0 hr, 0 min, 0 sec").
Give larger units precedence over smaller ones as much as possible (e.g., return 2 min, 10 sec and not 1 min, 70 sec or 130 sec)
Mimic the formatting shown in the test-cases (quantities sorted from largest unit to smallest and separated by comma+space; value and unit of each quantity separated by space).
| #Swift | Swift | func duration (_ secs:Int) -> String {
if secs <= 0 { return "" }
let units = [(604800,"wk"), (86400,"d"), (3600,"hr"), (60,"min")]
var secs = secs
var result = ""
for (period, unit) in units {
if secs >= period {
result += "\(secs/period) \(unit), "
secs = secs % period
}
}
if secs == 0 {
result.removeLast(2) // remove ", "
} else {
result += "\(secs) sec"
}
return result
}
print(duration(7259))
print(duration(86400))
print(duration(6000000)) |
http://rosettacode.org/wiki/Concurrent_computing | Concurrent computing | Task
Using either native language concurrency syntax or freely available libraries, write a program to display the strings "Enjoy" "Rosetta" "Code", one string per line, in random order.
Concurrency syntax must use threads, tasks, co-routines, or whatever concurrency is called in your language.
| #Mathematica_.2F_Wolfram_Language | Mathematica / Wolfram Language | ParallelDo[
Pause[RandomReal[]];
Print[s],
{s, {"Enjoy", "Rosetta", "Code"}}
] |
http://rosettacode.org/wiki/Concurrent_computing | Concurrent computing | Task
Using either native language concurrency syntax or freely available libraries, write a program to display the strings "Enjoy" "Rosetta" "Code", one string per line, in random order.
Concurrency syntax must use threads, tasks, co-routines, or whatever concurrency is called in your language.
| #Mercury | Mercury | :- module concurrent_computing.
:- interface.
:- import_module io.
:- pred main(io::di, io::uo) is cc_multi.
:- implementation.
:- import_module thread.
main(!IO) :-
spawn(io.print_cc("Enjoy\n"), !IO),
spawn(io.print_cc("Rosetta\n"), !IO),
spawn(io.print_cc("Code\n"), !IO). |
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.
| #Neko | Neko | /**
Concurrent computing, in Neko
*/
var thread_create = $loader.loadprim("std@thread_create", 2);
var subtask = function(message) {
$print(message, "\n");
}
/* The thread functions happen so fast as to look sequential */
thread_create(subtask, "Enjoy");
thread_create(subtask, "Rosetta");
thread_create(subtask, "Code");
/* slow things down */
var sys_sleep = $loader.loadprim("std@sys_sleep", 1);
var random_new = $loader.loadprim("std@random_new", 0);
var random_int = $loader.loadprim("std@random_int", 2);
var randomsleep = function(message) {
var r = random_new();
var sleep = random_int(r, 3);
sys_sleep(sleep);
$print(message, "\n");
}
$print("\nWith random delays\n");
thread_create(randomsleep, "Enjoy");
thread_create(randomsleep, "Rosetta");
thread_create(randomsleep, "Code");
/* Let the threads complete */
sys_sleep(4); |
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.
| #Delphi | Delphi | const fact10 = 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.
| #DWScript | DWScript | const fact10 = 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.
| #EchoLisp | EchoLisp |
(define-constant DIX! (factorial 10))
(define-constant DIX!+1 (1+ DIX!))
(writeln DIX!+1)
3628801
|
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.
| #Erlang | Erlang | : factorial ( n -- n! ) [1,b] product ;
CONSTANT: 10-factorial $[ 10 factorial ] |
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
| #Wren | Wren | import "/complex" for Complex, CMatrix
import "/fmt" for Fmt
var cm1 = CMatrix.new(
[
[Complex.new(3), Complex.new(2, 1)],
[Complex.new(2, -1), Complex.one ]
]
)
var cm2 = CMatrix.fromReals([ [1, 1, 0], [0, 1, 1], [1, 0, 1] ])
var x = 2.sqrt/2
var cm3 = CMatrix.new(
[
[Complex.new(x), Complex.new(x), Complex.zero],
[Complex.new(0, -x), Complex.new(0, x), Complex.zero],
[Complex.zero, Complex.zero, Complex.imagOne]
]
)
for (cm in [cm1, cm2, cm3]) {
System.print("Matrix:")
Fmt.mprint(cm, 5, 3)
System.print("\nConjugate transpose:")
Fmt.mprint(cm.conjTranspose, 5, 3)
System.print("\nHermitian : %(cm.isHermitian)")
System.print("Normal : %(cm.isNormal)")
System.print("Unitary : %(cm.isUnitary)")
System.print()
}
System.print("For the final example if we use a tolerance of 1e-14:")
var cm4 = cm3 * cm3.conjTranspose
var id = CMatrix.identity(3)
System.print("Unitary : %(cm4.almostEquals(id))") |
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
| #FreeBASIC | FreeBASIC | ' FB 1.05.0 Win64
Type Point
As Integer x, y
End Type
Dim p As Point = (1, 2)
Dim p2 As Point = (3, 4)
Print p.x, p.y
Print p2.x, p2.y
Sleep |
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
| #Go | Go | type point struct {
x, y float64
}
|
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.
| #VBA | VBA | Public Const precision = 10000
Private Function continued_fraction(steps As Integer, rid_a As String, rid_b As String) As Double
Dim res As Double
res = 0
For n = steps To 1 Step -1
res = Application.Run(rid_b, n) / (Application.Run(rid_a, n) + res)
Next n
continued_fraction = Application.Run(rid_a, 0) + res
End Function
Function sqr2_a(n As Integer) As Integer
sqr2_a = IIf(n = 0, 1, 2)
End Function
Function sqr2_b(n As Integer) As Integer
sqr2_b = 1
End Function
Function nap_a(n As Integer) As Integer
nap_a = IIf(n = 0, 2, n)
End Function
Function nap_b(n As Integer) As Integer
nap_b = IIf(n = 1, 1, n - 1)
End Function
Function pi_a(n As Integer) As Integer
pi_a = IIf(n = 0, 3, 6)
End Function
Function pi_b(n As Integer) As Long
pi_b = IIf(n = 1, 1, (2 * n - 1) ^ 2)
End Function
Public Sub main()
Debug.Print "Precision:", precision
Debug.Print "Sqr(2):", continued_fraction(precision, "sqr2_a", "sqr2_b")
Debug.Print "Napier:", continued_fraction(precision, "nap_a", "nap_b")
Debug.Print "Pi:", continued_fraction(precision, "pi_a", "pi_b")
End Sub |
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
| #Quackery | Quackery | $ "hello" dup |
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
| #R | R | str1 <- "abc"
str2 <- str1 |
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.
| #Nim | Nim | import tables, math, complex, random
type Point = tuple[x, y: int]
var world = initCountTable[Point]()
var possiblePoints = newSeq[Point]()
for x in -15..15:
for y in -15..15:
if abs(complex(x.float, y.float)) in 10.0..15.0:
possiblePoints.add((x,y))
randomize()
for i in 0..100: world.inc possiblePoints.sample
for x in -15..15:
for y in -15..15:
let key = (x, y)
if key in world and world[key] > 0:
stdout.write ' ' & $min(9, world[key])
else:
stdout.write " "
echo "" |
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/
| #Scala | Scala |
object convex_hull{
def get_hull(points:List[(Double,Double)], hull:List[(Double,Double)]):List[(Double,Double)] = points match{
case Nil => join_tail(hull,hull.size -1)
case head :: tail => get_hull(tail,reduce(head::hull))
}
def reduce(hull:List[(Double,Double)]):List[(Double,Double)] = hull match{
case p1::p2::p3::rest => {
if(check_point(p1,p2,p3)) hull
else reduce(p1::p3::rest)
}
case _ => hull
}
def check_point(pnt:(Double,Double), p2:(Double,Double),p1:(Double,Double)): Boolean = {
val (x,y) = (pnt._1,pnt._2)
val (x1,y1) = (p1._1,p1._2)
val (x2,y2) = (p2._1,p2._2)
((x-x1)*(y2-y1) - (x2-x1)*(y-y1)) <= 0
}
def m(p1:(Double,Double), p2:(Double,Double)):Double = {
if(p2._1 == p1._1 && p1._2>p2._2) 90
else if(p2._1 == p1._1 && p1._2<p2._2) -90
else if(p1._1<p2._1) 180 - Math.toDegrees(Math.atan(-(p1._2 - p2._2)/(p1._1 - p2._1)))
else Math.toDegrees(Math.atan((p1._2 - p2._2)/(p1._1 - p2._1)))
}
def join_tail(hull:List[(Double,Double)],len:Int):List[(Double,Double)] = {
if(m(hull(len),hull(0)) > m(hull(len-1),hull(0))) join_tail(hull.slice(0,len),len-1)
else hull
}
def main(args:Array[String]){
val points = List[(Double,Double)]((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))
val sorted_points = points.sortWith(m(_,(0.0,0.0)) < m(_,(0.0,0.0)))
println(f"Points:\n" + points + f"\n\nConvex Hull :\n" +get_hull(sorted_points,List[(Double,Double)]()))
}
}
|
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).
| #Tcl | Tcl | proc sec2str {i} {
set factors {
sec 60
min 60
hr 24
d 7
wk Inf
}
set result ""
foreach {label max} $factors {
if {$i >= $max} {
set r [expr {$i % $max}]
set i [expr {$i / $max}]
if {$r} {
lappend result "$r $label"
}
} else {
if {$i > 0} {
lappend result "$i $label"
}
break
}
}
join [lreverse $result] ", "
}
proc check {cmd res} {
set r [uplevel 1 $cmd]
if {$r eq $res} {
puts "Ok! $cmd \t = $res"
} else {
puts "ERROR: $cmd = $r \t expected $res"
}
}
check {sec2str 7259} {2 hr, 59 sec}
check {sec2str 86400} {1 d}
check {sec2str 6000000} {9 wk, 6 d, 10 hr, 40 min} |
http://rosettacode.org/wiki/Concurrent_computing | Concurrent computing | Task
Using either native language concurrency syntax or freely available libraries, write a program to display the strings "Enjoy" "Rosetta" "Code", one string per line, in random order.
Concurrency syntax must use threads, tasks, co-routines, or whatever concurrency is called in your language.
| #Nim | Nim | const str = ["Enjoy", "Rosetta", "Code"]
var thr: array[3, Thread[int32]]
proc f(i:int32) {.thread.} =
echo str[i]
for i in 0..thr.high:
createThread(thr[i], f, int32(i))
joinThreads(thr) |
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.
| #Objeck | Objeck |
bundle Default {
class MyThread from Thread {
New(name : String) {
Parent(name);
}
method : public : Run(param : Base) ~ Nil {
string := param->As(String);
string->PrintLine();
}
}
class Concurrent {
New() {
}
function : Main(args : System.String[]) ~ Nil {
t0 := MyThread->New("t0");
t1 := MyThread->New("t1");
t2 := MyThread->New("t2");
t0->Execute("Enjoy"->As(Base));
t1->Execute("Rosetta"->As(Base));
t2->Execute("Code"->As(Base));
}
}
}
|
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.
| #Factor | Factor | : factorial ( n -- n! ) [1,b] product ;
CONSTANT: 10-factorial $[ 10 factorial ] |
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.
| #Forth | Forth | : fac ( n -- n! ) 1 swap 1+ 2 max 2 ?do i * loop ;
: main ." 10! = " [ 10 fac ] literal . ;
see main
: main
.\" 10! = " 3628800 . ; ok |
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.
| #Fortran | Fortran | program test
implicit none
integer,parameter :: t = 10*9*8*7*6*5*4*3*2 !computed at compile time
write(*,*) t !write the value the console.
end program test
|
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.
| #FreeBASIC | FreeBASIC | ' FB 1.05.0 Win64
' Calculations can be done in a Const declaration at compile time
' provided only literals or other constant expressions are used
Const factorial As Integer = 2 * 3 * 4 * 5 * 6 * 7 * 8 * 9 * 10
Print factorial ' 3628800
Sleep |
http://rosettacode.org/wiki/Conway%27s_Game_of_Life | Conway's Game of Life | The Game of Life is a cellular automaton devised by the British mathematician John Horton Conway in 1970. It is the best-known example of a cellular automaton.
Conway's game of life is described here:
A cell C is represented by a 1 when alive, or 0 when dead, in an m-by-m (or m×m) square array of cells.
We calculate N - the sum of live cells in C's eight-location neighbourhood, then cell C is alive or dead in the next generation based on the following table:
C N new C
1 0,1 -> 0 # Lonely
1 4,5,6,7,8 -> 0 # Overcrowded
1 2,3 -> 1 # Lives
0 3 -> 1 # It takes three to give birth!
0 0,1,2,4,5,6,7,8 -> 0 # Barren
Assume cells beyond the boundary are always dead.
The "game" is actually a zero-player game, meaning that its evolution is determined by its initial state, needing no input from human players. One interacts with the Game of Life by creating an initial configuration and observing how it evolves.
Task
Although you should test your implementation on more complex examples such as the glider in a larger universe, show the action of the blinker (three adjoining cells in a row all alive), over three generations, in a 3 by 3 grid.
References
Its creator John Conway, explains the game of life. Video from numberphile on youtube.
John Conway Inventing Game of Life - Numberphile video.
Related task
Langton's ant - another well known cellular automaton.
| #11l | 11l | V cellcountx = 6
V cellcounty = 5
V celltable = [(1, 2) = 1,
(1, 3) = 1,
(0, 3) = 1]
DefaultDict[(Int, Int), Int] universe
universe[(1, 1)] = 1
universe[(2, 1)] = 1
universe[(3, 1)] = 1
universe[(1, 4)] = 1
universe[(2, 4)] = 1
universe[(3, 4)] = 1
L(i) 4
print("\nGeneration "i‘:’)
L(row) 0 .< cellcounty
print(‘ ’(0 .< cellcountx).map(col -> [‘. ’, ‘O ’][:universe[(@row, col)]]).join(‘’))
DefaultDict[(Int, Int), Int] nextgeneration
L(row) 0 .< cellcounty
L(col) 0 .< cellcountx
nextgeneration[(row, col)] = celltable.get(
(universe[(row, col)],
-universe[(row, col)] + sum(multiloop(row-1..row+1,
col-1..col+1, (r, c) -> :universe[(r, c)]))
), 0)
universe = nextgeneration |
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
| #Groovy | Groovy | class Point {
int x
int y
// Default values make this a 0-, 1-, and 2-argument constructor
Point(int x = 0, int y = 0) { this.x = x; this.y = y }
String toString() { "{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
| #Haskell | Haskell | data Tree = Empty
| Leaf Int
| Node Tree Tree
deriving (Eq, Show)
t1 = Node (Leaf 1) (Node (Leaf 2) (Leaf 3))
|
http://rosettacode.org/wiki/Continued_fraction | Continued fraction | continued fraction
Mathworld
a
0
+
b
1
a
1
+
b
2
a
2
+
b
3
a
3
+
⋱
{\displaystyle a_{0}+{\cfrac {b_{1}}{a_{1}+{\cfrac {b_{2}}{a_{2}+{\cfrac {b_{3}}{a_{3}+\ddots }}}}}}}
The task is to write a program which generates such a number and prints a real representation of it. The code should be tested by calculating and printing the square root of 2, Napier's Constant, and Pi, using the following coefficients:
For the square root of 2, use
a
0
=
1
{\displaystyle a_{0}=1}
then
a
N
=
2
{\displaystyle a_{N}=2}
.
b
N
{\displaystyle b_{N}}
is always
1
{\displaystyle 1}
.
2
=
1
+
1
2
+
1
2
+
1
2
+
⋱
{\displaystyle {\sqrt {2}}=1+{\cfrac {1}{2+{\cfrac {1}{2+{\cfrac {1}{2+\ddots }}}}}}}
For Napier's Constant, use
a
0
=
2
{\displaystyle a_{0}=2}
, then
a
N
=
N
{\displaystyle a_{N}=N}
.
b
1
=
1
{\displaystyle b_{1}=1}
then
b
N
=
N
−
1
{\displaystyle b_{N}=N-1}
.
e
=
2
+
1
1
+
1
2
+
2
3
+
3
4
+
⋱
{\displaystyle e=2+{\cfrac {1}{1+{\cfrac {1}{2+{\cfrac {2}{3+{\cfrac {3}{4+\ddots }}}}}}}}}
For Pi, use
a
0
=
3
{\displaystyle a_{0}=3}
then
a
N
=
6
{\displaystyle a_{N}=6}
.
b
N
=
(
2
N
−
1
)
2
{\displaystyle b_{N}=(2N-1)^{2}}
.
π
=
3
+
1
6
+
9
6
+
25
6
+
⋱
{\displaystyle \pi =3+{\cfrac {1}{6+{\cfrac {9}{6+{\cfrac {25}{6+\ddots }}}}}}}
See also
Continued fraction/Arithmetic for tasks that do arithmetic over continued fractions.
| #Visual_Basic_.NET | Visual Basic .NET | Module Module1
Function Calc(f As Func(Of Integer, Integer()), n As Integer) As Double
Dim temp = 0.0
For ni = n To 1 Step -1
Dim p = f(ni)
temp = p(1) / (p(0) + temp)
Next
Return f(0)(0) + temp
End Function
Sub Main()
Dim fList = {
Function(n As Integer) New Integer() {If(n > 0, 2, 1), 1},
Function(n As Integer) New Integer() {If(n > 0, n, 2), If(n > 1, n - 1, 1)},
Function(n As Integer) New Integer() {If(n > 0, 6, 3), Math.Pow(2 * n - 1, 2)}
}
For Each f In fList
Console.WriteLine(Calc(f, 200))
Next
End Sub
End Module |
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
| #Racket | Racket |
#lang racket
(let* ([s1 "Hey"]
[s2 s1]
[s3 (string-copy s1)]
[s4 s3])
(printf "s1 and s2 refer to ~a strings\n"
(if (eq? s1 s2) "the same" "different")) ; same
(printf "s1 and s3 refer to ~a strings\n"
(if (eq? s1 s3) "the same" "different")) ; different
(printf "s3 and s4 refer to ~a strings\n"
(if (eq? s3 s4) "the same" "different")) ; same
(string-fill! s3 #\!)
(printf "~a~a~a~a\n" s1 s2 s3 s4)) ; outputs "HeyHey!!!!!!"
|
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
| #Raku | Raku | my $original = 'Hello.';
my $copy = $original;
say $copy; # prints "Hello."
$copy = 'Goodbye.';
say $copy; # prints "Goodbye."
say $original; # prints "Hello." |
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.
| #OCaml | OCaml | let p x y =
let d = sqrt(x ** 2.0 +. y ** 2.0) in
10.0 <= d && d <= 15.0
let () =
Random.self_init();
let rec aux i acc =
if i >= 100 then acc else
let x = (Random.float 40.0) -. 20.0
and y = (Random.float 40.0) -. 20.0 in
if (p x y)
then aux (succ i) ((x,y)::acc)
else aux i acc
in
let points = aux 0 [] in
let g = Array.init 40 (fun _ -> String.make 40 ' ') in
List.iter (fun (x,y) ->
let x = (int_of_float x) + 20
and y = (int_of_float y) + 20 in
g.(y).[x] <- 'o'
) points;
Array.iter print_endline g |
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/
| #Scheme | Scheme | (define-library (convex-hulls)
(export vector-convex-hull)
(export list-convex-hull)
(import (scheme base))
(import (srfi 132)) ; Sorting.
(begin
;;
;; The implementation is based on Andrew's monotone chain
;; algorithm, and is adapted from a Fortran implementation I wrote
;; myself in 2011.
;;
;; For a description of the algorithm, see
;; https://en.wikibooks.org/w/index.php?title=Algorithm_Implementation/Geometry/Convex_hull/Monotone_chain&stableid=4016938
;;
(define x@ car)
(define y@ cadr)
(define (cross u v)
;; Cross product (as a signed scalar).
(- (* (x@ u) (y@ v)) (* (y@ u) (x@ v))))
(define (point- u v)
(list (- (x@ u) (x@ v)) (- (y@ u) (y@ v))))
(define (sort-points-vector points-vector)
;; Ascending sort on x-coordinates, followed by ascending sort
;; on y-coordinates.
(vector-sort (lambda (u v)
(or (< (x@ u) (x@ v))
(and (= (x@ u) (x@ v))
(< (y@ u) (y@ v)))))
points-vector))
(define (construct-lower-hull sorted-points-vector)
(let* ((pt sorted-points-vector)
(n (vector-length pt))
(hull (make-vector n))
(j 1))
(vector-set! hull 0 (vector-ref pt 0))
(vector-set! hull 1 (vector-ref pt 1))
(do ((i 2 (+ i 1)))
((= i n))
(let inner-loop ()
(if (or (zero? j)
(positive?
(cross (point- (vector-ref hull j)
(vector-ref hull (- j 1)))
(point- (vector-ref pt i)
(vector-ref hull (- j 1))))))
(begin
(set! j (+ j 1))
(vector-set! hull j (vector-ref pt i)))
(begin
(set! j (- j 1))
(inner-loop)))))
(values (+ j 1) hull))) ; Hull size, hull points.
(define (construct-upper-hull sorted-points-vector)
(let* ((pt sorted-points-vector)
(n (vector-length pt))
(hull (make-vector n))
(j 1))
(vector-set! hull 0 (vector-ref pt (- n 1)))
(vector-set! hull 1 (vector-ref pt (- n 2)))
(do ((i (- n 3) (- i 1)))
((= i -1))
(let inner-loop ()
(if (or (zero? j)
(positive?
(cross (point- (vector-ref hull j)
(vector-ref hull (- j 1)))
(point- (vector-ref pt i)
(vector-ref hull (- j 1))))))
(begin
(set! j (+ j 1))
(vector-set! hull j (vector-ref pt i)))
(begin
(set! j (- j 1))
(inner-loop)))))
(values (+ j 1) hull))) ; Hull size, hull points.
(define (construct-hull sorted-points-vector)
;; Notice that the lower and upper hulls could be constructed in
;; parallel.
(let-values (((lower-hull-size lower-hull)
(construct-lower-hull sorted-points-vector))
((upper-hull-size upper-hull)
(construct-upper-hull sorted-points-vector)))
(let* ((hull-size (+ lower-hull-size upper-hull-size -2))
(hull (make-vector hull-size)))
(vector-copy! hull 0 lower-hull 0 (- lower-hull-size 1))
(vector-copy! hull (- lower-hull-size 1) upper-hull
0 (- upper-hull-size 1))
hull)))
(define (vector-convex-hull points)
(let* ((points-vector (if (vector? points)
points
(list->vector points)))
(sorted-points-vector
(vector-delete-neighbor-dups
equal?
(sort-points-vector points-vector))))
(if (<= (vector-length sorted-points-vector) 2)
sorted-points-vector
(construct-hull sorted-points-vector))))
(define (list-convex-hull points)
(vector->list (vector-convex-hull points)))
)) ;; end of library convex-hulls.
;;
;; A demonstration.
;;
(import (scheme base))
(import (scheme write))
(import (convex-hulls))
(define example-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) (12 10)))
(write (list-convex-hull example-points))
(newline) |
http://rosettacode.org/wiki/Convert_seconds_to_compound_duration | Convert seconds to compound duration | Task
Write a function or program which:
takes a positive integer representing a duration in seconds as input (e.g., 100), and
returns a string which shows the same duration decomposed into:
weeks,
days,
hours,
minutes, and
seconds.
This is detailed below (e.g., "2 hr, 59 sec").
Demonstrate that it passes the following three test-cases:
Test Cases
input number
output string
7259
2 hr, 59 sec
86400
1 d
6000000
9 wk, 6 d, 10 hr, 40 min
Details
The following five units should be used:
unit
suffix used in output
conversion
week
wk
1 week = 7 days
day
d
1 day = 24 hours
hour
hr
1 hour = 60 minutes
minute
min
1 minute = 60 seconds
second
sec
However, only include quantities with non-zero values in the output (e.g., return "1 d" and not "0 wk, 1 d, 0 hr, 0 min, 0 sec").
Give larger units precedence over smaller ones as much as possible (e.g., return 2 min, 10 sec and not 1 min, 70 sec or 130 sec)
Mimic the formatting shown in the test-cases (quantities sorted from largest unit to smallest and separated by comma+space; value and unit of each quantity separated by space).
| #uBasic.2F4tH | uBasic/4tH | Proc _CompoundDuration(7259)
Proc _CompoundDuration(86400)
Proc _CompoundDuration(6000000)
End
_CompoundDuration Param(1) ' Print compound seconds
a@ = FUNC(_Compound(a@, 604800, _wk))
a@ = FUNC(_Compound(a@, 86400, _d))
a@ = FUNC(_Compound(a@, 3600, _hr))
a@ = FUNC(_Compound(a@, 60, _min))
If a@ > 0 Then Print a@;" sec"; ' Still seconds left to print?
Print
Return
_Compound Param(3)
Local(1)
d@ = a@/b@ ' Get main component
a@ = a@%b@ ' Leave the rest
If d@ > 0 Then ' Print the component
Print d@;
Proc c@
If a@ > 0 Then
Print ", "; ' If something follows, take
EndIf ' care of the comma
EndIf
Return (a@)
_wk Print " wk"; : Return
_d Print " d"; : Return
_hr Print " hr"; : Return
_min Print " min"; : Return |
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.
| #OCaml | OCaml | #directory "+threads"
#load "unix.cma"
#load "threads.cma"
let sleepy_print msg =
Unix.sleep (Random.int 4);
print_endline msg
let threads =
List.map (Thread.create sleepy_print) ["Enjoy"; "Rosetta"; "Code"]
let () =
Random.self_init ();
List.iter (Thread.join) threads |
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.
| #Oforth | Oforth | #[ "Enjoy" println ] &
#[ "Rosetta" println ] &
#[ "Code" println ] & |
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.
| #Go | Go | package main
import "fmt"
func main() {
fmt.Println(2*3*4*5*6*7*8*9*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.
| #Haskell | Haskell | module Factorial where
import Language.Haskell.TH.Syntax
fact n = product [1..n]
factQ :: Integer -> Q Exp
factQ = lift . fact |
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.
| #J | J | pf10=: smoutput bind (!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.
| #Julia | Julia | macro fact(n)
factorial(n)
end |
http://rosettacode.org/wiki/Conway%27s_Game_of_Life | Conway's Game of Life | The Game of Life is a cellular automaton devised by the British mathematician John Horton Conway in 1970. It is the best-known example of a cellular automaton.
Conway's game of life is described here:
A cell C is represented by a 1 when alive, or 0 when dead, in an m-by-m (or m×m) square array of cells.
We calculate N - the sum of live cells in C's eight-location neighbourhood, then cell C is alive or dead in the next generation based on the following table:
C N new C
1 0,1 -> 0 # Lonely
1 4,5,6,7,8 -> 0 # Overcrowded
1 2,3 -> 1 # Lives
0 3 -> 1 # It takes three to give birth!
0 0,1,2,4,5,6,7,8 -> 0 # Barren
Assume cells beyond the boundary are always dead.
The "game" is actually a zero-player game, meaning that its evolution is determined by its initial state, needing no input from human players. One interacts with the Game of Life by creating an initial configuration and observing how it evolves.
Task
Although you should test your implementation on more complex examples such as the glider in a larger universe, show the action of the blinker (three adjoining cells in a row all alive), over three generations, in a 3 by 3 grid.
References
Its creator John Conway, explains the game of life. Video from numberphile on youtube.
John Conway Inventing Game of Life - Numberphile video.
Related task
Langton's ant - another well known cellular automaton.
| #6502_Assembly | 6502 Assembly | randfill: stx $01 ;$200 for indirect
ldx #$02 ;addressing
stx $02
randloop: lda $fe ;generate random
and #$01 ;pixels on the
sta ($01),Y ;screen
jsr inc0103
cmp #$00
bne randloop
lda $02
cmp #$06
bne randloop
clearmem: lda #$df ;set $07df-$0a20
sta $01 ;to $#00
lda #$07
sta $02
clearbyte: lda #$00
sta ($01),Y
jsr inc0103
cmp #$20
bne clearbyte
lda $02
cmp #$0a
bne clearbyte
starttick:
copyscreen: lda #$00 ;set up source
sta $01 ;pointer at
sta $03 ;$01/$02 and
lda #$02 ;dest pointer
sta $02 ;at $03/$04
lda #$08
sta $04
ldy #$00
copybyte: lda ($01),Y ;copy pixel to
sta ($03),Y ;back buffer
jsr inc0103 ;increment pointers
cmp #$00 ;check to see
bne copybyte ;if we're at $600
lda $02 ;if so, we've
cmp #$06 ;copied the
bne copybyte ;entire screen
conway: lda #$df ;apply conway rules
sta $01 ;reset the pointer
sta $03 ;to $#01df/$#07df
lda #$01 ;($200 - $21)
sta $02 ;($800 - $21)
lda #$07
sta $04
onecell: lda #$00 ;process one cell
ldy #$01 ;upper cell
clc
adc ($03),Y
ldy #$41 ;lower cell
clc
adc ($03),Y
chkleft: tax ;check to see
lda $01 ;if we're at the
and #$1f ;left edge
tay
txa
cpy #$1f
beq rightcells
leftcells: ldy #$00 ;upper-left cell
clc
adc ($03),Y
ldy #$20 ;left cell
clc
adc ($03),Y
ldy #$40 ;lower-left cell
clc
adc ($03),Y
chkright: tax ;check to see
lda $01 ;if we're at the
and #$1f ;right edge
tay
txa
cpy #$1e
beq evaluate
rightcells: ldy #$02 ;upper-right cell
clc
adc ($03),Y
ldy #$22 ;right cell
clc
adc ($03),Y
ldy #$42 ;lower-right cell
clc
adc ($03),Y
evaluate: ldx #$01 ;evaluate total
ldy #$21 ;for current cell
cmp #$03 ;3 = alive
beq storex
ldx #$00
cmp #$02 ;2 = alive if
bne storex ;c = alive
lda ($03),Y
and #$01
tax
storex: txa ;store to screen
sta ($01),Y
jsr inc0103 ;move to next cell
conwayloop: cmp #$e0 ;if not last cell,
bne onecell ;process next cell
lda $02
cmp #$05
bne onecell
jmp starttick ;run next tick
inc0103: lda $01 ;increment $01
cmp #$ff ;and $03 as 16-bit
bne onlyinc01 ;pointers
inc $02
inc $04
onlyinc01: inc $01
lda $01
sta $03
rts |
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
| #Icon_and_Unicon | Icon and Unicon | record Point(x,y) |
http://rosettacode.org/wiki/Compound_data_type | Compound data type |
Data Structure
This illustrates a data structure, a means of storing data within a program.
You may see other such structures in the Data Structures category.
Task
Create a compound data type:
Point(x,y)
A compound data type is one that holds multiple independent values.
Related task
Enumeration
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
| #IDL | IDL | point = {x: 6 , y: 0 }
point.y = 7
print, point
;=> { 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.
| #Wren | Wren | var calc = Fn.new { |f, n|
var t = 0
for (i in n..1) {
var p = f.call(i)
t = p[1] / (p[0] + t)
}
return f.call(0)[0] + t
}
var pList = [
["sqrt(2)", Fn.new { |n| [(n > 0) ? 2 : 1, 1] }],
["e ", Fn.new { |n| [(n > 0) ? n : 2, (n > 1) ? n - 1 : 1] }],
["pi ", Fn.new { |n| [(n > 0) ? 6 : 3, (2*n - 1) * (2*n - 1)] }]
]
for (p in pList) System.print("%(p[0]) = %(calc.call(p[1], 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
| #Raven | Raven | 'abc' as a
a as b |
http://rosettacode.org/wiki/Copy_a_string | Copy a string | This task is about copying a string.
Task
Where it is relevant, distinguish between copying the contents of a string
versus making an additional reference to an existing string.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #REBOL | REBOL | rebol [
Title: "String Copy"
URL: http://rosettacode.org/wiki/Copy_a_string
]
x: y: "Testing."
y/2: #"X"
print ["Both variables reference same string:" mold x "," mold y]
x: "Slackeriffic!"
print ["Now reference different strings:" mold x "," mold y]
y: copy x ; String copy here!
y/3: #"X" ; Modify string.
print ["x copied to y, then modified:" mold x "," mold y]
y: copy/part x 7 ; Copy only the first part of y to x.
print ["Partial copy:" mold x "," mold y]
y: copy/part skip x 2 3
print ["Partial copy from offset:" mold x "," mold y] |
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.
| #PARI.2FGP | PARI/GP | crpc()={
my(v=vector(404),t=0,i=0,vx=vy=vector(100));
for(x=1,14,for(y=1,14,
t=x^2+y^2;
if(t>99&t<226,
v[i++]=[x,y];
v[i++]=[x,-y];
v[i++]=[-x,y];
v[i++]=[-x,-y]
)
));
for(x=10,15,
v[i++]=[x,0];
v[i++]=[-x,0];
v[i++]=[0,x];
v[i++]=[0,-x]
);
for(i=1,#vx,
t=v[random(#v)+1];
vx[i]=t[1];
vy[i]=t[2];
);
plothraw(vx,vy)
}; |
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/
| #Sidef | Sidef | class Point(Number x, Number y) {
method to_s {
"(#{x}, #{y})"
}
}
func ccw (Point a, Point b, Point c) {
(b.x - a.x)*(c.y - a.y) - (b.y - a.y)*(c.x - a.x)
}
func tangent (Point a, Point b) {
(b.x - a.x) / (b.y - a.y)
}
func graham_scan (*coords) {
## sort points by y, secondary sort on x
var sp = coords.map { |a|
Point(a...)
}.sort { |a,b|
(a.y <=> b.y) ||
(a.x <=> b.x)
}
# need at least 3 points to make a hull
if (sp.len < 3) {
return sp
}
# first point on hull is minimum y point
var h = [sp.shift]
# re-sort the points by angle, secondary on x
sp = sp.map_kv { |k,v|
Pair(k, [tangent(h[0], v), v.x])
}.sort { |a,b|
(b.value[0] <=> a.value[0]) ||
(a.value[1] <=> b.value[1])
}.map { |a|
sp[a.key]
}
# first point of re-sorted list is guaranteed to be on hull
h << sp.shift
# check through the remaining list making sure that
# there is always a positive angle
sp.each { |point|
loop {
if (ccw(h.last(2)..., point) >= 0) {
h << point
break
} else {
h.pop
}
}
}
return h
}
var 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.len} points): ", hull.join(" "))
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], [14,-9], [1,-9])
say("Convex Hull (#{hull.len} points): ", hull.join(" ")) |
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).
| #VBA | VBA | Private Function compound_duration(ByVal seconds As Long) As String
minutes = 60
hours = 60 * minutes
days_ = 24 * hours
weeks = 7 * days_
Dim out As String
w = seconds \ weeks
seconds = seconds - w * weeks
d = seconds \ days_
seconds = seconds - d * days_
h = seconds \ hours
seconds = seconds - h * hours
m = seconds \ minutes
s = seconds Mod minutes
out = IIf(w > 0, w & " wk, ", "") & _
IIf(d > 0, d & " d, ", "") & _
IIf(h > 0, h & " hr, ", "") & _
IIf(m > 0, m & " min, ", "") & _
IIf(s > 0, s & " sec", "")
If Right(out, 2) = ", " Then
compound_duration = Left(out, Len(out) - 2)
Else
compound_duration = out
End If
End Function
Public Sub cstcd()
Debug.Print compound_duration(7259)
Debug.Print compound_duration(86400)
Debug.Print compound_duration(6000000)
End Sub |
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.
| #Ol | Ol |
(import (otus random!))
(for-each (lambda (str)
(define timeout (rand! 999))
(async (lambda ()
(sleep timeout)
(print str))))
'("Enjoy" "Rosetta" "Code"))
|
http://rosettacode.org/wiki/Concurrent_computing | Concurrent computing | Task
Using either native language concurrency syntax or freely available libraries, write a program to display the strings "Enjoy" "Rosetta" "Code", one string per line, in random order.
Concurrency syntax must use threads, tasks, co-routines, or whatever concurrency is called in your language.
| #ooRexx | ooRexx |
-- this will launch 3 threads, with each thread given a message to print out.
-- I've added a stoplight to make each thread wait until given a go signal,
-- plus some sleeps to give the threads a chance to randomize the execution
-- order a little.
launcher = .launcher~new
launcher~launch
::class launcher
-- the launcher method. Guarded is the default, but let's make this
-- explicit here
::method launch guarded
runner1 = .runner~new(self, "Enjoy")
runner2 = .runner~new(self, "Rosetta")
runner3 = .runner~new(self, "Code")
-- let's give the threads a chance to settle in to the
-- starting line
call syssleep 1
guard off -- release the launcher lock. This is the starter's gun
-- this is a guarded method that the runners will call. They
-- will block until the launch method releases the object guard
::method block guarded
::class runner
::method init
use arg launcher, text
reply -- this creates the new thread
call syssleep .5 -- try to mix things up by sleeping
launcher~block -- wait for the go signal
call syssleep .5 -- add another sleep here
say text
|
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.
| #Kotlin | Kotlin | // version 1.0.6
const val TEN_FACTORIAL = 10 * 9 * 8 * 7 * 6 * 5 * 4 * 3 * 2
fun main(args: Array<String>) {
println("10! = $TEN_FACTORIAL")
} |
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.
| #Lingo | Lingo | -- create new (movie) script at runtime
m = new(#script)
-- the following line triggers compilation to bytecode
m.scriptText = "on fac10"&RETURN&"return "&(10*9*8*7*6*5*4*3*2)&RETURN&"end"
put fac10()
-- 3628800 |
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.
| #Lua | Lua | local factorial = 10*9*8*7*6*5*4*3*2*1
print(factorial) |
http://rosettacode.org/wiki/Conditional_structures | Conditional structures | Control Structures
These are examples of control structures. You may also be interested in:
Conditional structures
Exceptions
Flow-control structures
Loops
Task
List the conditional structures offered by a programming language. See Wikipedia: conditionals for descriptions.
Common conditional structures include if-then-else and switch.
Less common are arithmetic if, ternary operator and Hash-based conditionals.
Arithmetic if allows tight control over computed gotos, which optimizers have a hard time to figure out.
| #11l | 11l | I x == 0
foo()
E I x == 1
bar()
E
baz() |
http://rosettacode.org/wiki/Conway%27s_Game_of_Life | Conway's Game of Life | The Game of Life is a cellular automaton devised by the British mathematician John Horton Conway in 1970. It is the best-known example of a cellular automaton.
Conway's game of life is described here:
A cell C is represented by a 1 when alive, or 0 when dead, in an m-by-m (or m×m) square array of cells.
We calculate N - the sum of live cells in C's eight-location neighbourhood, then cell C is alive or dead in the next generation based on the following table:
C N new C
1 0,1 -> 0 # Lonely
1 4,5,6,7,8 -> 0 # Overcrowded
1 2,3 -> 1 # Lives
0 3 -> 1 # It takes three to give birth!
0 0,1,2,4,5,6,7,8 -> 0 # Barren
Assume cells beyond the boundary are always dead.
The "game" is actually a zero-player game, meaning that its evolution is determined by its initial state, needing no input from human players. One interacts with the Game of Life by creating an initial configuration and observing how it evolves.
Task
Although you should test your implementation on more complex examples such as the glider in a larger universe, show the action of the blinker (three adjoining cells in a row all alive), over three generations, in a 3 by 3 grid.
References
Its creator John Conway, explains the game of life. Video from numberphile on youtube.
John Conway Inventing Game of Life - Numberphile video.
Related task
Langton's ant - another well known cellular automaton.
| #68000_Assembly | 68000 Assembly | include "\SrcALL\68000_Macros.asm"
;Ram Variables
Cursor_X equ $00FF0000 ;Ram for Cursor Xpos
Cursor_Y equ $00FF0000+1 ;Ram for Cursor Ypos
conwayTilemapRam equ $00FF1000
conwayBackupTilemapRam equ $00FF2000
;Video Ports
VDP_data EQU $C00000 ; VDP data, R/W word or longword access only
VDP_ctrl EQU $C00004 ; VDP control, word or longword writes only
;constants
ROWLENGTH equ 40
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; Traps
DC.L $FFFFFE00 ;SP register value
DC.L ProgramStart ;Start of Program Code
DS.L 7,IntReturn ; bus err,addr err,illegal inst,divzero,CHK,TRAPV,priv viol
DC.L IntReturn ; TRACE
DC.L IntReturn ; Line A (1010) emulator
DC.L IntReturn ; Line F (1111) emulator
DS.L 4,IntReturn ; Reserverd /Coprocessor/Format err/ Uninit Interrupt
DS.L 8,IntReturn ; Reserved
DC.L IntReturn ; spurious interrupt
DC.L IntReturn ; IRQ level 1
DC.L IntReturn ; IRQ level 2 EXT
DC.L IntReturn ; IRQ level 3
DC.L IntReturn ; IRQ level 4 Hsync
DC.L IntReturn ; IRQ level 5
DC.L IntReturn ; IRQ level 6 Vsync
DC.L IntReturn ; IRQ level 7
DS.L 16,IntReturn ; TRAPs
DS.L 16,IntReturn ; Misc (FP/MMU)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; Header
DC.B "SEGA GENESIS " ;System Name
DC.B "(C)CHBI " ;Copyright
DC.B "2019.JAN" ;Date
DC.B "ChibiAkumas.com " ; Cart Name
DC.B "ChibiAkumas.com " ; Cart Name (Alt)
DC.B "GM CHIBI001-00" ;TT NNNNNNNN-RR T=Type (GM=Game) N=game Num R=Revision
DC.W $0000 ;16-bit Checksum (Address $000200+)
DC.B "J " ;Control Data (J=3button K=Keyboard 6=6button C=cdrom)
DC.L $00000000 ;ROM Start
DC.L $003FFFFF ;ROM Length
DC.L $00FF0000,$00FFFFFF ;RAM start/end (fixed)
DC.B " " ;External RAM Data
DC.B " " ;Modem Data
DC.B " " ;MEMO
DC.B "JUE " ;Regions Allowed
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; Generic Interrupt Handler
IntReturn:
rte
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; Program Start
ProgramStart:
;initialize TMSS (TradeMark Security System)
move.b ($A10001),D0 ;A10001 test the hardware version
and.b #$0F,D0
beq NoTmss ;branch if no TMSS chip
move.l #'SEGA',($A14000);A14000 disable TMSS
NoTmss:
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; Set Up Graphics
lea VDPSettings,A5 ;Initialize Screen Registers
move.l #VDPSettingsEnd-VDPSettings,D1 ;length of Settings
move.w (VDP_ctrl),D0 ;C00004 read VDP status (interrupt acknowledge?)
move.l #$00008000,d5 ;VDP Reg command (%8rvv)
NextInitByte:
move.b (A5)+,D5 ;get next video control byte
move.w D5,(VDP_ctrl) ;C00004 send write register command to VDP
; 8RVV - R=Reg V=Value
add.w #$0100,D5 ;point to next VDP register
dbra D1,NextInitByte ;loop for rest of block
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; Set up palette and graphics
move.l #$C0000000,d0 ;Color 0
move.l d0,VDP_Ctrl
MOVE.W #$0A00,VDP_Data ;BLUE
move.l #$C01E0000,d0 ;Color 0
move.l d0,VDP_Ctrl
MOVE.W #$00EE,VDP_Data ;YELLOW
lea Graphics,a0 ;background tiles
move.w #(GraphicsEnd-Graphics)-1,d1 ;data size
CLR.L D2 ;start loading at tile 0 of VRAM
jsr DefineTiles
clr.b Cursor_X ;Clear Cursor XY
clr.b Cursor_Y
;Turn on screen
move.w #$8144,(VDP_Ctrl);C00004 reg 1 = 0x44 unblank display
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; TESTING AREA
;load the tilemaps
LEA Conway_Tilemap,a3
LEA ConwayTilemapRam,A2
move.l #(Conway_Backup_Tilemap-Conway_Tilemap),d1
JSR LDIR
LEA Conway_Backup_Tilemap,a3
LEA conwayBackupTilemapRam,A2
move.l #(Conway_Backup_Tilemap-Conway_Tilemap),d1
JSR LDIR
CLR.B Cursor_X
CLR.B Cursor_Y
;print the tilemap once
LEA ConwayTilemapRam,A3
JSR Conway_Print
main:
;do the behavior
jsr Conway_CheckTilemap
;copy the tilemap
lea conwayBackupTilemapRam,A3
LEA ConwayTilemapRam,A2
move.l #(Conway_Backup_Tilemap-Conway_Tilemap),d1
jsr LDIR
CLR.B Cursor_X
CLR.B Cursor_Y
;print the tilemap
LEA ConwayTilemapRam,A3
JSR Conway_Print
;repeat
JMP main
Conway_CheckTilemap:
;since we don't want the partial results of the checks to mess with later ones, we'll copy the changes to a buffer, and then
;have that buffer clobber the original. That way, all changes to the ecosystem are effectively atomic.
LEA ConwayTilemapRam,A0
LEA conwayBackupTilemapRam,A6
LEA (ROWLENGTH+3,A0),A0 ;actual data starts here
LEA (ROWLENGTH+3,A6),A6 ;actual data starts here
.loop:
MOVE.B (A0),D2
CMP.B #255,D2
BEQ .done
CMP.B #2,D2
BEQ .overhead
JSR Conway_CheckNeighbors
pushLong D0
JSR popcnt_8
MOVE.B D0,D3
popLong D0
;now implement the table here.
;neighbor bits in D0
;current state in D2
;popcnt in D3
;pointer to where we are in A0
;the only time the current state is relevant to the output, is when popcnt = 2. Otherwise, it's entirely determined by popcnt.
CMP.B #4,D3
BCC .DeadCell
CMP.B #1,D3
BLS .DeadCell
CMP.B #3,D3
BEQ .LiveCell
;else, must be 2.
MOVE.B D2,(A6) ;store current value into backup table.
bra .overhead
.LiveCell:
MOVE.B #1,(A6)
BRA .overhead
.DeadCell:
MOVE.B #0,(A6) ;store in backup table.
.overhead:
ADDA.L #1,A0
ADDA.L #1,A6
JMP .loop
.done:
RTS
popcnt_8:
pushRegs D2-D5
MOVEQ #8-1,D5
MOVEQ #0,D3
.loop:
ROR.B #1,D0
BCC .overhead
ADDQ.B #1,D3
.overhead:
dbra d5,.loop
MOVE.B D3,D0
popRegs D2-D5
RTS
Conway_CheckNeighbors:
;A0 = pointer to where we are in the tilemap.
;returns: D0.B = uUrRdDlL
;u = top left
;U = top
;r = top Right
;R = Right
;d = bottom right
;D = bottom
;l = bottom Left
;L = Left
pushRegs D2-D5/A0
MOVEQ #0,D0
MOVE.L A0,A1
MOVE.L A1,A2
SUBA.L #ROWLENGTH+2,A1 ;POINTS ABOVE
ADDA.L #ROWLENGTH+2,A2 ;POINTS BELOW
MOVE.B (A1),D1
MOVE.B (A2),D2
CMP.B #1,D1
BNE .noUpper
BSET #6,D0
bra .next
.noUpper:
BCLR #6,D0
.next:
CheckLower:
CMP.B #1,D2
BNE .noLower
BSET #2,D0
bra .next
.noLower:
BCLR #2,D0
.next:
SUBA.L #1,A0 ;left
SUBA.L #1,A1 ;upper-left
SUBA.L #1,A2 ;lower-left
MOVE.B (A1),D1
MOVE.B (A2),D2
MOVE.B (A0),D3
CheckUpperLeft:
CMP.B #1,D1
BNE .noUpperLeft
BSET #7,D0
bra .next
.noUpperLeft:
BCLR #7,D0
.next:
CheckLowerLeft:
CMP.B #1,D2
BNE .noLowerLeft
BSET #1,D0
bra .next
.noLowerLeft:
BCLR #1,D0
.next:
CheckLeft:
CMP.B #1,D3
BNE .noLeft
BSET #0,D0
bra .next
.noLeft:
BCLR #0,D0
.next:
addA.L #2,A0
addA.L #2,A1
addA.L #2,A2
MOVE.B (A1),D1
MOVE.B (A2),D2
MOVE.B (A0),D3
CheckUpperRight:
CMP.B #1,D1
BNE .noUpperRight
BSET #5,D0
bra .next
.noUpperRight:
BCLR #5,D0
.next:
CheckLowerRight:
CMP.B #1,D2
BNE .noLowerRight
BSET #3,D0
bra .next
.noLowerRight:
BCLR #3,D0
.next:
CheckRight:
CMP.B #1,D3
BNE .noRight
BSET #4,D0
bra .next
.noRight:
BCLR #4,D0
.next:
popRegs D2-D5/A0
rts
Conway_Print:
;input: A3 = base address of tilemap
MOVE.B (A3)+,D0
CMP.B #255,D0
BEQ .done
CMP.B #2,D0
BEQ .skip
;else, print
JSR Conway_PrintChar
.skip
BRA Conway_Print
.done
rts
Conway_PrintChar: ;Show D0 to screen
moveM.l d0-d7/a0-a7,-(sp)
and.l #$FF,d0 ;Keep only 1 byte
Move.L #$40000003,d5 ;top 4=write, bottom $3=Cxxx range
MOVEQ #0,D4 ;Tilemap at $C000+
Move.B (Cursor_Y),D4
rol.L #8,D4 ;move $-FFF to $-FFF----
rol.L #8,D4
rol.L #7,D4 ;2 bytes per tile * 64 tiles per line
add.L D4,D5 ;add $4------3
Move.B (Cursor_X),D4
rol.L #8,D4 ;move $-FFF to $-FFF----
rol.L #8,D4
rol.L #1,D4 ;2 bytes per tile
add.L D4,D5 ;add $4------3
MOVE.L D5,(VDP_ctrl) ; C00004 write next character to VDP
MOVE.W D0,(VDP_data) ; C00000 store next word of name data
addq.b #1,(Cursor_X) ;INC Xpos
move.b (Cursor_X),d0
cmp.b #39,d0
bls .nextpixel_Xok
jsr NewLine ;If we're at end of line, start newline
.nextpixel_Xok:
moveM.l (sp)+,d0-d7/a0-a7
rts
;don't forget, these are in ROM so we can't write to them directly.
;instead, they will be copied to ram and worked with from there.
Conway_Tilemap: ;(screenwidth + 2) by (screenheight+2)
DC.B $02,$02,$02,$02,$02,$02,$02,$02,$02,$02,$02,$02,$02,$02,$02,$02,$02,$02,$02,$02,$02,$02,$02,$02,$02,$02,$02,$02,$02,$02,$02,$02,$02,$02,$02,$02,$02,$02,$02,$02,$02,$02
DC.B $02,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$02
DC.B $02,$00,$00,$01,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$01,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$02
DC.B $02,$00,$00,$00,$01,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$01,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$02
DC.B $02,$00,$01,$01,$01,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$01,$01,$01,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$02
DC.B $02,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$02
DC.B $02,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$02
DC.B $02,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$02
DC.B $02,$00,$00,$00,$00,$00,$00,$00,$00,$00,$01,$01,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$02
DC.B $02,$00,$00,$00,$00,$00,$00,$00,$00,$01,$00,$00,$01,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$02
DC.B $02,$00,$01,$01,$00,$00,$00,$00,$00,$00,$01,$01,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$02
DC.B $02,$00,$01,$01,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$02
DC.B $02,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$02
DC.B $02,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$02
DC.B $02,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$02
DC.B $02,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$02
DC.B $02,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$02
DC.B $02,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$02
DC.B $02,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$02
DC.B $02,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$02
DC.B $02,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$02
DC.B $02,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$02
DC.B $02,$00,$00,$00,$00,$01,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$02
DC.B $02,$00,$00,$00,$00,$01,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$02
DC.B $02,$00,$00,$00,$00,$01,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$02
DC.B $02,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$02
DC.B $02,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$02
DC.B $02,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$02
DC.B $02,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$02
DC.B $02,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$02
DC.B $02,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$02
DC.B $02,$02,$02,$02,$02,$02,$02,$02,$02,$02,$02,$02,$02,$02,$02,$02,$02,$02,$02,$02,$02,$02,$02,$02,$02,$02,$02,$02,$02,$02,$02,$02,$02,$02,$02,$02,$02,$02,$02,$02,$02,$02
DC.B 255
EVEN
Conway_Backup_Tilemap: ;(screenwidth + 2) by (screenheight+2)
DC.B $02,$02,$02,$02,$02,$02,$02,$02,$02,$02,$02,$02,$02,$02,$02,$02,$02,$02,$02,$02,$02,$02,$02,$02,$02,$02,$02,$02,$02,$02,$02,$02,$02,$02,$02,$02,$02,$02,$02,$02,$02,$02
rept 30
DC.B $02,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$02
endr
DC.B $02,$02,$02,$02,$02,$02,$02,$02,$02,$02,$02,$02,$02,$02,$02,$02,$02,$02,$02,$02,$02,$02,$02,$02,$02,$02,$02,$02,$02,$02,$02,$02,$02,$02,$02,$02,$02,$02,$02,$02,$02,$02
DC.B 255
EVEN
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
NewLine:
addq.b #1,(Cursor_Y) ;INC Y
clr.b (Cursor_X) ;Zero X
rts
LDIR: ;COPY D1 BYTES FROM A3 TO A2
move.b (a3)+,(a2)+
DBRA D1,LDIR
rts
DefineTiles: ;Copy D1 bytes of data from A0 to VDP memory D2
jsr prepareVram ;Calculate the memory location we want to write
.again: ; the tile pattern definitions to
move.l (a0)+,(VDP_data)
dbra d1,.again
rts
prepareVram: ;To select a memory location D2 we need to calculate
;the command byte... depending on the memory location
pushall ;$7FFF0003 = Vram $FFFF.... $40000000=Vram $0000
move.l d2,d0
and.w #%1100000000000000,d0 ;Shift the top two bits to the far right
rol.w #2,d0
and.l #%0011111111111111,d2 ; shift all the other bits left two bytes
rol.l #8,d2
rol.l #8,d2
or.l d0,d2
or.l #$40000000,d2 ;Set the second bit from the top to 1
;#%01000000 00000000 00000000 00000000
move.l d2,(VDP_ctrl)
popallRTS:
popall
rts
Graphics:
DC.L $0000000F,$0000000F,$0000000F,$0000000F,$0000000F,$0000000F,$0000000F,$FFFFFFFF
DC.L $FFFFFFFF,$FFFFFFFF,$FFFFFFFF,$FFFFFFFF,$FFFFFFFF,$FFFFFFFF,$FFFFFFFF,$FFFFFFFF
GraphicsEnd:
VDPSettings:
DC.B $04 ; 0 mode register 1 ---H-1M-
DC.B $04 ; 1 mode register 2 -DVdP---
DC.B $30 ; 2 name table base for scroll A (A=top 3 bits) --AAA--- = $C000
DC.B $3C ; 3 name table base for window (A=top 4 bits / 5 in H40 Mode) --AAAAA- = $F000
DC.B $07 ; 4 name table base for scroll B (A=top 3 bits) -----AAA = $E000
DC.B $6C ; 5 sprite attribute table base (A=top 7 bits / 6 in H40) -AAAAAAA = $D800
DC.B $00 ; 6 unused register --------
DC.B $00 ; 7 background color (P=Palette C=Color) --PPCCCC
DC.B $00 ; 8 unused register --------
DC.B $00 ; 9 unused register --------
DC.B $FF ;10 H interrupt register (L=Number of lines) LLLLLLLL
DC.B $00 ;11 mode register 3 ----IVHL
DC.B $81 ;12 mode register 4 (C bits both1 = H40 Cell) C---SIIC
DC.B $37 ;13 H scroll table base (A=Top 6 bits) --AAAAAA = $FC00
DC.B $00 ;14 unused register --------
DC.B $02 ;15 auto increment (After each Read/Write) NNNNNNNN
DC.B $01 ;16 scroll size (Horiz & Vert size of ScrollA & B) --VV--HH = 64x32 tiles
DC.B $00 ;17 window H position (D=Direction C=Cells) D--CCCCC
DC.B $00 ;18 window V position (D=Direction C=Cells) D--CCCCC
DC.B $FF ;19 DMA length count low LLLLLLLL
DC.B $FF ;20 DMA length count high HHHHHHHH
DC.B $00 ;21 DMA source address low LLLLLLLL
DC.B $00 ;22 DMA source address mid MMMMMMMM
DC.B $80 ;23 DMA source address high (C=CMD) CCHHHHHH
VDPSettingsEnd:
even |
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
| #J | J | NB. Create a "Point" class
coclass'Point'
NB. Define its constructor
create =: 3 : 0
'X Y' =: y
)
NB. Instantiate an instance (i.e. an object)
cocurrent 'base'
P =: 10 20 conew 'Point'
NB. Interrogate its members
X__P
10
Y__P
20 |
http://rosettacode.org/wiki/Compound_data_type | Compound data type |
Data Structure
This illustrates a data structure, a means of storing data within a program.
You may see other such structures in the Data Structures category.
Task
Create a compound data type:
Point(x,y)
A compound data type is one that holds multiple independent values.
Related task
Enumeration
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
| #Java | Java | public class Point
{
public int x, y;
public Point() { this(0); }
public Point(int x0) { this(x0,0); }
public Point(int x0, int y0) { x = x0; y = y0; }
public static void main(String args[])
{
Point point = new Point(1,2);
System.out.println("x = " + point.x );
System.out.println("y = " + 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.
| #XPL0 | XPL0 | include c:\cxpl\codes;
int N;
real A, B, F;
[Format(1, 15);
A:= 2.0; B:= 1.0; N:= 16;
IntOut(0, N); CrLf(0);
F:= 0.0;
while N>=1 do [F:= B/(A+F); N:= N-1];
RlOut(0, 1.0+F); CrLf(0);
RlOut(0, sqrt(2.0)); CrLf(0);
N:= 13;
IntOut(0, N); CrLf(0);
F:= 0.0;
while N>=2 do [F:= float(N-1)/(float(N)+F); N:= N-1];
RlOut(0, 2.0 + 1.0/(1.0+F)); CrLf(0);
RlOut(0, Exp(1.0)); CrLf(0);
N:= 10000;
IntOut(0, N); CrLf(0);
F:= 0.0;
while N>=1 do [F:= float(sq(2*N-1))/(6.0+F); N:= N-1];
RlOut(0, 3.0+F); CrLf(0);
RlOut(0, ACos(-1.0)); CrLf(0);
] |
http://rosettacode.org/wiki/Continued_fraction | Continued fraction | continued fraction
Mathworld
a
0
+
b
1
a
1
+
b
2
a
2
+
b
3
a
3
+
⋱
{\displaystyle a_{0}+{\cfrac {b_{1}}{a_{1}+{\cfrac {b_{2}}{a_{2}+{\cfrac {b_{3}}{a_{3}+\ddots }}}}}}}
The task is to write a program which generates such a number and prints a real representation of it. The code should be tested by calculating and printing the square root of 2, Napier's Constant, and Pi, using the following coefficients:
For the square root of 2, use
a
0
=
1
{\displaystyle a_{0}=1}
then
a
N
=
2
{\displaystyle a_{N}=2}
.
b
N
{\displaystyle b_{N}}
is always
1
{\displaystyle 1}
.
2
=
1
+
1
2
+
1
2
+
1
2
+
⋱
{\displaystyle {\sqrt {2}}=1+{\cfrac {1}{2+{\cfrac {1}{2+{\cfrac {1}{2+\ddots }}}}}}}
For Napier's Constant, use
a
0
=
2
{\displaystyle a_{0}=2}
, then
a
N
=
N
{\displaystyle a_{N}=N}
.
b
1
=
1
{\displaystyle b_{1}=1}
then
b
N
=
N
−
1
{\displaystyle b_{N}=N-1}
.
e
=
2
+
1
1
+
1
2
+
2
3
+
3
4
+
⋱
{\displaystyle e=2+{\cfrac {1}{1+{\cfrac {1}{2+{\cfrac {2}{3+{\cfrac {3}{4+\ddots }}}}}}}}}
For Pi, use
a
0
=
3
{\displaystyle a_{0}=3}
then
a
N
=
6
{\displaystyle a_{N}=6}
.
b
N
=
(
2
N
−
1
)
2
{\displaystyle b_{N}=(2N-1)^{2}}
.
π
=
3
+
1
6
+
9
6
+
25
6
+
⋱
{\displaystyle \pi =3+{\cfrac {1}{6+{\cfrac {9}{6+{\cfrac {25}{6+\ddots }}}}}}}
See also
Continued fraction/Arithmetic for tasks that do arithmetic over continued fractions.
| #zkl | zkl | fcn cf(fa,fb,a0){fcn(fa,fb,a0,n){
a0 + [n..1,-1].reduce(
'wrap(p,n){ fb(n)/(fa(n)+p) },0.0) }.fp(fa,fb,a0)
} |
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
| #Red | Red |
Red[]
originalString: "hello wordl"
copiedString: originalString
; OR
copiedString2: copy originalString
|
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
| #Retro | Retro | 'this_is_a_string dup s:temp |
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.
| #Perl | Perl | my @points;
while (@points < 100) {
my ($x, $y) = (int(rand(31))-15, int(rand(31)) - 15);
my $r2 = $x*$x + $y*$y;
next if $r2 < 100 || $r2 > 225;
push @points, [$x, $y];
}
print << 'HEAD';
%!PS-Adobe-3.0 EPSF-3.0
%%BoundingBox 0 0 400 400
200 200 translate 10 10 scale
0 setlinewidth
1 0 0 setrgbcolor
0 0 10 0 360 arc stroke
0 0 15 360 0 arcn stroke
0 setgray
/pt { .1 0 360 arc fill } def
HEAD
print "@$_ pt\n" for @points;
print "%%EOF"; |
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/
| #Standard_ML | Standard ML | (*
* Convex hulls by Andrew's monotone chain algorithm.
*
* For a description of the algorithm, see
* https://en.wikibooks.org/w/index.php?title=Algorithm_Implementation/Geometry/Convex_hull/Monotone_chain&stableid=40169
*)
(*------------------------------------------------------------------*)
(*
* Just enough plane geometry for our purpose.
*)
signature PLANE_POINT =
sig
type planePoint
val planePoint : real * real -> planePoint
val toTuple : planePoint -> real * real
val x : planePoint -> real
val y : planePoint -> real
val == : planePoint * planePoint -> bool
(* Impose a total order on points, making it one that will work for
Andrew's monotone chain algorithm. *)
val order : planePoint * planePoint -> bool
(* Subtraction is really a vector or multivector operation. *)
val subtract : planePoint * planePoint -> planePoint
(* Cross product is really a multivector operation. *)
val cross : planePoint * planePoint -> real
val toString : planePoint -> string
end
structure PlanePoint : PLANE_POINT =
struct
type planePoint = real * real
fun planePoint xy = xy
fun toTuple (x, y) = (x, y)
fun x (x, _) = x
fun y (_, y) = y
fun == ((a : real, b : real), (c : real, d : real)) =
Real.== (a, c) andalso Real.== (b, d)
fun order ((a : real, b : real), (c : real, d : real)) =
Real.< (a, c) orelse (Real.== (a, c) andalso Real.< (b, d))
fun subtract ((a : real, b : real), (c : real, d : real)) =
(a - c, b - d)
fun cross ((a : real, b : real), (c : real, d : real)) =
(a * d) - (b * c)
fun toString (x, y) =
"(" ^ Real.toString x ^ " " ^ Real.toString y ^ ")"
end
(*------------------------------------------------------------------*)
(*
* Rather than rely on compiler extensions for sorting, let us write
* our own.
*
* For no special reason, let us use the Shell sort of
* https://en.wikipedia.org/w/index.php?title=Shellsort&oldid=1084744510
*)
val ciura_gaps = Array.fromList [701, 301, 132, 57, 23, 10, 4, 1]
fun sort_in_place less arr =
let
open Array
fun span_gap gap =
let
fun iloop i =
if length arr <= i then
()
else
let
val temp = sub (arr, i)
fun jloop j =
if j < gap orelse
less (sub (arr, j - gap), temp) then
update (arr, j, temp)
else
(update (arr, j, sub (arr, j - gap));
jloop (j - gap))
in
jloop i;
iloop (i + gap)
end
in
iloop 0
end
in
app span_gap ciura_gaps
end
(*------------------------------------------------------------------*)
(*
* To go with our sort routine, we want something akin to
* array_delete_neighbor_dups of Scheme's SRFI-132.
*)
fun array_delete_neighbor_dups equal arr =
let
open Array
fun loop i lst =
(* Cons a list of non-duplicates, going backwards through
the array so the list will be in forwards order. *)
if i = 0 then
sub (arr, i) :: lst
else if equal (sub (arr, i - 1), sub (arr, i)) then
loop (i - 1) lst
else
loop (i - 1) (sub (arr, i) :: lst)
val n = length arr
in
fromList (if n = 0 then [] else loop (n - 1) [])
end
(*------------------------------------------------------------------*)
(*
* The convex hull algorithm.
*)
fun cross_test (pt_i, hull, j) =
let
open PlanePoint
val hull_j = Array.sub (hull, j)
val hull_j1 = Array.sub (hull, j - 1)
in
0.0 < cross (subtract (hull_j, hull_j1),
subtract (pt_i, hull_j1))
end
fun construct_lower_hull (n, pt) =
let
open PlanePoint
val hull = Array.array (n, planePoint (0.0, 0.0))
val () = Array.update (hull, 0, Array.sub (pt, 0))
val () = Array.update (hull, 1, Array.sub (pt, 1))
fun outer_loop i j =
if i = n then
j + 1
else
let
val pt_i = Array.sub (pt, i)
fun inner_loop j =
if j = 0 orelse cross_test (pt_i, hull, j) then
(Array.update (hull, j + 1, pt_i);
j + 1)
else
inner_loop (j - 1)
in
outer_loop (i + 1) (inner_loop j)
end
val hull_size = outer_loop 2 1
in
(hull_size, hull)
end
fun construct_upper_hull (n, pt) =
let
open PlanePoint
val hull = Array.array (n, planePoint (0.0, 0.0))
val () = Array.update (hull, 0, Array.sub (pt, n - 1))
val () = Array.update (hull, 1, Array.sub (pt, n - 2))
fun outer_loop i j =
if i = ~1 then
j + 1
else
let
val pt_i = Array.sub (pt, i)
fun inner_loop j =
if j = 0 orelse cross_test (pt_i, hull, j) then
(Array.update (hull, j + 1, pt_i);
j + 1)
else
inner_loop (j - 1)
in
outer_loop (i - 1) (inner_loop j)
end
val hull_size = outer_loop (n - 3) 1
in
(hull_size, hull)
end
fun construct_hull (n, pt) =
let
(* Side note: Construction of the lower and upper hulls can be
done in parallel. *)
val (lower_hull_size, lower_hull) = construct_lower_hull (n, pt)
and (upper_hull_size, upper_hull) = construct_upper_hull (n, pt)
val hull_size = lower_hull_size + upper_hull_size - 2
val hull =
Array.array (hull_size, PlanePoint.planePoint (0.0, 0.0))
fun copy_lower i =
if i = lower_hull_size - 1 then
()
else
(Array.update (hull, i, Array.sub (lower_hull, i));
copy_lower (i + 1))
fun copy_upper i =
if i = upper_hull_size - 1 then
()
else
(Array.update (hull, i + lower_hull_size - 1,
Array.sub (upper_hull, i));
copy_upper (i + 1))
in
copy_lower 0;
copy_upper 0;
hull
end
fun plane_convex_hull points_lst =
(* Takes an arbitrary list of points, which may be in any order
and may contain duplicates. Returns an ordered array of points
that make up the convex hull. If the list of points is empty,
the returned array is empty. *)
let
val pt = Array.fromList points_lst
val () = sort_in_place PlanePoint.order pt
val pt = array_delete_neighbor_dups (PlanePoint.==) pt
val n = Array.length pt
in
if n <= 2 then
pt
else
construct_hull (n, pt)
end
(*------------------------------------------------------------------*)
fun main () =
let
open PlanePoint
val example_points =
[planePoint (16.0, 3.0),
planePoint (12.0, 17.0),
planePoint (0.0, 6.0),
planePoint (~4.0, ~6.0),
planePoint (16.0, 6.0),
planePoint (16.0, ~7.0),
planePoint (16.0, ~3.0),
planePoint (17.0, ~4.0),
planePoint (5.0, 19.0),
planePoint (19.0, ~8.0),
planePoint (3.0, 16.0),
planePoint (12.0, 13.0),
planePoint (3.0, ~4.0),
planePoint (17.0, 5.0),
planePoint (~3.0, 15.0),
planePoint (~3.0, ~9.0),
planePoint (0.0, 11.0),
planePoint (~9.0, ~3.0),
planePoint (~4.0, ~2.0),
planePoint (12.0, 10.0)]
val hull = plane_convex_hull example_points
in
Array.app (fn p => (print (toString p);
print " "))
hull;
print "\n"
end;
main ();
(*------------------------------------------------------------------*)
(* local variables: *)
(* mode: sml *)
(* sml-indent-level: 2 *)
(* sml-indent-args: 2 *)
(* end: *) |
http://rosettacode.org/wiki/Convert_seconds_to_compound_duration | Convert seconds to compound duration | Task
Write a function or program which:
takes a positive integer representing a duration in seconds as input (e.g., 100), and
returns a string which shows the same duration decomposed into:
weeks,
days,
hours,
minutes, and
seconds.
This is detailed below (e.g., "2 hr, 59 sec").
Demonstrate that it passes the following three test-cases:
Test Cases
input number
output string
7259
2 hr, 59 sec
86400
1 d
6000000
9 wk, 6 d, 10 hr, 40 min
Details
The following five units should be used:
unit
suffix used in output
conversion
week
wk
1 week = 7 days
day
d
1 day = 24 hours
hour
hr
1 hour = 60 minutes
minute
min
1 minute = 60 seconds
second
sec
However, only include quantities with non-zero values in the output (e.g., return "1 d" and not "0 wk, 1 d, 0 hr, 0 min, 0 sec").
Give larger units precedence over smaller ones as much as possible (e.g., return 2 min, 10 sec and not 1 min, 70 sec or 130 sec)
Mimic the formatting shown in the test-cases (quantities sorted from largest unit to smallest and separated by comma+space; value and unit of each quantity separated by space).
| #VBScript | VBScript |
Function compound_duration(n)
Do Until n = 0
If n >= 604800 Then
wk = Int(n/604800)
n = n-(604800*wk)
compound_duration = compound_duration & wk & " wk"
End If
If n >= 86400 Then
d = Int(n/86400)
n = n-(86400*d)
If wk > 0 Then compound_duration = compound_duration & ", " End If
compound_duration = compound_duration & d & " d"
End If
If n >= 3600 Then
hr = Int(n/3600)
n = n-(3600*hr)
If d > 0 Then compound_duration = compound_duration & ", " End If
compound_duration = compound_duration & hr & " hr"
End If
If n >= 60 Then
min = Int(n/60)
n = n-(60*min)
If hr > 0 Then compound_duration = compound_duration & ", " End If
compound_duration = compound_duration & min & " min"
End If
If n > 0 Then
If min > 0 Then compound_duration = compound_duration & ", " End If
compound_duration = compound_duration & ", " & n & " sec"
n = 0
End If
Loop
End Function
'validating the function
WScript.StdOut.WriteLine compound_duration(7259)
WScript.StdOut.WriteLine compound_duration(86400)
WScript.StdOut.WriteLine compound_duration(6000000)
|
http://rosettacode.org/wiki/Concurrent_computing | Concurrent computing | Task
Using either native language concurrency syntax or freely available libraries, write a program to display the strings "Enjoy" "Rosetta" "Code", one string per line, in random order.
Concurrency syntax must use threads, tasks, co-routines, or whatever concurrency is called in your language.
| #Oz | Oz | for Msg in ["Enjoy" "Rosetta" "Code"] do
thread
{System.showInfo Msg}
end
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.
| #PARI.2FGP | PARI/GP | inline(func);
func(n)=print(["Enjoy","Rosetta","Code"][n]);
parapply(func,[1..3]); |
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.
| #m4 | m4 | define(`factorial',
`ifelse($1, 0, 1, `eval($1 * factorial(eval($1 - 1)))')')dnl
dnl
BEGIN {
print "10! is 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.
| #Mathematica_.2F_Wolfram_Language | Mathematica / Wolfram Language | f = Compile[{}, 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.
| #Nim | Nim | proc fact(x: int): int =
result = 1
for i in 2..x:
result = result * i
const fact10 = fact(10)
echo(fact10) |
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.
| #Oberon-2 | Oberon-2 |
MODULE CompileTime;
IMPORT
Out;
CONST
tenfac = 10*9*8*7*6*5*4*3*2;
BEGIN
Out.String("10! =");Out.LongInt(tenfac,0);Out.Ln
END CompileTime.
|
http://rosettacode.org/wiki/Conditional_structures | Conditional structures | Control Structures
These are examples of control structures. You may also be interested in:
Conditional structures
Exceptions
Flow-control structures
Loops
Task
List the conditional structures offered by a programming language. See Wikipedia: conditionals for descriptions.
Common conditional structures include if-then-else and switch.
Less common are arithmetic if, ternary operator and Hash-based conditionals.
Arithmetic if allows tight control over computed gotos, which optimizers have a hard time to figure out.
| #360_Assembly | 360 Assembly | * Unconditional Branch or No Branch:
B label Unconditional
BR Rx "
NOP label No Operation
NOPR Rx "
* After Compare Instructions
BH label Branch on High
BHR Rx "
BL label Branch on Low
BLR Rx "
BE label Branch on Equal
BER Rx "
BNH label Branch on Not High
BNHR Rx "
BNL label Branch on Not Low
BNLR Rx "
BNE label Branch on Not Equal
BNER Rx "
* After Arithmetic Instructions:
BP label Branch on Plus
BPR Rx "
BM label Branch on Minus
BMR Rx "
BZ label Branch on Zero
BZR Rx "
BO label Branch on Overflow
BOR Rx "
BNP label Branch on Not Plus
BNPR Rx "
BNM label Branch on Not Minus
BNMR Rx "
BNZ label Branch on Not Zero
BNZR Rx "
BNO label Branch on No Overflow
BNOR Rx "
* After Test Under Mask Instructions:
BO label Branch if Ones
BOR Rx "
BM label Branch if Mixed
BMR Rx "
BZ label Branch if Zero
BZR Rx "
BNO label Branch if Not Ones
BNOR Rx "
BNM label Branch if Not Mixed
BNMR Rx "
BNZ label Branch if Not Zero
BNZR Rx " |
http://rosettacode.org/wiki/Conway%27s_Game_of_Life | Conway's Game of Life | The Game of Life is a cellular automaton devised by the British mathematician John Horton Conway in 1970. It is the best-known example of a cellular automaton.
Conway's game of life is described here:
A cell C is represented by a 1 when alive, or 0 when dead, in an m-by-m (or m×m) square array of cells.
We calculate N - the sum of live cells in C's eight-location neighbourhood, then cell C is alive or dead in the next generation based on the following table:
C N new C
1 0,1 -> 0 # Lonely
1 4,5,6,7,8 -> 0 # Overcrowded
1 2,3 -> 1 # Lives
0 3 -> 1 # It takes three to give birth!
0 0,1,2,4,5,6,7,8 -> 0 # Barren
Assume cells beyond the boundary are always dead.
The "game" is actually a zero-player game, meaning that its evolution is determined by its initial state, needing no input from human players. One interacts with the Game of Life by creating an initial configuration and observing how it evolves.
Task
Although you should test your implementation on more complex examples such as the glider in a larger universe, show the action of the blinker (three adjoining cells in a row all alive), over three generations, in a 3 by 3 grid.
References
Its creator John Conway, explains the game of life. Video from numberphile on youtube.
John Conway Inventing Game of Life - Numberphile video.
Related task
Langton's ant - another well known cellular automaton.
| #ABAP | ABAP |
*&---------------------------------------------------------------------*
*& Report ZCONWAYS_GAME_OF_LIFE
*&---------------------------------------------------------------------*
*& by Marcelo Bovo
*&---------------------------------------------------------------------*
report zconways_game_of_life line-size 174 no standard page heading
line-count 40.
parameters: p_char type c default '#',
p_pos type string.
class lcl_game_of_life definition.
public section.
data: x_max type i value 174,
y_max type i value 40,
character type c value abap_true,
x type i,
y type i,
pos type string,
offlimits type i value 9998,
grid(9999) type c. " every X_MAX characters on grid equals one line on screen
data: o_random_y type ref to cl_abap_random_int,
o_random_x type ref to cl_abap_random_int.
methods: constructor,
play,
initial_position,
initial_grid,
write,
change_grid.
endclass.
class lcl_game_of_life implementation.
method constructor.
o_random_y = cl_abap_random_int=>create( seed = cl_abap_random=>create( conv i( sy-uzeit ) )->intinrange( low = 1 high = 999999 )
min = 1
max = y_max ).
o_random_x = cl_abap_random_int=>create( seed = cl_abap_random=>create( conv i( |{ sy-datum(4) }{ sy-uzeit }| ) )->intinrange( low = 1 high = 999999 )
min = 1
max = x_max ).
endmethod.
method play.
"fill initial data ramdonly if user hasnt typed any coordenates
if pos is initial.
initial_position( ).
endif.
initial_grid( ).
write( ).
endmethod.
method initial_position.
do cl_abap_random_int=>create( "seed = conv i( sy-uzeit )
min = 50
max = 800 )->get_next( ) times.
data(lv_index) = sy-index.
x = o_random_x->get_next( ).
y = o_random_y->get_next( ).
p_pos = |{ p_pos }{ switch char1( lv_index when '1' then space else ';' ) }{ y },{ x }|.
enddo.
endmethod.
method initial_grid.
"Split coordenates
split p_pos at ';' into table data(lt_pos_inicial) .
"Sort By Line(Easy to read)
sort lt_pos_inicial.
loop at lt_pos_inicial assigning field-symbol(<pos_inicial>).
split <pos_inicial> at ',' into data(y_char) data(x_char).
x = x_char.
y = y_char.
"Ensure maximum coordenates are not surpassed
x = cond #( when x <= x_max then x
else o_random_x->get_next( ) ).
y = cond #( when y <= y_max then y
else o_random_y->get_next( ) ).
"Write on string grid
"Every x_max lines represent one line(Y) on the grid
data(grid_xy) = ( x_max * y ) + x - x_max - 1.
grid+grid_xy(1) = character.
endloop.
endmethod.
method write.
skip to line 1.
"Write every line on screen
do y_max times.
data(lv_index) = sy-index - 1.
"Write whole line(current line plus number of maximum X characters)
data(grid_xy) = ( lv_index * x_max ).
write / grid+grid_xy(x_max) no-gap.
if grid+grid_xy(x_max) is initial.
skip.
endif.
enddo.
change_grid( ).
endmethod.
method change_grid.
data(grid_aux) = grid.
clear grid_aux.
data(grid_size) = strlen( grid ).
"Validate neighbours based on previous written grid
"ABC
"D.F
"GHI
do grid_size + x_max times.
"Doens't write anything beyond borders
check sy-index <= x_max * y_max.
data(grid_xy) = sy-index - 1.
data(neighbours) = 0.
"Current Line neighbours
data(d) = grid_xy - 1.
data(f) = grid_xy + 1.
"Line above neighbours
data(b) = grid_xy - x_max.
data(a) = b - 1.
data(c) = b + 1.
"Line Bellow neighbours
data(h) = grid_xy + x_max.
data(g) = h - 1.
data(i) = h + 1.
"Previous Neighbours
neighbours += cond #( when a < 0 then 0 else cond #( when grid+a(1) is not initial then 1 else 0 ) ).
neighbours += cond #( when b < 0 then 0 else cond #( when grid+b(1) is not initial then 1 else 0 ) ).
neighbours += cond #( when c < 0 then 0 else cond #( when grid+c(1) is not initial then 1 else 0 ) ).
neighbours += cond #( when d < 0 then 0 else cond #( when grid+d(1) is not initial then 1 else 0 ) ).
"Next Neighbours
neighbours += cond #( when f > grid_size then 0 else cond #( when grid+f(1) is not initial then 1 else 0 ) ).
neighbours += cond #( when g > grid_size then 0 else cond #( when grid+g(1) is not initial then 1 else 0 ) ).
neighbours += cond #( when h > grid_size then 0 else cond #( when grid+h(1) is not initial then 1 else 0 ) ).
neighbours += cond #( when i > grid_size then 0 else cond #( when grid+i(1) is not initial then 1 else 0 ) ).
grid_aux+grid_xy(1) = cond #( when neighbours = 3 or ( neighbours = 2 and grid+grid_xy(1) = character )
then character
else space ).
enddo.
grid = grid_aux.
endmethod.
endclass.
start-of-selection.
set pf-status 'STANDARD_FULLSCREEN'. "Use &REFRESH button with F8 Shortcut to go to next generation
data(lo_prog) = new lcl_game_of_life( ).
lo_prog->character = p_char.
lo_prog->pos = p_pos.
lo_prog->play( ).
at user-command.
case sy-ucomm.
when 'REFR' or '&REFRESH'.
sy-lsind = 1. "Prevents LIST_TOO_MANY_LEVELS DUMP
lo_prog->write( ).
when others.
leave list-processing.
endcase.
|
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
| #JavaScript | JavaScript | //using object literal syntax
var point = {x : 1, y : 2};
//using constructor
var Point = function (x, y) {
this.x = x;
this.y = y;
};
point = new Point(1, 2);
//using ES6 class syntax
class Point {
constructor(x, y) {
this.x = x;
this.y = y;
}
}
point = new Point(1, 2); |
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
| #jq | jq | {"x":1, "y":2} |
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.
| #ZX_Spectrum_Basic | ZX Spectrum Basic | 10 LET a0=1: LET b1=1: LET a$="2": LET b$="1": PRINT "SQR(2) = ";: GO SUB 1000
20 LET a0=2: LET b1=1: LET a$="N": LET b$="N": PRINT "e = ";: GO SUB 1000
30 LET a0=3: LET b1=1: LET a$="6": LET b$="(2*N+1)^2": PRINT "PI = ";: GO SUB 1000
100 STOP
1000 LET n=0: LET e$="": LET p$=""
1010 LET n=n+1
1020 LET e$=e$+STR$ VAL a$+"+"+STR$ VAL b$+"/("
1030 IF LEN e$<(4000-n) THEN GO TO 1010
1035 FOR i=1 TO n: LET p$=p$+")": NEXT i
1040 PRINT a0+b1/VAL (e$+"1"+p$)
1050 RETURN |
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
| #REXX | REXX | src = "this is a string"
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
| #Ring | Ring |
cStr1 = "Hello!" # create original string
cStr2 = cStr1 # make new string from original
|
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.
| #Phix | Phix | with javascript_semantics
sequence screen = repeat(repeat(' ',31),31)
integer x, y, count = 0
atom r
while 1 do
x = rand(31)
y = rand(31)
r = sqrt(power(x-16,2)+power(y-16,2))
if r>=10 and r<=15 then
screen[x][y] = 'x'
count += 1
if count>=100 then exit end if
end if
end while
puts(1,join(screen,"\n"))
|
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/
| #Swift | Swift | public struct Point: Equatable, Hashable {
public var x: Double
public var y: Double
public init(fromTuple t: (Double, Double)) {
self.x = t.0
self.y = t.1
}
}
public func calculateConvexHull(fromPoints points: [Point]) -> [Point] {
guard points.count >= 3 else {
return points
}
var hull = [Point]()
let (leftPointIdx, _) = points.enumerated().min(by: { $0.element.x < $1.element.x })!
var p = leftPointIdx
var q = 0
repeat {
hull.append(points[p])
q = (p + 1) % points.count
for i in 0..<points.count where calculateOrientation(points[p], points[i], points[q]) == .counterClockwise {
q = i
}
p = q
} while p != leftPointIdx
return hull
}
private func calculateOrientation(_ p: Point, _ q: Point, _ r: Point) -> Orientation {
let val = (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y)
if val == 0 {
return .straight
} else if val > 0 {
return .clockwise
} else {
return .counterClockwise
}
}
private enum Orientation {
case straight, clockwise, counterClockwise
}
let 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),
(12,10)
].map(Point.init(fromTuple:))
print("Input: \(points)")
print("Output: \(calculateConvexHull(fromPoints: points))") |
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).
| #Wren | Wren | var duration = Fn.new { |s|
if (s < 1) return "0 sec"
var dur = ""
var divs = [7, 24, 60, 60, 1]
var units = ["wk", "d", "hr", "min", "sec"]
var t = divs.reduce { |prod, div| prod * div }
for (i in 0...divs.count) {
var u = (s/t).floor
if (u > 0) {
dur = dur + "%(u) %(units[i]), "
s = s % t
}
t = t / divs[i]
}
if (dur.endsWith(", ")) dur = dur[0..-3]
return dur
}
for (s in [7259, 86400, 6000000]) System.print(duration.call(s)) |
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.
| #Pascal | Pascal | program ConcurrentComputing;
{$IFdef FPC}
{$MODE DELPHI}
{$ELSE}
{$APPTYPE CONSOLE}
{$ENDIF}
uses
{$IFDEF UNIX}
cthreads,
{$ENDIF}
SysUtils, Classes;
type
TRandomThread = class(TThread)
private
FString: string;
T0 : Uint64;
protected
procedure Execute; override;
public
constructor Create(const aString: string); overload;
end;
const
MyStrings: array[0..2] of String = ('Enjoy ','Rosetta ','Code ');
var
gblRunThdCnt : LongWord = 0;
constructor TRandomThread.Create(const aString: string);
begin
inherited Create(False);
FreeOnTerminate := True;
FString := aString;
interlockedincrement(gblRunThdCnt);
end;
procedure TRandomThread.Execute;
var
i : NativeInt;
begin
i := Random(300);
T0 := GettickCount64;
Sleep(i);
//output of difference in time
Writeln(FString,i:4,GettickCount64-T0 -i:2);
interlockeddecrement(gblRunThdCnt);
end;
var
lThreadArray: Array[0..9] of THandle;
i : NativeInt;
begin
Randomize;
gblRunThdCnt := 0;
For i := low(lThreadArray) to High(lThreadArray) do
lThreadArray[i] := TRandomThread.Create(Format('%9s %4d',[myStrings[Random(3)],i])).Handle;
while gblRunThdCnt > 0 do
sleep(125);
end. |
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.
| #Objeck | Objeck |
bundle Default {
class CompileTime {
function : Main(args : String[]) ~ Nil {
(10*9*8*7*6*5*4*3*2*1)->PrintLine();
}
}
}
|
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.
| #OCaml | OCaml | let days_to_seconds n =
let conv = 24 * 60 * 60 in
(n * conv)
;; |
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.
| #Oforth | Oforth | 10 seq reduce(#*) Constant new: FACT10
: newFunction FACT10 . ; |
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.
| #OxygenBasic | OxygenBasic |
'LIBRARY CALLS
'=============
extern lib "../../oxygen.dll"
declare o2_basic (string src)
declare o2_exec (optional sys p) as sys
declare o2_errno () as sys
declare o2_error () as string
extern lib "kernel32.dll"
declare QueryPerformanceFrequency(quad*freq)
declare QueryPerformanceCounter(quad*count)
end extern
'EMBEDDED SOURCE CODE
'====================
src=quote
===Source===
def Pling10 2*3*4*5*6*7*8*9*10
byte a[pling10] 'Pling10 is resolved to a number here at compile time
print pling10
===Source===
'TIMER
'=====
quad ts,tc,freq
QueryPerformanceFrequency freq
QueryPerformanceCounter ts
'COMPILE/EXECUTE
'===============
o2_basic src
if o2_errno then
print o2_error
else
QueryPerformanceCounter tc
print "Compile time: " str((tc-ts)*1000/freq, 1) " MilliSeconds"
o2_exec 'Run the program
end if
|
http://rosettacode.org/wiki/Conditional_structures | Conditional structures | Control Structures
These are examples of control structures. You may also be interested in:
Conditional structures
Exceptions
Flow-control structures
Loops
Task
List the conditional structures offered by a programming language. See Wikipedia: conditionals for descriptions.
Common conditional structures include if-then-else and switch.
Less common are arithmetic if, ternary operator and Hash-based conditionals.
Arithmetic if allows tight control over computed gotos, which optimizers have a hard time to figure out.
| #6502_Assembly | 6502 Assembly | LDA #10
CMP #11 |
http://rosettacode.org/wiki/Conway%27s_Game_of_Life | Conway's Game of Life | The Game of Life is a cellular automaton devised by the British mathematician John Horton Conway in 1970. It is the best-known example of a cellular automaton.
Conway's game of life is described here:
A cell C is represented by a 1 when alive, or 0 when dead, in an m-by-m (or m×m) square array of cells.
We calculate N - the sum of live cells in C's eight-location neighbourhood, then cell C is alive or dead in the next generation based on the following table:
C N new C
1 0,1 -> 0 # Lonely
1 4,5,6,7,8 -> 0 # Overcrowded
1 2,3 -> 1 # Lives
0 3 -> 1 # It takes three to give birth!
0 0,1,2,4,5,6,7,8 -> 0 # Barren
Assume cells beyond the boundary are always dead.
The "game" is actually a zero-player game, meaning that its evolution is determined by its initial state, needing no input from human players. One interacts with the Game of Life by creating an initial configuration and observing how it evolves.
Task
Although you should test your implementation on more complex examples such as the glider in a larger universe, show the action of the blinker (three adjoining cells in a row all alive), over three generations, in a 3 by 3 grid.
References
Its creator John Conway, explains the game of life. Video from numberphile on youtube.
John Conway Inventing Game of Life - Numberphile video.
Related task
Langton's ant - another well known cellular automaton.
| #ACL2 | ACL2 | (defun print-row (row)
(if (endp row)
nil
(prog2$ (if (first row)
(cw "[]")
(cw " "))
(print-row (rest row)))))
(defun print-grid-r (grid)
(if (endp grid)
nil
(progn$ (cw "|")
(print-row (first grid))
(cw "|~%")
(print-grid-r (rest grid)))))
(defun print-line (l)
(if (zp l)
nil
(prog2$ (cw "-")
(print-line (1- l)))))
(defun print-grid (grid)
(progn$ (cw "+")
(print-line (* 2 (len (first grid))))
(cw "+~%")
(print-grid-r grid)
(cw "+")
(print-line (* 2 (len (first grid))))
(cw "+~%")))
(defun neighbors-row-r (row)
(if (endp (rest (rest row)))
(list (if (first row) 1 0))
(cons (+ (if (first row) 1 0)
(if (third row) 1 0))
(neighbors-row-r (rest row)))))
(defun neighbors-row (row)
(cons (if (second row) 1 0)
(neighbors-row-r row)))
(defun zip+ (xs ys)
(if (or (endp xs) (endp ys))
(append xs ys)
(cons (+ (first xs) (first ys))
(zip+ (rest xs) (rest ys)))))
(defun counts-row (row)
(if (endp row)
nil
(cons (if (first row) 1 0)
(counts-row (rest row)))))
(defun neighbors-r (grid prev-counts curr-counts next-counts
prev-neighbors curr-neighbors
next-neighbors)
(if (endp (rest grid))
(list (zip+ (zip+ prev-counts
prev-neighbors)
(neighbors-row (first grid))))
(cons (zip+ (zip+ (zip+ prev-counts next-counts)
(zip+ prev-neighbors next-neighbors))
curr-neighbors)
(neighbors-r (rest grid)
curr-counts
next-counts
(counts-row (third grid))
curr-neighbors
next-neighbors
(neighbors-row (third grid))))))
(defun neighbors (grid)
(neighbors-r grid
nil
(counts-row (first grid))
(counts-row (second grid))
nil
(neighbors-row (first grid))
(neighbors-row (second grid))))
(defun life-rules-row (life neighbors)
(if (or (endp life) (endp neighbors))
nil
(cons (or (and (first life)
(or (= (first neighbors) 2)
(= (first neighbors) 3)))
(and (not (first life))
(= (first neighbors) 3)))
(life-rules-row (rest life) (rest neighbors)))))
(defun life-rules-r (grid neighbors)
(if (or (endp grid) (endp neighbors))
nil
(cons (life-rules-row (first grid) (first neighbors))
(life-rules-r (rest grid) (rest neighbors)))))
(defun conway-step (grid)
(life-rules-r grid (neighbors grid)))
(defun conway (grid steps)
(if (zp steps)
nil
(progn$ (print-grid grid)
(conway (conway-step grid) (1- steps))))) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.