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/Reverse_a_string
Reverse a string
Task Take a string and reverse it. For example, "asdf" becomes "fdsa". Extra credit Preserve Unicode combining characters. For example, "as⃝df̅" becomes "f̅ds⃝a", not "̅fd⃝sa". 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
#Oz
Oz
{System.showInfo {Reverse "!dlroW olleH"}}
http://rosettacode.org/wiki/Random_number_generator_(device)
Random number generator (device)
Task If your system has a means to generate random numbers involving not only a software algorithm   (like the /dev/urandom devices in Unix),   then: show how to obtain a random 32-bit number from that mechanism. Related task Random_number_generator_(included)
#Pascal
Pascal
program RandomNumberDevice; var byteFile: file of byte; randomByte: byte; begin assign(byteFile, '/dev/urandom'); reset (byteFile); read (byteFile, randomByte); close (byteFile); writeln('The random byte is: ', randomByte); end.  
http://rosettacode.org/wiki/Random_number_generator_(device)
Random number generator (device)
Task If your system has a means to generate random numbers involving not only a software algorithm   (like the /dev/urandom devices in Unix),   then: show how to obtain a random 32-bit number from that mechanism. Related task Random_number_generator_(included)
#Perl
Perl
use Crypt::Random::Seed; my $source = Crypt::Random::Seed->new( NonBlocking => 1 ); # Allow non-blocking sources like /dev/urandom print "$_\n" for $source->random_values(10); # A method returning an array of 32-bit values
http://rosettacode.org/wiki/Random_number_generator_(device)
Random number generator (device)
Task If your system has a means to generate random numbers involving not only a software algorithm   (like the /dev/urandom devices in Unix),   then: show how to obtain a random 32-bit number from that mechanism. Related task Random_number_generator_(included)
#Phix
Phix
integer res -- 1=failure, 0=success atom rint = 0 -- random 32-bit int #ilASM{ mov eax,1 cpuid bt ecx,30 mov edi,1 -- exit code: failure jnc :exit -- rdrand sets CF=0 if no random number -- was available. Intel documentation -- recommends 10 retries in a tight loop mov ecx,11  ::loop1 sub ecx, 1 jz :exit -- exit code is set already rdrand eax -- (the above generates exception #C000001D if not supported) -- rdtsc jnc :loop1 lea edi,[rint] call :%pStoreMint xor edi,edi  ::exit mov [res],edi xor ebx,ebx -- important! } ?{res,rint} if res=0 then -- (success) -- -- To convert a signed 32-bit int to an unsigned one: -- -- method 1 -- atom urint1 = rint -- if urint1<0 then urint1+=#100000000 end if atom urint1 = rint+iff(rint<0?#100000000:0) -- method 2 atom pMem = allocate(4) poke4(pMem,rint) atom urint2 = peek4u(pMem) free(pMem) -- method 3 atom urint3 = bytes_to_int(int_to_bytes(rint,4),signed:=false) ?{urint1,urint2,urint3} end if
http://rosettacode.org/wiki/Random_Latin_squares
Random Latin squares
A Latin square of size n is an arrangement of n symbols in an n-by-n square in such a way that each row and column has each symbol appearing exactly once. A randomised Latin square generates random configurations of the symbols for any given n. Example n=4 randomised Latin square 0 2 3 1 2 1 0 3 3 0 1 2 1 3 2 0 Task Create a function/routine/procedure/method/... that given n generates a randomised Latin square of size n. Use the function to generate and show here, two randomly generated squares of size 5. Note Strict Uniformity in the random generation is a hard problem and not a requirement of the task. Reference Wikipedia: Latin square OEIS: A002860
#Julia
Julia
using Random   shufflerows(mat) = mat[shuffle(1:end), :] shufflecols(mat) = mat[:, shuffle(1:end)]   function addatdiagonal(mat) n = size(mat)[1] + 1 newmat = similar(mat, size(mat) .+ 1) for j in 1:n, i in 1:n newmat[i, j] = (i == n && j < n) ? mat[1, j] : (i == j) ? n - 1 : (i < j) ? mat[i, j - 1] : mat[i, j] end newmat end   function makelatinsquare(N) mat = [0 1; 1 0] for i in 3:N mat = addatdiagonal(mat) end shufflecols(shufflerows(mat)) end   function printlatinsquare(N) mat = makelatinsquare(N) for i in 1:N, j in 1:N print(rpad(mat[i, j], 3), j == N ? "\n" : "") end end   printlatinsquare(5), println("\n"), printlatinsquare(5)  
http://rosettacode.org/wiki/Random_Latin_squares
Random Latin squares
A Latin square of size n is an arrangement of n symbols in an n-by-n square in such a way that each row and column has each symbol appearing exactly once. A randomised Latin square generates random configurations of the symbols for any given n. Example n=4 randomised Latin square 0 2 3 1 2 1 0 3 3 0 1 2 1 3 2 0 Task Create a function/routine/procedure/method/... that given n generates a randomised Latin square of size n. Use the function to generate and show here, two randomly generated squares of size 5. Note Strict Uniformity in the random generation is a hard problem and not a requirement of the task. Reference Wikipedia: Latin square OEIS: A002860
#Kotlin
Kotlin
typealias matrix = MutableList<MutableList<Int>>   fun printSquare(latin: matrix) { for (row in latin) { println(row) } println() }   fun latinSquare(n: Int) { if (n <= 0) { println("[]") return }   val latin = MutableList(n) { MutableList(n) { it } } // first row latin[0].shuffle()   // middle row(s) for (i in 1 until n - 1) { var shuffled = false shuffling@ while (!shuffled) { latin[i].shuffle() for (k in 0 until i) { for (j in 0 until n) { if (latin[k][j] == latin[i][j]) { continue@shuffling } } } shuffled = true } }   // last row for (j in 0 until n) { val used = MutableList(n) { false } for (i in 0 until n - 1) { used[latin[i][j]] = true } for (k in 0 until n) { if (!used[k]) { latin[n - 1][j] = k break } } }   printSquare(latin) }   fun main() { latinSquare(5) latinSquare(5) latinSquare(10) // for good measure }
http://rosettacode.org/wiki/Ray-casting_algorithm
Ray-casting algorithm
This page uses content from Wikipedia. The original article was at Point_in_polygon. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Given a point and a polygon, check if the point is inside or outside the polygon using the ray-casting algorithm. A pseudocode can be simply: count ← 0 foreach side in polygon: if ray_intersects_segment(P,side) then count ← count + 1 if is_odd(count) then return inside else return outside Where the function ray_intersects_segment return true if the horizontal ray starting from the point P intersects the side (segment), false otherwise. An intuitive explanation of why it works is that every time we cross a border, we change "country" (inside-outside, or outside-inside), but the last "country" we land on is surely outside (since the inside of the polygon is finite, while the ray continues towards infinity). So, if we crossed an odd number of borders we were surely inside, otherwise we were outside; we can follow the ray backward to see it better: starting from outside, only an odd number of crossing can give an inside: outside-inside, outside-inside-outside-inside, and so on (the - represents the crossing of a border). So the main part of the algorithm is how we determine if a ray intersects a segment. The following text explain one of the possible ways. Looking at the image on the right, we can easily be convinced of the fact that rays starting from points in the hatched area (like P1 and P2) surely do not intersect the segment AB. We also can easily see that rays starting from points in the greenish area surely intersect the segment AB (like point P3). So the problematic points are those inside the white area (the box delimited by the points A and B), like P4. Let us take into account a segment AB (the point A having y coordinate always smaller than B's y coordinate, i.e. point A is always below point B) and a point P. Let us use the cumbersome notation PAX to denote the angle between segment AP and AX, where X is always a point on the horizontal line passing by A with x coordinate bigger than the maximum between the x coordinate of A and the x coordinate of B. As explained graphically by the figures on the right, if PAX is greater than the angle BAX, then the ray starting from P intersects the segment AB. (In the images, the ray starting from PA does not intersect the segment, while the ray starting from PB in the second picture, intersects the segment). Points on the boundary or "on" a vertex are someway special and through this approach we do not obtain coherent results. They could be treated apart, but it is not necessary to do so. An algorithm for the previous speech could be (if P is a point, Px is its x coordinate): ray_intersects_segment: P : the point from which the ray starts A : the end-point of the segment with the smallest y coordinate (A must be "below" B) B : the end-point of the segment with the greatest y coordinate (B must be "above" A) if Py = Ay or Py = By then Py ← Py + ε end if if Py < Ay or Py > By then return false else if Px >= max(Ax, Bx) then return false else if Px < min(Ax, Bx) then return true else if Ax ≠ Bx then m_red ← (By - Ay)/(Bx - Ax) else m_red ← ∞ end if if Ax ≠ Px then m_blue ← (Py - Ay)/(Px - Ax) else m_blue ← ∞ end if if m_blue ≥ m_red then return true else return false end if end if end if (To avoid the "ray on vertex" problem, the point is moved upward of a small quantity   ε.)
#R
R
point_in_polygon <- function(polygon, p) { count <- 0 for(side in polygon) { if ( ray_intersect_segment(p, side) ) { count <- count + 1 } } if ( count %% 2 == 1 ) "INSIDE" else "OUTSIDE" }   ray_intersect_segment <- function(p, side) { eps <- 0.0001 a <- side$A b <- side$B if ( a$y > b$y ) { a <- side$B b <- side$A } if ( (p$y == a$y) || (p$y == b$y) ) { p$y <- p$y + eps } if ( (p$y < a$y) || (p$y > b$y) ) return(FALSE) else if ( p$x > max(a$x, b$x) ) return(FALSE) else { if ( p$x < min(a$x, b$x) ) return(TRUE) else { if ( a$x != b$x ) m_red <- (b$y - a$y) / (b$x - a$x) else m_red <- Inf if ( a$x != p$x ) m_blue <- (p$y - a$y) / (p$x - a$x) else m_blue <- Inf return( m_blue >= m_red ) } } }
http://rosettacode.org/wiki/Queue/Definition
Queue/Definition
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. Illustration of FIFO behavior Task Implement a FIFO queue. Elements are added at one side and popped from the other in the order of insertion. Operations:   push   (aka enqueue)    - add element   pop     (aka dequeue)    - pop first element   empty                             - return truth value when empty Errors:   handle the error of trying to pop from an empty queue (behavior depends on the language and platform) See   Queue/Usage   for the built-in FIFO or queue of your language or standard library. See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal Stack
#Action.21
Action!
DEFINE MAXSIZE="200" BYTE ARRAY queue(MAXSIZE) BYTE queueFront=[0],queueRear=[0]   BYTE FUNC IsEmpty() IF queueFront=queueRear THEN RETURN (1) FI RETURN (0)   PROC Push(BYTE v) BYTE rear   rear=queueRear+1 IF rear=MAXSIZE THEN rear=0 FI IF rear=queueFront THEN PrintE("Error: queue is full!") Break() FI queue(queueRear)=v queueRear=rear RETURN   BYTE FUNC Pop() BYTE v   IF IsEmpty() THEN PrintE("Error: queue is empty!") Break() FI v=queue(queueFront) queueFront==+1 IF queueFront=MAXSIZE THEN queueFront=0 FI RETURN (v)   PROC TestIsEmpty() IF IsEmpty() THEN PrintE("Queue is empty") ELSE PrintE("Queue is not empty") FI RETURN   PROC TestPush(BYTE v) PrintF("Push: %B%E",v) Push(v) RETURN   PROC TestPop() BYTE v   Print("Pop: ") v=Pop() PrintBE(v) RETURN   PROC Main() TestIsEmpty() TestPush(10) TestIsEmpty() TestPush(31) TestPop() TestIsEmpty() TestPush(5) TestPop() TestPop() TestPop() RETURN
http://rosettacode.org/wiki/Quaternion_type
Quaternion type
Quaternions   are an extension of the idea of   complex numbers. A complex number has a real and complex part,   sometimes written as   a + bi, where   a   and   b   stand for real numbers, and   i   stands for the square root of minus 1. An example of a complex number might be   -3 + 2i,   where the real part,   a   is   -3.0   and the complex part,   b   is   +2.0. A quaternion has one real part and three imaginary parts,   i,   j,   and   k. A quaternion might be written as   a + bi + cj + dk. In the quaternion numbering system:   i∙i = j∙j = k∙k = i∙j∙k = -1,       or more simply,   ii  = jj  = kk  = ijk   = -1. The order of multiplication is important, as, in general, for two quaternions:   q1   and   q2:     q1q2 ≠ q2q1. An example of a quaternion might be   1 +2i +3j +4k There is a list form of notation where just the numbers are shown and the imaginary multipliers   i,   j,   and   k   are assumed by position. So the example above would be written as   (1, 2, 3, 4) Task Given the three quaternions and their components: q = (1, 2, 3, 4) = (a, b, c, d) q1 = (2, 3, 4, 5) = (a1, b1, c1, d1) q2 = (3, 4, 5, 6) = (a2, b2, c2, d2) And a wholly real number   r = 7. Create functions   (or classes)   to perform simple maths with quaternions including computing: The norm of a quaternion: = a 2 + b 2 + c 2 + d 2 {\displaystyle ={\sqrt {a^{2}+b^{2}+c^{2}+d^{2}}}} The negative of a quaternion: = (-a, -b, -c, -d) The conjugate of a quaternion: = ( a, -b, -c, -d) Addition of a real number   r   and a quaternion   q: r + q = q + r = (a+r, b, c, d) Addition of two quaternions: q1 + q2 = (a1+a2, b1+b2, c1+c2, d1+d2) Multiplication of a real number and a quaternion: qr = rq = (ar, br, cr, dr) Multiplication of two quaternions   q1   and   q2   is given by: ( a1a2 − b1b2 − c1c2 − d1d2,   a1b2 + b1a2 + c1d2 − d1c2,   a1c2 − b1d2 + c1a2 + d1b2,   a1d2 + b1c2 − c1b2 + d1a2 ) Show that, for the two quaternions   q1   and   q2: q1q2 ≠ q2q1 If a language has built-in support for quaternions, then use it. C.f.   Vector products   On Quaternions;   or on a new System of Imaginaries in Algebra.   By Sir William Rowan Hamilton LL.D, P.R.I.A., F.R.A.S., Hon. M. R. Soc. Ed. and Dub., Hon. or Corr. M. of the Royal or Imperial Academies of St. Petersburgh, Berlin, Turin and Paris, Member of the American Academy of Arts and Sciences, and of other Scientific Societies at Home and Abroad, Andrews' Prof. of Astronomy in the University of Dublin, and Royal Astronomer of Ireland.
#Action.21
Action!
INCLUDE "H6:REALMATH.ACT"   DEFINE A_="+0" DEFINE B_="+6" DEFINE C_="+12" DEFINE D_="+18"   TYPE Quaternion=[CARD a1,a2,a3,b1,b2,b3,c1,c2,c3,d1,d2,d3] REAL neg   PROC Init() ValR("-1",neg) RETURN   BYTE FUNC Positive(REAL POINTER x) BYTE ARRAY tmp   tmp=x IF (tmp(0)&$80)=$00 THEN RETURN (1) FI RETURN (0)   PROC PrintQuat(Quaternion POINTER q) PrintR(q A_) IF Positive(q B_) THEN Put('+) FI PrintR(q B_) Put('i) IF Positive(q C_) THEN Put('+) FI PrintR(q C_) Put('j) IF Positive(q D_) THEN Put('+) FI PrintR(q D_) Put('k) RETURN   PROC PrintQuatE(Quaternion POINTER q) PrintQuat(q) PutE() RETURN   PROC QuatIntInit(Quaternion POINTER q INT ia,ib,ic,id) IntToReal(ia,q A_) IntToReal(ib,q B_) IntToReal(ic,q C_) IntToReal(id,q D_) RETURN   PROC Sqr(REAL POINTER a,b) RealMult(a,a,b) RETURN   PROC QuatNorm(Quaternion POINTER q REAL POINTER res) REAL r1,r2,r3   Sqr(q A_,r1)  ;r1=q.a^2 Sqr(q B_,r2)  ;r2=q.b^2 RealAdd(r1,r2,r3) ;r3=q.a^2+q.b^2 Sqr(q C_,r1)  ;r1=q.c^2 RealAdd(r3,r1,r2) ;r2=q.a^2+q.b^2+q.c^2 Sqr(q D_,r1)  ;r1=q.d^2 RealAdd(r2,r1,r3) ;r3=q.a^2+q.b^2+q.c^2+q.d^2 Sqrt(r3,res)  ;res=sqrt(q.a^2+q.b^2+q.c^2+q.d^2) RETURN   PROC QuatNegative(Quaternion POINTER q,res) RealMult(q A_,neg,res A_) ;res.a=-q.a RealMult(q B_,neg,res B_) ;res.b=-q.b RealMult(q C_,neg,res C_) ;res.c=-q.c RealMult(q D_,neg,res D_) ;res.d=-q.d RETURN   PROC QuatConjugate(Quaternion POINTER q,res) RealAssign(q A_,res A_)  ;res.a=q.a RealMult(q B_,neg,res B_) ;res.b=-q.b RealMult(q C_,neg,res C_) ;res.c=-q.c RealMult(q D_,neg,res D_) ;res.d=-q.d RETURN   PROC QuatAddReal(Quaternion POINTER q REAL POINTER r Quaternion POINTER res) RealAdd(q A_,r,res A_)  ;res.a=q.a+r RealAssign(q B_,res B_) ;res.b=q.b RealAssign(q C_,res C_) ;res.c=q.c RealAssign(q D_,res D_) ;res.d=q.d RETURN   PROC QuatAdd(Quaternion POINTER q1,q2,res) RealAdd(q1 A_,q2 A_,res A_) ;res.a=q1.a+q2.a RealAdd(q1 B_,q2 B_,res B_) ;res.b=q1.b+q2.b RealAdd(q1 C_,q2 C_,res C_) ;res.c=q1.c+q2.c RealAdd(q1 D_,q2 D_,res D_) ;res.d=q1.d+q2.d RETURN   PROC QuatMultReal(Quaternion POINTER q REAL POINTER r Quaternion POINTER res) RealMult(q A_,r,res A_) ;res.a=q.a*r RealMult(q B_,r,res B_) ;res.b=q.b*r RealMult(q C_,r,res C_) ;res.c=q.c*r RealMult(q D_,r,res D_) ;res.d=q.d*r RETURN   PROC QuatMult(Quaternion POINTER q1,q2,res) REAL r1,r2   RealMult(q1 A_,q2 A_,r1) ;r1=q1.a*q2.a RealMult(q1 B_,q2 B_,r2) ;r2=q1.b*q2.b RealSub(r1,r2,r3)  ;r3=q1.a*q2.a-q1.b*q2.b RealMult(q1 C_,q2 C_,r1) ;r1=q1.c*q2.c RealSub(r3,r1,r2)  ;r2=q1.a*q2.a-q1.b*q2.b-q1.c*q2.c RealMult(q1 D_,q2 D_,r1) ;r1=q1.d*q2.d RealSub(r2,r1,res A_)  ;res.a=q1.a*q2.a-q1.b*q2.b-q1.c*q2.c-q1.d*q2.d   RealMult(q1 A_,q2 B_,r1) ;r1=q1.a*q2.b RealMult(q1 B_,q2 A_,r2) ;r2=q1.b*q2.a RealAdd(r1,r2,r3)  ;r3=q1.a*q2.b+q1.b*q2.a RealMult(q1 C_,q2 D_,r1) ;r1=q1.c*q2.d RealAdd(r3,r1,r2)  ;r2=q1.a*q2.b+q1.b*q2.a+q1.c*q2.d RealMult(q1 D_,q2 C_,r1) ;r1=q1.d*q2.c RealSub(r2,r1,res B_)  ;res.b=q1.a*q2.b+q1.b*q2.a+q1.c*q2.d-q1.d*q2.c   RealMult(q1 A_,q2 C_,r1) ;r1=q1.a*q2.c RealMult(q1 B_,q2 D_,r2) ;r2=q1.b*q2.d RealSub(r1,r2,r3)  ;r3=q1.a*q2.c-q1.b*q2.d RealMult(q1 C_,q2 A_,r1) ;r1=q1.c*q2.a RealAdd(r3,r1,r2)  ;r2=q1.a*q2.c-q1.b*q2.d+q1.c*q2.a RealMult(q1 D_,q2 B_,r1) ;r1=q1.d*q2.b RealAdd(r2,r1,res C_)  ;res.c=q1.a*q2.c-q1.b*q2.d+q1.c*q2.a+q1.d*q2.b   RealMult(q1 A_,q2 D_,r1) ;r1=q1.a*q2.d RealMult(q1 B_,q2 C_,r2) ;r2=q1.b*q2.c RealAdd(r1,r2,r3)  ;r3=q1.a*q2.d+q1.b*q2.c RealMult(q1 C_,q2 B_,r1) ;r1=q1.c*q2.b RealSub(r3,r1,r2)  ;r2=q1.a*q2.d+q1.b*q2.c-q1.c*q2.b RealMult(q1 D_,q2 A_,r1) ;r1=q1.d*q2.a RealAdd(r2,r1,res D_)  ;res.d=q1.a*q2.d+q1.b*q2.c-q1.c*q2.b+q1.d*q2.a RETURN   PROC Main() Quaternion q,q1,q2,q3 REAL r,r2   Put(125) PutE() ;clear the screen MathInit() Init()   QuatIntInit(q,1,2,3,4) QuatIntInit(q1,2,3,4,5) QuatIntInit(q2,3,4,5,6) IntToReal(7,r)   Print(" q = ") PrintQuatE(q) Print("q1 = ") PrintQuatE(q1) Print("q2 = ") PrintQuatE(q2) Print(" r = ") PrintRE(r) PutE()   QuatNorm(q,r2) Print(" Norm(q) = ") PrintRE(r2) QuatNorm(q1,r2) Print("Norm(q1) = ") PrintRE(r2) QuatNorm(q2,r2) Print("Norm(q2) = ") PrintRE(r2) QuatNegative(q,q3) Print(" -q = ") PrintQuatE(q3) QuatConjugate(q,q3) Print(" Conj(q) = ") PrintQuatE(q3) QuatAddReal(q,r,q3) Print(" q+r = ") PrintQuatE(q3) QuatAdd(q1,q2,q3) Print(" q1+q2 = ") PrintQuatE(q3) QuatAdd(q2,q1,q3) Print(" q2+q1 = ") PrintQuatE(q3) QuatMultReal(q,r,q3) Print(" q*r = ") PrintQuatE(q3) QuatMult(q1,q2,q3) Print(" q1*q2 = ") PrintQuatE(q3) QuatMult(q2,q1,q3) Print(" q2*q1 = ") PrintQuatE(q3) RETURN
http://rosettacode.org/wiki/Quine
Quine
A quine is a self-referential program that can, without any external access, output its own source. A   quine   (named after Willard Van Orman Quine)   is also known as:   self-reproducing automata   (1972)   self-replicating program         or   self-replicating computer program   self-reproducing program      or   self-reproducing computer program   self-copying program             or   self-copying computer program It is named after the philosopher and logician who studied self-reference and quoting in natural language, as for example in the paradox "'Yields falsehood when preceded by its quotation' yields falsehood when preceded by its quotation." "Source" has one of two meanings. It can refer to the text-based program source. For languages in which program source is represented as a data structure, "source" may refer to the data structure: quines in these languages fall into two categories: programs which print a textual representation of themselves, or expressions which evaluate to a data structure which is equivalent to that expression. The usual way to code a quine works similarly to this paradox: The program consists of two identical parts, once as plain code and once quoted in some way (for example, as a character string, or a literal data structure). The plain code then accesses the quoted code and prints it out twice, once unquoted and once with the proper quotation marks added. Often, the plain code and the quoted code have to be nested. Task Write a program that outputs its own source code in this way. If the language allows it, you may add a variant that accesses the code directly. You are not allowed to read any external files with the source code. The program should also contain some sort of self-reference, so constant expressions which return their own value which some top-level interpreter will print out. Empty programs producing no output are not allowed. There are several difficulties that one runs into when writing a quine, mostly dealing with quoting: Part of the code usually needs to be stored as a string or structural literal in the language, which needs to be quoted somehow. However, including quotation marks in the string literal itself would be troublesome because it requires them to be escaped, which then necessitates the escaping character (e.g. a backslash) in the string, which itself usually needs to be escaped, and so on. Some languages have a function for getting the "source code representation" of a string (i.e. adds quotation marks, etc.); in these languages, this can be used to circumvent the quoting problem. Another solution is to construct the quote character from its character code, without having to write the quote character itself. Then the character is inserted into the string at the appropriate places. The ASCII code for double-quote is 34, and for single-quote is 39. Newlines in the program may have to be reproduced as newlines in the string, which usually requires some kind of escape sequence (e.g. "\n"). This causes the same problem as above, where the escaping character needs to itself be escaped, etc. If the language has a way of getting the "source code representation", it usually handles the escaping of characters, so this is not a problem. Some languages allow you to have a string literal that spans multiple lines, which embeds the newlines into the string without escaping. Write the entire program on one line, for free-form languages (as you can see for some of the solutions here, they run off the edge of the screen), thus removing the need for newlines. However, this may be unacceptable as some languages require a newline at the end of the file; and otherwise it is still generally good style to have a newline at the end of a file. (The task is not clear on whether a newline is required at the end of the file.) Some languages have a print statement that appends a newline; which solves the newline-at-the-end issue; but others do not. Next to the Quines presented here, many other versions can be found on the Quine page. Related task   print itself.
#ALGOL_68
ALGOL 68
STRINGa="STRINGa=,q=REPR34;print(a[:8]+q+a+q+a[9:])",q=REPR34;print(a[:8]+q+a+q+a[9:])
http://rosettacode.org/wiki/Queue/Usage
Queue/Usage
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. Illustration of FIFO behavior Task Create a queue data structure and demonstrate its operations. (For implementations of queues, see the FIFO task.) Operations:   push       (aka enqueue) - add element   pop         (aka dequeue) - pop first element   empty     - return truth value when empty See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal Stack
#BBC_BASIC
BBC BASIC
FIFOSIZE = 1000   FOR n = 3 TO 5 PRINT "Push ";n : PROCenqueue(n) NEXT PRINT "Pop " ; FNdequeue PRINT "Push 6" : PROCenqueue(6) REPEAT PRINT "Pop " ; FNdequeue UNTIL FNisempty PRINT "Pop " ; FNdequeue END   DEF PROCenqueue(n) : LOCAL f% DEF FNdequeue : LOCAL f% : f% = 1 DEF FNisempty : LOCAL f% : f% = 2 PRIVATE fifo(), rptr%, wptr% DIM fifo(FIFOSIZE-1) CASE f% OF WHEN 0: wptr% = (wptr% + 1) MOD FIFOSIZE IF rptr% = wptr% ERROR 100, "Error: queue overflowed" fifo(wptr%) = n WHEN 1: IF rptr% = wptr% ERROR 101, "Error: queue empty" rptr% = (rptr% + 1) MOD FIFOSIZE = fifo(rptr%) WHEN 2: = (rptr% = wptr%) ENDCASE ENDPROC
http://rosettacode.org/wiki/Queue/Usage
Queue/Usage
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. Illustration of FIFO behavior Task Create a queue data structure and demonstrate its operations. (For implementations of queues, see the FIFO task.) Operations:   push       (aka enqueue) - add element   pop         (aka dequeue) - pop first element   empty     - return truth value when empty See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal Stack
#Bracmat
Bracmat
( queue = (list=) (enqueue=.(.!arg) !(its.list):?(its.list)) ( dequeue = x .  !(its.list):?(its.list) (.?x) & !x ) (empty=.!(its.list):) ) & new$queue:?Q & ( (Q..enqueue)$1 & (Q..enqueue)$2 & (Q..enqueue)$3 & out$((Q..dequeue)$) & (Q..enqueue)$4 & out$((Q..dequeue)$) & out$((Q..dequeue)$) & out $ ( The queue is ((Q..empty)$&|not) empty ) & out$((Q..dequeue)$) & out $ ( The queue is ((Q..empty)$&|not) empty ) & out$((Q..dequeue)$) & out$Success! | out$"Attempt to dequeue failed" ) ;
http://rosettacode.org/wiki/Read_a_specific_line_from_a_file
Read a specific line from a file
Some languages have special semantics for obtaining a known line number from a file. Task Demonstrate how to obtain the contents of a specific line within a file. For the purpose of this task demonstrate how the contents of the seventh line of a file can be obtained,   and store it in a variable or in memory   (for potential future use within the program if the code were to become embedded). If the file does not contain seven lines,   or the seventh line is empty,   or too big to be retrieved,   output an appropriate message. If no special semantics are available for obtaining the required line,   it is permissible to read line by line. Note that empty lines are considered and should still be counted. Also note that for functional languages or languages without variables or storage,   it is permissible to output the extracted data to standard output.
#REXX
REXX
/*REXX program reads a specific line from a file (and displays the length and content).*/ parse arg FID n . /*obtain optional arguments from the CL*/ if FID=='' | FID=="," then FID= 'JUNK.TXT' /*not specified? Then use the default.*/ if n=='' | n=="," then n=7 /* " " " " " " */   if lines(FID)==0 then call ser "wasn't found." /*see if the file exists (or not). */   call linein FID, n-1 /*read the record previous to N. */ if lines(FID)==0 then call ser "doesn't contain" N 'lines.' /* [↑] any more lines to read in file?*/   $=linein(FID) /*read the Nth record in the file. */   say 'File ' FID " line " N ' has a length of: ' length($) say 'File ' FID " line " N 'contents: ' $ /*display the contents of the Nth line.*/ exit /*stick a fork in it, we're all done. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ ser: say; say '***error!*** File ' FID " " arg(1); say; exit 13
http://rosettacode.org/wiki/Quickselect_algorithm
Quickselect algorithm
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort Use the quickselect algorithm on the vector [9, 8, 7, 6, 5, 0, 1, 2, 3, 4] To show the first, second, third, ... up to the tenth largest member of the vector, in order, here on this page. Note: Quicksort has a separate task.
#C.23
C#
// ---------------------------------------------------------------------------------------------- // // Program.cs - QuickSelect // // ----------------------------------------------------------------------------------------------   using System; using System.Collections.Generic; using System.Linq;   namespace QuickSelect { internal static class Program { #region Static Members   private static void Main() { var inputArray = new[] {9, 8, 7, 6, 5, 0, 1, 2, 3, 4}; // Loop 10 times Console.WriteLine( "Loop quick select 10 times." ); for( var i = 0 ; i < 10 ; i++ ) { Console.Write( inputArray.NthSmallestElement( i ) ); if( i < 9 ) Console.Write( ", " ); } Console.WriteLine();   // And here is then more effective way to get N smallest elements from vector in order by using quick select algorithm // Basically we are here just sorting array (taking 10 smallest from array which length is 10) Console.WriteLine( "Just sort 10 elements." ); Console.WriteLine( string.Join( ", ", inputArray.TakeSmallest( 10 ).OrderBy( v => v ).Select( v => v.ToString() ).ToArray() ) ); // Here we are actually doing quick select once by taking only 4 smallest from array. Console.WriteLine( "Get 4 smallest and sort them." ); Console.WriteLine( string.Join( ", ", inputArray.TakeSmallest( 4 ).OrderBy( v => v ).Select( v => v.ToString() ).ToArray() ) ); Console.WriteLine( "< Press any key >" ); Console.ReadKey(); }   #endregion }   internal static class ArrayExtension { #region Static Members   /// <summary> /// Return specified number of smallest elements from array. /// </summary> /// <typeparam name="T">The type of the elements of array. Type must implement IComparable(T) interface.</typeparam> /// <param name="array">The array to return elemnts from.</param> /// <param name="count">The number of smallest elements to return. </param> /// <returns>An IEnumerable(T) that contains the specified number of smallest elements of the input array. Returned elements are NOT sorted.</returns> public static IEnumerable<T> TakeSmallest<T>( this T[] array, int count ) where T : IComparable<T> { if( count < 0 ) throw new ArgumentOutOfRangeException( "count", "Count is smaller than 0." ); if( count == 0 ) return new T[0]; if( array.Length <= count ) return array;   return QuickSelectSmallest( array, count - 1 ).Take( count ); }   /// <summary> /// Returns N:th smallest element from the array. /// </summary> /// <typeparam name="T">The type of the elements of array. Type must implement IComparable(T) interface.</typeparam> /// <param name="array">The array to return elemnt from.</param> /// <param name="n">Nth element. 0 is smallest element, when array.Length - 1 is largest element.</param> /// <returns>N:th smalles element from the array.</returns> public static T NthSmallestElement<T>( this T[] array, int n ) where T : IComparable<T> { if( n < 0 || n > array.Length - 1 ) throw new ArgumentOutOfRangeException( "n", n, string.Format( "n should be between 0 and {0} it was {1}.", array.Length - 1, n ) ); if( array.Length == 0 ) throw new ArgumentException( "Array is empty.", "array" ); if( array.Length == 1 ) return array[ 0 ];   return QuickSelectSmallest( array, n )[ n ]; }   /// <summary> /// Partially sort array such way that elements before index position n are smaller or equal than elemnt at position n. And elements after n are larger or equal. /// </summary> /// <typeparam name="T">The type of the elements of array. Type must implement IComparable(T) interface.</typeparam> /// <param name="input">The array which elements are being partially sorted. This array is not modified.</param> /// <param name="n">Nth smallest element.</param> /// <returns>Partially sorted array.</returns> private static T[] QuickSelectSmallest<T>( T[] input, int n ) where T : IComparable<T> { // Let's not mess up with our input array // For very large arrays - we should optimize this somehow - or just mess up with our input var partiallySortedArray = (T[]) input.Clone();   // Initially we are going to execute quick select to entire array var startIndex = 0; var endIndex = input.Length - 1;   // Selecting initial pivot // Maybe we are lucky and array is sorted initially? var pivotIndex = n;   // Loop until there is nothing to loop (this actually shouldn't happen - we should find our value before we run out of values) var r = new Random(); while( endIndex > startIndex ) { pivotIndex = QuickSelectPartition( partiallySortedArray, startIndex, endIndex, pivotIndex ); if( pivotIndex == n ) // We found our n:th smallest value - it is stored to pivot index break; if( pivotIndex > n ) // Array before our pivot index have more elements that we are looking for endIndex = pivotIndex - 1; else // Array before our pivot index has less elements that we are looking for startIndex = pivotIndex + 1;   // Omnipotent beings don't need to roll dices - but we do... // Randomly select a new pivot index between end and start indexes (there are other methods, this is just most brutal and simplest) pivotIndex = r.Next( startIndex, endIndex ); } return partiallySortedArray; }   /// <summary> /// Sort elements in sub array between startIndex and endIndex, such way that elements smaller than or equal with value initially stored to pivot index are before /// new returned pivot value index. /// </summary> /// <typeparam name="T">The type of the elements of array. Type must implement IComparable(T) interface.</typeparam> /// <param name="array">The array that is being sorted.</param> /// <param name="startIndex">Start index of sub array.</param> /// <param name="endIndex">End index of sub array.</param> /// <param name="pivotIndex">Pivot index.</param> /// <returns>New pivot index. Value that was initially stored to <paramref name="pivotIndex"/> is stored to this newly returned index. All elements before this index are /// either smaller or equal with pivot value. All elements after this index are larger than pivot value.</returns> /// <remarks>This method modifies paremater array.</remarks> private static int QuickSelectPartition<T>( this T[] array, int startIndex, int endIndex, int pivotIndex ) where T : IComparable<T> { var pivotValue = array[ pivotIndex ]; // Initially we just assume that value in pivot index is largest - so we move it to end (makes also for loop more straight forward) array.Swap( pivotIndex, endIndex ); for( var i = startIndex ; i < endIndex ; i++ ) { if( array[ i ].CompareTo( pivotValue ) > 0 ) continue;   // Value stored to i was smaller than or equal with pivot value - let's move it to start array.Swap( i, startIndex ); // Move start one index forward startIndex++; } // Start index is now pointing to index where we should store our pivot value from end of array array.Swap( endIndex, startIndex ); return startIndex; }   private static void Swap<T>( this T[] array, int index1, int index2 ) { if( index1 == index2 ) return;   var temp = array[ index1 ]; array[ index1 ] = array[ index2 ]; array[ index2 ] = temp; }   #endregion } }
http://rosettacode.org/wiki/Ramer-Douglas-Peucker_line_simplification
Ramer-Douglas-Peucker line simplification
Ramer-Douglas-Peucker line simplification You are encouraged to solve this task according to the task description, using any language you may know. The   Ramer–Douglas–Peucker   algorithm is a line simplification algorithm for reducing the number of points used to define its shape. Task Using the   Ramer–Douglas–Peucker   algorithm, simplify the   2D   line defined by the points: (0,0) (1,0.1) (2,-0.1) (3,5) (4,6) (5,7) (6,8.1) (7,9) (8,9) (9,9) The error threshold to be used is:   1.0. Display the remaining points here. Reference   the Wikipedia article:   Ramer-Douglas-Peucker algorithm.
#Nim
Nim
import math   type Point = tuple[x, y: float64]   proc pointLineDistance(pt, lineStart, lineEnd: Point): float64 = var n, d, dx, dy: float64 dx = lineEnd.x - lineStart.x dy = lineEnd.y - lineStart.y n = abs(dx * (lineStart.y - pt.y) - (lineStart.x - pt.x) * dy) d = sqrt(dx * dx + dy * dy) n / d   proc rdp(points: seq[Point], startIndex, lastIndex: int, ε: float64 = 1.0): seq[Point] = var dmax = 0.0 var index = startIndex   for i in index+1..<lastIndex: var d = pointLineDistance(points[i], points[startIndex], points[lastIndex]) if d > dmax: index = i dmax = d   if dmax > ε: var res1 = rdp(points, startIndex, index, ε) var res2 = rdp(points, index, lastIndex, ε)   var finalRes: seq[Point] = @[] finalRes.add(res1[0..^2]) finalRes.add(res2[0..^1])   result = finalRes else: result = @[points[startIndex], points[lastIndex]]   var line: seq[Point] = @[(0.0, 0.0), (1.0, 0.1), (2.0, -0.1), (3.0, 5.0), (4.0, 6.0), (5.0, 7.0), (6.0, 8.1), (7.0, 9.0), (8.0, 9.0), (9.0, 9.0)] echo rdp(line, line.low, line.high)
http://rosettacode.org/wiki/Range_extraction
Range extraction
A format for expressing an ordered list of integers is to use a comma separated list of either individual integers Or a range of integers denoted by the starting integer separated from the end integer in the range by a dash, '-'. (The range includes all integers in the interval including both endpoints) The range syntax is to be used only for, and for every range that expands to more than two values. Example The list of integers: -6, -3, -2, -1, 0, 1, 3, 4, 5, 7, 8, 9, 10, 11, 14, 15, 17, 18, 19, 20 Is accurately expressed by the range expression: -6,-3-1,3-5,7-11,14,15,17-20 (And vice-versa). Task Create a function that takes a list of integers in increasing order and returns a correctly formatted string in the range format. Use the function to compute and print the range formatted version of the following ordered list of integers. (The correct answer is: 0-2,4,6-8,11,12,14-25,27-33,35-39). 0, 1, 2, 4, 6, 7, 8, 11, 12, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 27, 28, 29, 30, 31, 32, 33, 35, 36, 37, 38, 39 Show the output of your program. Related task   Range expansion
#COBOL
COBOL
IDENTIFICATION DIVISION. PROGRAM-ID. extract-range-task.   DATA DIVISION. WORKING-STORAGE SECTION. 01 data-str PIC X(200) VALUE "0, 1, 2, 4, 6," & " 7, 8, 11, 12, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, " & "24, 25, 27, 28, 29, 30, 31, 32, 33, 35, 36, 37, 38, 39".   01 result PIC X(200).   PROCEDURE DIVISION. CALL "extract-range" USING CONTENT data-str, REFERENCE result DISPLAY FUNCTION TRIM(result)   GOBACK . END PROGRAM extract-range-task.     IDENTIFICATION DIVISION. PROGRAM-ID. extract-range.   DATA DIVISION. LOCAL-STORAGE SECTION. COPY "nums-table.cpy".   01 difference PIC 999.   01 rng-begin PIC S999. 01 rng-end PIC S999.   01 num-trailing PIC 999.   01 trailing-comma-pos PIC 999.   LINKAGE SECTION. 01 nums-str PIC X(200). 01 extracted-range PIC X(200).   01 extracted-range-len CONSTANT LENGTH extracted-range.   PROCEDURE DIVISION USING nums-str, extracted-range. CALL "split-nums" USING CONTENT nums-str, ", ", REFERENCE nums-table   *> Process the table MOVE nums (1) TO rng-begin PERFORM VARYING nums-idx FROM 2 BY 1 UNTIL num-nums < nums-idx SUBTRACT nums (nums-idx - 1) FROM nums (nums-idx) GIVING difference   *> If number is more than one away from the previous one *> end the range and start a new one. IF difference > 1 MOVE nums (nums-idx - 1) TO rng-end CALL "add-next-range" USING CONTENT rng-begin, rng-end, REFERENCE extracted-range MOVE nums (nums-idx) TO rng-begin END-IF END-PERFORM   *> Process the last number MOVE nums (num-nums) TO rng-end CALL "add-next-range" USING CONTENT rng-begin, rng-end, REFERENCE extracted-range   *> Remove trailing comma. CALL "find-num-trailing-spaces" USING CONTENT extracted-range, REFERENCE num-trailing COMPUTE trailing-comma-pos = extracted-range-len - num-trailing MOVE SPACE TO extracted-range (trailing-comma-pos:1)   GOBACK .   IDENTIFICATION DIVISION. PROGRAM-ID. split-nums INITIAL.   DATA DIVISION. WORKING-STORAGE SECTION. 01 num-len PIC 9. 01 next-num-pos PIC 999.   LINKAGE SECTION. 01 str PIC X(200). 01 delim PIC X ANY LENGTH.   COPY "nums-table.cpy".   PROCEDURE DIVISION USING str, delim, nums-table. INITIALIZE num-nums   PERFORM UNTIL str = SPACES INITIALIZE num-len INSPECT str TALLYING num-len FOR CHARACTERS BEFORE delim   ADD 1 TO num-nums   *> If there are no more instances of delim in the string, *> add the rest of the string to the last element of the *> table. IF num-len = 0 MOVE str TO nums (num-nums) EXIT PERFORM ELSE MOVE str (1:num-len) TO nums (num-nums) ADD 3 TO num-len GIVING next-num-pos MOVE str (next-num-pos:) TO str END-IF END-PERFORM . END PROGRAM split-nums.   IDENTIFICATION DIVISION. PROGRAM-ID. add-next-range INITIAL.   DATA DIVISION. WORKING-STORAGE SECTION. 01 num-trailing PIC 999. 01 start-pos PIC 999.   01 range-len PIC 999.   01 begin-edited PIC -ZZ9. 01 end-edited PIC -ZZ9.   LINKAGE SECTION. 01 rng-begin PIC S999. 01 rng-end PIC S999.   01 extracted-range PIC X(200).   01 extracted-range-len CONSTANT LENGTH extracted-range.   PROCEDURE DIVISION USING rng-begin, rng-end, extracted-range. CALL "find-num-trailing-spaces" USING CONTENT extracted-range, REFERENCE num-trailing COMPUTE start-pos = extracted-range-len - num-trailing + 1   SUBTRACT rng-begin FROM rng-end GIVING range-len   MOVE rng-begin TO begin-edited MOVE rng-end TO end-edited   EVALUATE TRUE WHEN rng-begin = rng-end STRING FUNCTION TRIM(begin-edited), "," INTO extracted-range (start-pos:)   WHEN range-len = 1 STRING FUNCTION TRIM(begin-edited), ",", FUNCTION TRIM(end-edited), "," INTO extracted-range (start-pos:)   WHEN OTHER STRING FUNCTION TRIM(begin-edited), "-", FUNCTION TRIM(end-edited), "," INTO extracted-range (start-pos:) END-EVALUATE . END PROGRAM add-next-range.   IDENTIFICATION DIVISION. PROGRAM-ID. find-num-trailing-spaces.   DATA DIVISION. LINKAGE SECTION. 01 str PIC X(200). 01 num-trailing PIC 999.   PROCEDURE DIVISION USING str, num-trailing. INITIALIZE num-trailing INSPECT str TALLYING num-trailing FOR TRAILING SPACES . END PROGRAM find-num-trailing-spaces.   END PROGRAM extract-range.
http://rosettacode.org/wiki/Random_numbers
Random numbers
Task Generate a collection filled with   1000   normally distributed random (or pseudo-random) numbers with a mean of   1.0   and a   standard deviation   of   0.5 Many libraries only generate uniformly distributed random numbers. If so, you may use one of these algorithms. Related task   Standard deviation
#Euphoria
Euphoria
include misc.e   function RandomNormal() atom x1, x2 x1 = rand(999999) / 1000000 x2 = rand(999999) / 1000000 return sqrt(-2*log(x1)) * cos(2*PI*x2) end function   constant n = 1000 sequence s s = repeat(0,n) for i = 1 to n do s[i] = 1 + 0.5 * RandomNormal() end for
http://rosettacode.org/wiki/Random_number_generator_(included)
Random number generator (included)
The task is to: State the type of random number generator algorithm used in a language's built-in random number generator. If the language or its immediate libraries don't provide a random number generator, skip this task. If possible, give a link to a wider explanation of the algorithm used. Note: the task is not to create an RNG, but to report on the languages in-built RNG that would be the most likely RNG used. The main types of pseudo-random number generator (PRNG) that are in use are the Linear Congruential Generator (LCG), and the Generalized Feedback Shift Register (GFSR), (of which the Mersenne twister generator is a subclass). The last main type is where the output of one of the previous ones (typically a Mersenne twister) is fed through a cryptographic hash function to maximize unpredictability of individual bits. Note that neither LCGs nor GFSRs should be used for the most demanding applications (cryptography) without additional steps.
#Julia
Julia
setrand(3) random(6)+1 \\ chosen by fair dice roll. \\ guaranteed to the random.
http://rosettacode.org/wiki/Random_number_generator_(included)
Random number generator (included)
The task is to: State the type of random number generator algorithm used in a language's built-in random number generator. If the language or its immediate libraries don't provide a random number generator, skip this task. If possible, give a link to a wider explanation of the algorithm used. Note: the task is not to create an RNG, but to report on the languages in-built RNG that would be the most likely RNG used. The main types of pseudo-random number generator (PRNG) that are in use are the Linear Congruential Generator (LCG), and the Generalized Feedback Shift Register (GFSR), (of which the Mersenne twister generator is a subclass). The last main type is where the output of one of the previous ones (typically a Mersenne twister) is fed through a cryptographic hash function to maximize unpredictability of individual bits. Note that neither LCGs nor GFSRs should be used for the most demanding applications (cryptography) without additional steps.
#Kotlin
Kotlin
setrand(3) random(6)+1 \\ chosen by fair dice roll. \\ guaranteed to the random.
http://rosettacode.org/wiki/Read_a_configuration_file
Read a configuration file
The task is to read a configuration file in standard configuration file format, and set variables accordingly. For this task, we have a configuration file as follows: # This is a configuration file in standard configuration file format # # Lines beginning with a hash or a semicolon are ignored by the application # program. Blank lines are also ignored by the application program. # This is the fullname parameter FULLNAME Foo Barber # This is a favourite fruit FAVOURITEFRUIT banana # This is a boolean that should be set NEEDSPEELING # This boolean is commented out ; SEEDSREMOVED # Configuration option names are not case sensitive, but configuration parameter # data is case sensitive and may be preserved by the application program. # An optional equals sign can be used to separate configuration parameter data # from the option name. This is dropped by the parser. # A configuration option may take multiple parameters separated by commas. # Leading and trailing whitespace around parameter names and parameter data fields # are ignored by the application program. OTHERFAMILY Rhu Barber, Harry Barber For the task we need to set four variables according to the configuration entries as follows: fullname = Foo Barber favouritefruit = banana needspeeling = true seedsremoved = false We also have an option that contains multiple parameters. These may be stored in an array. otherfamily(1) = Rhu Barber otherfamily(2) = Harry Barber Related tasks Update a configuration file
#Gambas
Gambas
Public Sub Form_Open() Dim fullname As String = Settings["fullname", "Foo Barber"] 'If fullname is empty then use the default "Foo Barber" Dim favouritefruit As String = Settings["favouritefruit", "banana"] Dim needspeeling As String = Settings["needspeling", True] Dim seedsremoved As String = Settings["seedsremoved", False] Dim otherfamily As String[] = Settings["otherfamily", ["Rhu Barber", "Harry Barber"]]   Print fullname   'To save Settings["fullname"] = "John Smith" fullname = Settings["fullname"]   Print fullname   End
http://rosettacode.org/wiki/Rare_numbers
Rare numbers
Definitions and restrictions Rare   numbers are positive integers   n   where:   n   is expressed in base ten   r   is the reverse of   n     (decimal digits)   n   must be non-palindromic   (n ≠ r)   (n+r)   is the   sum   (n-r)   is the   difference   and must be positive   the   sum   and the   difference   must be perfect squares Task   find and show the first   5   rare   numbers   find and show the first   8   rare   numbers       (optional)   find and show more   rare   numbers                (stretch goal) Show all output here, on this page. References   an   OEIS   entry:   A035519          rare numbers.   an   OEIS   entry:   A059755   odd rare numbers.   planetmath entry:   rare numbers.     (some hints)   author's  website:   rare numbers   by Shyam Sunder Gupta.     (lots of hints and some observations).
#REXX
REXX
/*REXX program calculates and displays a specified amount of rare numbers. */ numeric digits 20; w= digits() + digits() % 3 /*use enough dec. digs for calculations*/ parse arg many . /*obtain optional argument from the CL.*/ if many=='' | many=="," then many= 5 /*Not specified? Then use the default.*/ @g= 2002 2112 2222 2332 2442 2552 2662 2772 2882 2992 4000 4010 4030 4050 4070 4090 4100 , 4110 4120 4140 4160 4180 4210 4230 4250 4270 4290 4300 4320 4340 4360 4380 4410 4430 , 4440 4450 4470 4490 4500 4520 4540 4560 4580 4610 4630 4650 4670 4690 4700 4720 4740 , 4760 4780 4810 4830 4850 4870 4890 4900 4920 4940 4960 4980 4990 6010 6015 6030 6035 , 6050 6055 6070 6075 6090 6095 6100 6105 6120 6125 6140 6145 6160 6165 6180 6185 6210 , 6215 6230 6235 6250 6255 6270 6275 6290 6295 6300 6305 6320 6325 6340 6345 6360 6365 , 6380 6385 6410 6415 6430 6435 6450 6455 6470 6475 6490 6495 6500 6505 6520 6525 6540 , 6545 6560 6565 6580 6585 6610 6615 6630 6635 6650 6655 6670 6675 6690 6695 6700 6705 , 6720 6725 6740 6745 6760 6765 6780 6785 6810 6815 6830 6835 6850 6855 6870 6875 6890 , 6895 6900 6905 6920 6925 6940 6945 6960 6965 6980 6985 8007 8008 8017 8027 8037 8047 , 8057 8067 8077 8087 8092 8097 8107 8117 8118 8127 8137 8147 8157 8167 8177 8182 8187 , 8197 8228 8272 8297 8338 8362 8387 8448 8452 8477 8542 8558 8567 8632 8657 8668 8722 , 8747 8778 8812 8837 8888 8902 8927 8998 /*4 digit abutted numbers for AB and PQ*/ @g#= words(@g) /* [↓]─────────────────boolean arrays are used for checking for digit presence.*/ @dr.=0; @dr.2= 1; @dr.5=1 ; @dr.8= 1; @dr.9= 1 /*rare # must have these digital roots.*/ @ps.=0; @ps.2= 1; @ps.3= 1; @ps.7= 1; @ps.8= 1 /*perfect squares must end in these.*/ @149.=0; @149.1=1; @149.4=1; @149.9=1 /*values for Z that need an even Y. */ @odd.=0; do i=-9 by 2 to 9; @odd.i=1 /* " " N " " " " A. */ end /*i*/ @gen.=0; do i=1 for words(@g); parse value word(@g,i) with a 2 b 3 p 4 q; @gen.a.b.p.q=1 /*# AB···PQ could be a good rare value*/ end /*i*/ div9= 9 /*dif must be ÷ 9 when N has even #digs*/ evenN= \ (10 // 2) /*initial value for evenness of N. */ #= 0 /*the number of rare numbers (so far)*/ do n=10 /*Why 10? All 1 dig #s are palindromic*/ parse var n a 2 b 3 '' -2 p +1 q /*get 1st\2nd\penultimate\last digits. */ if @odd.a then do; n=n+10**(length(n)-1)-1 /*bump N so next N starts with even dig*/ evenN=\(length(n+1)//2) /*flag when N has an even # of digits. */ if evenN then div9= 9 /*when dif isn't divisible by 9 ... */ else div9= 99 /* " " " " " 99 " */ iterate /*let REXX do its thing with DO loop.*/ end /* {it's allowed to modify a DO index} */ if \@gen.a.b.p.q then iterate /*can N not be a rare AB···PQ number?*/ r= reverse(n) /*obtain the reverse of the number N. */ if r>n then iterate /*Difference will be negative? Skip it*/ if n==r then iterate /*Palindromic? Then it can't be rare.*/ dif= n-r; parse var dif '' -2 y +1 z /*obtain the last 2 digs of difference.*/ if @ps.z then iterate /*Not 0, 1, 4, 5, 6, 9? Not perfect sq.*/ select when z==0 then if y\==0 then iterate /*Does Z = 0? Then Y must be zero. */ when z==5 then if y\==2 then iterate /*Does Z = 5? Then Y must be two. */ when z==6 then if y//2==0 then iterate /*Does Z = 6? Then Y must be odd. */ otherwise if @149.z then if y//2 then iterate /*Z=1,4,9? Y must be even*/ end /*select*/ /* [↑] the OTHERWISE handles Z=8 case.*/ if dif//div9\==0 then iterate /*Difference isn't ÷ by div9? Then skip*/ sum= n+r; parse var sum '' -2 y +1 z /*obtain the last two digits of the sum*/ if @ps.z then iterate /*Not 0, 2, 5, 8, or 9? Not perfect sq.*/ select when z==0 then if y\==0 then iterate /*Does Z = 0? Then Y must be zero. */ when z==5 then if y\==2 then iterate /*Does Z = 5? Then Y must be two. */ when z==6 then if y//2==0 then iterate /*Does Z = 6? Then Y must be odd. */ otherwise if @149.z then if y//2 then iterate /*Z=1,4,9? Y must be even*/ end /*select*/ /* [↑] the OTHERWISE handles Z=8 case.*/ if evenN then if sum//11 \==0 then iterate /*N has even #digs? Sum must be ÷ by 11*/ $= a + b /*a head start on figuring digital root*/ do k=3 for length(n) - 2 /*now, process the rest of the digits. */ $= $ + substr(n, k, 1) /*add the remainder of the digits in N.*/ end /*k*/ do while $>9 /* [◄] Algorithm is good for 111 digs.*/ if $>9 then $= left($,1) + substr($,2,1) + substr($,3,1,0) /*>9? Reduce it.*/ end /*while*/ if \@dr.$ then iterate /*Doesn't have good digital root? Skip*/ if iSqrt(sum)**2 \== sum then iterate /*Not a perfect square? Then skip it. */ if iSqrt(dif)**2 \== dif then iterate /* " " " " " " " */ #= # + 1; call tell /*bump rare number counter; display #.*/ if #>=many then leave /* [↑] W: the width of # with commas.*/ end /*n*/ exit /*stick a fork in it, we're all done. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ commas: parse arg _; do jc=length(_)-3 to 1 by -3; _=insert(',', _, jc); end; return _ tell: say right(th(#),length(#)+9) ' rare number is:' right(commas(n),w); return th: parse arg th;return th||word('th st nd rd',1+(th//10)*(th//100%10\==1)*(th//10<4)) /*──────────────────────────────────────────────────────────────────────────────────────*/ iSqrt: parse arg x; $= 0; q= 1; do while q<=x; q=q*4; end do while q>1; q=q%4; _= x-$-q; $= $%2; if _>=0 then do; x=_; $=$+q; end end /*while q>1*/; return $
http://rosettacode.org/wiki/Range_expansion
Range expansion
A format for expressing an ordered list of integers is to use a comma separated list of either individual integers Or a range of integers denoted by the starting integer separated from the end integer in the range by a dash, '-'. (The range includes all integers in the interval including both endpoints) The range syntax is to be used only for, and for every range that expands to more than two values. Example The list of integers: -6, -3, -2, -1, 0, 1, 3, 4, 5, 7, 8, 9, 10, 11, 14, 15, 17, 18, 19, 20 Is accurately expressed by the range expression: -6,-3-1,3-5,7-11,14,15,17-20 (And vice-versa). Task Expand the range description: -6,-3--1,3-5,7-11,14,15,17-20 Note that the second element above, is the range from minus 3 to minus 1. Related task   Range extraction
#Delphi
Delphi
  program Range_expansion;   {$APPTYPE CONSOLE}   uses System.SysUtils;   const input = '-6,-3--1,3-5,7-11,14,15,17-20';   var r: TArray<Integer>; last, i, n: Integer;   begin for var part in input.Split([',']) do begin i := part.Substring(1).IndexOf('-'); if i = -1 then begin if not TryStrToInt(part, n) then raise Exception.Create('Error: value invalid ' + part); if Length(r) > 0 then if last = n then begin raise Exception.Create('Error: Duplicate value:' + n.ToString); end else begin if last > n then raise Exception.CreateFmt('Error: values not ordered: %s > %s', [last, n]); end; SetLength(r, Length(r) + 1); r[High(r)] := n; last := n; end else begin var n1 := 0; var n2 := 0; if not TryStrToInt(part.Substring(0, i + 1), n1) then raise Exception.Create('Error: value invalid ' + part); if not TryStrToInt(part.Substring(i + 2), n2) then raise Exception.Create('Error: value invalid ' + part); if n2 < n1 + 2 then raise Exception.Create('Error: Invalid range' + part); if Length(r) > 0 then begin if last = n1 then raise Exception.Create('Error: Duplicate value: ' + n1.ToString); if last > n1 then raise Exception.CreateFmt('Error: Values not ordened: %d > %d', [last, n1]); end;   for i := n1 to n2 do begin SetLength(r, Length(r) + 1); r[High(r)] := i; end;   last := n2; end; end; write('expanded: '); for var rr in r do begin write(rr, ','); end; readln; end.
http://rosettacode.org/wiki/Read_a_file_line_by_line
Read a file line by line
Read a file one line at a time, as opposed to reading the entire file at once. Related tasks Read a file character by character Input loop.
#Draco
Draco
\util.g proc nonrec main() void: /* first we need to declare a file buffer and an input channel */ file() infile; channel input text in_ch;   /* a buffer to store the line in is also handy */ [256] char line; word counter; /* to count the lines */   /* open the file, and exit if it fails */ if not open(in_ch, infile, "input.txt") then writeln("cannot open file"); exit(1) fi;   counter := 0;   /* readln() reads a line and will return false once the end is reached */ /* we pass in a pointer so it stores a C-style zero-terminated string, * rather than try to fill the entire array */ while readln(in_ch; &line[0]) do counter := counter + 1; writeln(counter:5, ": ", &line[0]) od;   /* finally, close the file */ close(in_ch) corp
http://rosettacode.org/wiki/Ranking_methods
Ranking methods
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort The numerical rank of competitors in a competition shows if one is better than, equal to, or worse than another based on their results in a competition. The numerical rank of a competitor can be assigned in several different ways. Task The following scores are accrued for all competitors of a competition (in best-first order): 44 Solomon 42 Jason 42 Errol 41 Garry 41 Bernard 41 Barry 39 Stephen For each of the following ranking methods, create a function/method/procedure/subroutine... that applies the ranking method to an ordered list of scores with scorers: Standard. (Ties share what would have been their first ordinal number). Modified. (Ties share what would have been their last ordinal number). Dense. (Ties share the next available integer). Ordinal. ((Competitors take the next available integer. Ties are not treated otherwise). Fractional. (Ties share the mean of what would have been their ordinal numbers). See the wikipedia article for a fuller description. Show here, on this page, the ranking of the test scores under each of the numbered ranking methods.
#Perl
Perl
my %scores = ( 'Solomon' => 44, 'Jason' => 42, 'Errol' => 42, 'Garry' => 41, 'Bernard' => 41, 'Barry' => 41, 'Stephen' => 39 );   sub tiers { my(%s) = @_; my(%h); push @{$h{$s{$_}}}, $_ for keys %s; @{\%h}{reverse sort keys %h}; }   sub standard { my(%s) = @_; my($result); my $rank = 1; for my $players (tiers %s) { $result .= "$rank " . join(', ', sort @$players) . "\n"; $rank += @$players; } return $result; }   sub modified { my(%s) = @_; my($result); my $rank = 0; for my $players (tiers %s) { $rank += @$players; $result .= "$rank " . join(', ', sort @$players) . "\n"; } return $result; }   sub dense { my(%s) = @_; my($n,$result); $result .= sprintf "%d %s\n", ++$n, join(', ', sort @$_) for tiers %s; return $result; }   sub ordinal { my(%s) = @_; my($n,$result); for my $players (tiers %s) { $result .= sprintf "%d %s\n", ++$n, $_ for sort @$players; } return $result; }   sub fractional { my(%s) = @_; my($result); my $rank = 1; for my $players (tiers %s) { my $beg = $rank; my $end = $rank += @$players; my $avg = 0; $avg += $_/@$players for $beg .. $end-1; $result .= sprintf "%3.1f %s\n", $avg, join ', ', sort @$players; } return $result; }   print "Standard:\n" . standard(%scores) . "\n"; print "Modified:\n" . modified(%scores) . "\n"; print "Dense:\n" . dense(%scores) . "\n"; print "Ordinal:\n" . ordinal(%scores) . "\n"; print "Fractional:\n" . fractional(%scores) . "\n";
http://rosettacode.org/wiki/Range_consolidation
Range consolidation
Define a range of numbers   R,   with bounds   b0   and   b1   covering all numbers between and including both bounds. That range can be shown as: [b0, b1]    or equally as: [b1, b0] Given two ranges, the act of consolidation between them compares the two ranges:   If one range covers all of the other then the result is that encompassing range.   If the ranges touch or intersect then the result is   one   new single range covering the overlapping ranges.   Otherwise the act of consolidation is to return the two non-touching ranges. Given   N   ranges where   N > 2   then the result is the same as repeatedly replacing all combinations of two ranges by their consolidation until no further consolidation between range pairs is possible. If   N < 2   then range consolidation has no strict meaning and the input can be returned. Example 1   Given the two ranges   [1, 2.5]   and   [3, 4.2]   then   there is no common region between the ranges and the result is the same as the input. Example 2   Given the two ranges   [1, 2.5]   and   [1.8, 4.7]   then   there is :   an overlap   [2.5, 1.8]   between the ranges and   the result is the single range   [1, 4.7].   Note that order of bounds in a range is not (yet) stated. Example 3   Given the two ranges   [6.1, 7.2]   and   [7.2, 8.3]   then   they touch at   7.2   and   the result is the single range   [6.1, 8.3]. Example 4   Given the three ranges   [1, 2]   and   [4, 8]   and   [2, 5]   then there is no intersection of the ranges   [1, 2]   and   [4, 8]   but the ranges   [1, 2]   and   [2, 5]   overlap and   consolidate to produce the range   [1, 5].   This range, in turn, overlaps the other range   [4, 8],   and   so consolidates to the final output of the single range   [1, 8]. Task Let a normalized range display show the smaller bound to the left;   and show the range with the smaller lower bound to the left of other ranges when showing multiple ranges. Output the normalized result of applying consolidation to these five sets of ranges: [1.1, 2.2] [6.1, 7.2], [7.2, 8.3] [4, 3], [2, 1] [4, 3], [2, 1], [-1, -2], [3.9, 10] [1, 3], [-6, -1], [-4, -5], [8, 2], [-6, -6] Show all output here. See also Set consolidation Set of real numbers
#Yabasic
Yabasic
sub sort(tabla()) local items, i, t1, t2, s   items = arraysize(tabla(), 1)   repeat s = true for i = 1 to items-1 if tabla(i, 1) > tabla(i+1, 1) then t1 = tabla(i, 1) : t2 = tabla(i, 2) tabla(i, 1) = tabla(i + 1, 1) : tabla(i, 2) = tabla(i + 1, 2) tabla(i + 1, 1) = t1 : tabla(i + 1, 2) = t2 s = false end if next until(s) end sub   sub normalize(tabla()) local items, i, t   items = arraysize(tabla(), 1)   for i = 1 to items if tabla(i, 1) > tabla(i, 2) then t = tabla(i, 1) tabla(i, 1) = tabla(i, 2) tabla(i, 2) = t end if next   sort(tabla()) end sub   sub consolidate(tabla()) local items, i   normalize(tabla()) items = arraysize(tabla(), 1)   for i = 1 to items - 1 if tabla(i + 1, 1) <= tabla(i, 2) then tabla(i + 1, 1) = tabla(i, 1) if tabla(i + 1, 2) <= tabla(i, 2) then tabla(i + 1, 2) = tabla(i, 2) end if tabla(i, 1) = void : tabla(i, 2) = void end if next end sub   // data 1, 1.1, 2.2 // data 2, 6.1, 7.2, 7.2, 8.3 // data 2, 4, 3, 2, 1 // data 4, 4, 3, 2, 1, -1, -2, 3.9, 10 data 5, 1,3, -6,-1, -4,-5, 8,2, -6,-6   void = 10^30 read items   dim tabla(items, 2)   for i = 1 to items read tabla(i, 1), tabla(i, 2) next   consolidate(tabla())   for i = 1 to items if tabla(i, 1) <> void print tabla(i, 1), "..", tabla(i, 2); next
http://rosettacode.org/wiki/Reverse_a_string
Reverse a string
Task Take a string and reverse it. For example, "asdf" becomes "fdsa". Extra credit Preserve Unicode combining characters. For example, "as⃝df̅" becomes "f̅ds⃝a", not "̅fd⃝sa". Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#PARI.2FGP
PARI/GP
reverse(s)=concat(Vecrev(s))
http://rosettacode.org/wiki/Random_number_generator_(device)
Random number generator (device)
Task If your system has a means to generate random numbers involving not only a software algorithm   (like the /dev/urandom devices in Unix),   then: show how to obtain a random 32-bit number from that mechanism. Related task Random_number_generator_(included)
#PicoLisp
PicoLisp
: (in "/dev/urandom" (rd 4)) -> 2917110327
http://rosettacode.org/wiki/Random_number_generator_(device)
Random number generator (device)
Task If your system has a means to generate random numbers involving not only a software algorithm   (like the /dev/urandom devices in Unix),   then: show how to obtain a random 32-bit number from that mechanism. Related task Random_number_generator_(included)
#PowerShell
PowerShell
  function Get-RandomInteger { Param ( [Parameter(Mandatory=$false, ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true, Position=0)] [ValidateScript({$_ -ge 4})] [int[]] $InputObject = 64 )   Begin { $rng = New-Object -TypeName System.Security.Cryptography.RNGCryptoServiceProvider } Process { foreach($count in $InputObject) { $bytes = New-Object -TypeName Byte[] -Argument $count $rng.GetBytes($bytes) [System.BitConverter]::ToInt32($bytes,0) } } End { Remove-Variable -Name rng -Scope Local } }  
http://rosettacode.org/wiki/Random_Latin_squares
Random Latin squares
A Latin square of size n is an arrangement of n symbols in an n-by-n square in such a way that each row and column has each symbol appearing exactly once. A randomised Latin square generates random configurations of the symbols for any given n. Example n=4 randomised Latin square 0 2 3 1 2 1 0 3 3 0 1 2 1 3 2 0 Task Create a function/routine/procedure/method/... that given n generates a randomised Latin square of size n. Use the function to generate and show here, two randomly generated squares of size 5. Note Strict Uniformity in the random generation is a hard problem and not a requirement of the task. Reference Wikipedia: Latin square OEIS: A002860
#M2000_Interpreter
M2000 Interpreter
  Module FastLatinSquare { n=5 For k=1 To 2 latin() Next n=40 latin() Sub latin() Local i,a, a(1 To n), b, k Profiler flush Print "latin square ";n;" by ";n For i=1 To n Push i Next i For i=1 To n div 2 Shiftback random(2, n) Next i a=[] Push ! stack(a) a=array(a) ' change a from stack to array For i=1 To n*10 Shiftback random(2, n) Next i For i=0 To n-1 Data number ' rotate by one the stack items b=[] ' move stack To b, leave empty stack a(a#val(i))=b Push ! stack(b) ' Push from a copy of b all items To stack Next i flush For k=1 To n div 2 z=random(2, n) For i=1 To n a=a(i) stack a { shift z } Next Next For i=1 To n a=a(i) a(i)=array(a) ' change To array from stack Next i For i=1 To n Print a(i) Next i Print TimeCount End Sub } FastLatinSquare
http://rosettacode.org/wiki/Ray-casting_algorithm
Ray-casting algorithm
This page uses content from Wikipedia. The original article was at Point_in_polygon. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Given a point and a polygon, check if the point is inside or outside the polygon using the ray-casting algorithm. A pseudocode can be simply: count ← 0 foreach side in polygon: if ray_intersects_segment(P,side) then count ← count + 1 if is_odd(count) then return inside else return outside Where the function ray_intersects_segment return true if the horizontal ray starting from the point P intersects the side (segment), false otherwise. An intuitive explanation of why it works is that every time we cross a border, we change "country" (inside-outside, or outside-inside), but the last "country" we land on is surely outside (since the inside of the polygon is finite, while the ray continues towards infinity). So, if we crossed an odd number of borders we were surely inside, otherwise we were outside; we can follow the ray backward to see it better: starting from outside, only an odd number of crossing can give an inside: outside-inside, outside-inside-outside-inside, and so on (the - represents the crossing of a border). So the main part of the algorithm is how we determine if a ray intersects a segment. The following text explain one of the possible ways. Looking at the image on the right, we can easily be convinced of the fact that rays starting from points in the hatched area (like P1 and P2) surely do not intersect the segment AB. We also can easily see that rays starting from points in the greenish area surely intersect the segment AB (like point P3). So the problematic points are those inside the white area (the box delimited by the points A and B), like P4. Let us take into account a segment AB (the point A having y coordinate always smaller than B's y coordinate, i.e. point A is always below point B) and a point P. Let us use the cumbersome notation PAX to denote the angle between segment AP and AX, where X is always a point on the horizontal line passing by A with x coordinate bigger than the maximum between the x coordinate of A and the x coordinate of B. As explained graphically by the figures on the right, if PAX is greater than the angle BAX, then the ray starting from P intersects the segment AB. (In the images, the ray starting from PA does not intersect the segment, while the ray starting from PB in the second picture, intersects the segment). Points on the boundary or "on" a vertex are someway special and through this approach we do not obtain coherent results. They could be treated apart, but it is not necessary to do so. An algorithm for the previous speech could be (if P is a point, Px is its x coordinate): ray_intersects_segment: P : the point from which the ray starts A : the end-point of the segment with the smallest y coordinate (A must be "below" B) B : the end-point of the segment with the greatest y coordinate (B must be "above" A) if Py = Ay or Py = By then Py ← Py + ε end if if Py < Ay or Py > By then return false else if Px >= max(Ax, Bx) then return false else if Px < min(Ax, Bx) then return true else if Ax ≠ Bx then m_red ← (By - Ay)/(Bx - Ax) else m_red ← ∞ end if if Ax ≠ Px then m_blue ← (Py - Ay)/(Px - Ax) else m_blue ← ∞ end if if m_blue ≥ m_red then return true else return false end if end if end if (To avoid the "ray on vertex" problem, the point is moved upward of a small quantity   ε.)
#Racket
Racket
  #lang racket   (module pip racket (require racket/contract)   (provide point) (provide seg) (provide (contract-out [point-in-polygon? (-> point? list? boolean?)]))   (struct point (x y) #:transparent) (struct seg (Ax Ay Bx By) #:transparent) (define ε 0.000001) (define (neq? x y) (not (eq? x y)))   (define (ray-cross-seg? r s) (let* ([Ax (seg-Ax s)] [Ay (seg-Ay s)] [Bx (seg-Bx s)] [By (seg-By s)] [Px (point-x r)] [Pyo (point-y r)] [Py (+ Pyo (if (or (eq? Pyo Ay) (eq? Pyo By)) ε 0))])   (define Ax2 (if (< Ay By) Ax Bx)) (define Ay2 (if (< Ay By) Ay By)) (define Bx2 (if (< Ay By) Bx Ax)) (define By2 (if (< Ay By) By Ay))   (cond [(or (> Py (max Ay By)) (< Py (min Ay By))) #f] [(> Px (max Ax Bx)) #f] [else (cond [(< Px (min Ax Bx)) #t] [else (let ([red (if (neq? Ax2 Bx2) (/ (- By2 Ay2) (- Bx2 Ax2)) +inf.0)] [blue (if (neq? Ax2 Px) (/ (- Py Ay2) (- Px Ax2)) +inf.0)]) (if (>= blue red) #t #f))])])))   (define (point-in-polygon? point polygon) (odd? (for/fold ([c 0]) ([seg polygon]) (+ c (if (ray-cross-seg? point seg) 1 0))))))   (require 'pip)   (define test-point-list (list (point 5.0 5.0) (point 5.0 8.0) (point -10.0 5.0) (point 0.0 5.0) (point 10.0 5.0) (point 8.0 5.0) (point 10.0 10.0)))   (define square (list (seg 0.0 0.0 10.0 0.0) (seg 10.0 0.0 10.0 10.0) (seg 10.0 10.0 0.0 10.0) (seg 0.0 0.0 0.0 10.0)))   (define exagon (list (seg 3.0 0.0 7.0 0.0) (seg 7.0 0.0 10.0 5.0) (seg 10.0 5.0 7.0 10.0) (seg 7.0 10.0 3.0 10.0) (seg 0.0 5.0 3.0 10.0) (seg 3.0 0.0 0.0 5.0)))   (define (test-figure fig name) (printf "\ntesting ~a: \n" name) (for ([p test-point-list]) (printf "testing ~v: ~a\n" p (point-in-polygon? p fig))))   (test-figure square "square") (test-figure exagon "exagon")  
http://rosettacode.org/wiki/Queue/Definition
Queue/Definition
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. Illustration of FIFO behavior Task Implement a FIFO queue. Elements are added at one side and popped from the other in the order of insertion. Operations:   push   (aka enqueue)    - add element   pop     (aka dequeue)    - pop first element   empty                             - return truth value when empty Errors:   handle the error of trying to pop from an empty queue (behavior depends on the language and platform) See   Queue/Usage   for the built-in FIFO or queue of your language or standard library. See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal Stack
#Ada
Ada
generic type Element_Type is private; package Fifo is type Fifo_Type is private; procedure Push(List : in out Fifo_Type; Item : in Element_Type); procedure Pop(List : in out Fifo_Type; Item : out Element_Type); function Is_Empty(List : Fifo_Type) return Boolean; Empty_Error : exception; private type Fifo_Element; type Fifo_Ptr is access Fifo_Element; type Fifo_Type is record Head : Fifo_Ptr := null; Tail : Fifo_Ptr := null; end record; type Fifo_Element is record Value : Element_Type; Next  : Fifo_Ptr := null; end record; end Fifo;
http://rosettacode.org/wiki/Quaternion_type
Quaternion type
Quaternions   are an extension of the idea of   complex numbers. A complex number has a real and complex part,   sometimes written as   a + bi, where   a   and   b   stand for real numbers, and   i   stands for the square root of minus 1. An example of a complex number might be   -3 + 2i,   where the real part,   a   is   -3.0   and the complex part,   b   is   +2.0. A quaternion has one real part and three imaginary parts,   i,   j,   and   k. A quaternion might be written as   a + bi + cj + dk. In the quaternion numbering system:   i∙i = j∙j = k∙k = i∙j∙k = -1,       or more simply,   ii  = jj  = kk  = ijk   = -1. The order of multiplication is important, as, in general, for two quaternions:   q1   and   q2:     q1q2 ≠ q2q1. An example of a quaternion might be   1 +2i +3j +4k There is a list form of notation where just the numbers are shown and the imaginary multipliers   i,   j,   and   k   are assumed by position. So the example above would be written as   (1, 2, 3, 4) Task Given the three quaternions and their components: q = (1, 2, 3, 4) = (a, b, c, d) q1 = (2, 3, 4, 5) = (a1, b1, c1, d1) q2 = (3, 4, 5, 6) = (a2, b2, c2, d2) And a wholly real number   r = 7. Create functions   (or classes)   to perform simple maths with quaternions including computing: The norm of a quaternion: = a 2 + b 2 + c 2 + d 2 {\displaystyle ={\sqrt {a^{2}+b^{2}+c^{2}+d^{2}}}} The negative of a quaternion: = (-a, -b, -c, -d) The conjugate of a quaternion: = ( a, -b, -c, -d) Addition of a real number   r   and a quaternion   q: r + q = q + r = (a+r, b, c, d) Addition of two quaternions: q1 + q2 = (a1+a2, b1+b2, c1+c2, d1+d2) Multiplication of a real number and a quaternion: qr = rq = (ar, br, cr, dr) Multiplication of two quaternions   q1   and   q2   is given by: ( a1a2 − b1b2 − c1c2 − d1d2,   a1b2 + b1a2 + c1d2 − d1c2,   a1c2 − b1d2 + c1a2 + d1b2,   a1d2 + b1c2 − c1b2 + d1a2 ) Show that, for the two quaternions   q1   and   q2: q1q2 ≠ q2q1 If a language has built-in support for quaternions, then use it. C.f.   Vector products   On Quaternions;   or on a new System of Imaginaries in Algebra.   By Sir William Rowan Hamilton LL.D, P.R.I.A., F.R.A.S., Hon. M. R. Soc. Ed. and Dub., Hon. or Corr. M. of the Royal or Imperial Academies of St. Petersburgh, Berlin, Turin and Paris, Member of the American Academy of Arts and Sciences, and of other Scientific Societies at Home and Abroad, Andrews' Prof. of Astronomy in the University of Dublin, and Royal Astronomer of Ireland.
#Ada
Ada
generic type Real is digits <>; package Quaternions is type Quaternion is record A, B, C, D : Real; end record; function "abs" (Left : Quaternion) return Real; function Conj (Left : Quaternion) return Quaternion; function "-" (Left : Quaternion) return Quaternion; function "+" (Left, Right : Quaternion) return Quaternion; function "-" (Left, Right : Quaternion) return Quaternion; function "*" (Left : Quaternion; Right : Real) return Quaternion; function "*" (Left : Real; Right : Quaternion) return Quaternion; function "*" (Left, Right : Quaternion) return Quaternion; function Image (Left : Quaternion) return String; end Quaternions;
http://rosettacode.org/wiki/Quine
Quine
A quine is a self-referential program that can, without any external access, output its own source. A   quine   (named after Willard Van Orman Quine)   is also known as:   self-reproducing automata   (1972)   self-replicating program         or   self-replicating computer program   self-reproducing program      or   self-reproducing computer program   self-copying program             or   self-copying computer program It is named after the philosopher and logician who studied self-reference and quoting in natural language, as for example in the paradox "'Yields falsehood when preceded by its quotation' yields falsehood when preceded by its quotation." "Source" has one of two meanings. It can refer to the text-based program source. For languages in which program source is represented as a data structure, "source" may refer to the data structure: quines in these languages fall into two categories: programs which print a textual representation of themselves, or expressions which evaluate to a data structure which is equivalent to that expression. The usual way to code a quine works similarly to this paradox: The program consists of two identical parts, once as plain code and once quoted in some way (for example, as a character string, or a literal data structure). The plain code then accesses the quoted code and prints it out twice, once unquoted and once with the proper quotation marks added. Often, the plain code and the quoted code have to be nested. Task Write a program that outputs its own source code in this way. If the language allows it, you may add a variant that accesses the code directly. You are not allowed to read any external files with the source code. The program should also contain some sort of self-reference, so constant expressions which return their own value which some top-level interpreter will print out. Empty programs producing no output are not allowed. There are several difficulties that one runs into when writing a quine, mostly dealing with quoting: Part of the code usually needs to be stored as a string or structural literal in the language, which needs to be quoted somehow. However, including quotation marks in the string literal itself would be troublesome because it requires them to be escaped, which then necessitates the escaping character (e.g. a backslash) in the string, which itself usually needs to be escaped, and so on. Some languages have a function for getting the "source code representation" of a string (i.e. adds quotation marks, etc.); in these languages, this can be used to circumvent the quoting problem. Another solution is to construct the quote character from its character code, without having to write the quote character itself. Then the character is inserted into the string at the appropriate places. The ASCII code for double-quote is 34, and for single-quote is 39. Newlines in the program may have to be reproduced as newlines in the string, which usually requires some kind of escape sequence (e.g. "\n"). This causes the same problem as above, where the escaping character needs to itself be escaped, etc. If the language has a way of getting the "source code representation", it usually handles the escaping of characters, so this is not a problem. Some languages allow you to have a string literal that spans multiple lines, which embeds the newlines into the string without escaping. Write the entire program on one line, for free-form languages (as you can see for some of the solutions here, they run off the edge of the screen), thus removing the need for newlines. However, this may be unacceptable as some languages require a newline at the end of the file; and otherwise it is still generally good style to have a newline at the end of a file. (The task is not clear on whether a newline is required at the end of the file.) Some languages have a print statement that appends a newline; which solves the newline-at-the-end issue; but others do not. Next to the Quines presented here, many other versions can be found on the Quine page. Related task   print itself.
#APL
APL
1⌽,⍨9⍴'''1⌽,⍨9⍴''' ⍝ Author: Nikolay Nikolov; Source: https://dfns.dyalog.com/n_quine.htm
http://rosettacode.org/wiki/Queue/Usage
Queue/Usage
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. Illustration of FIFO behavior Task Create a queue data structure and demonstrate its operations. (For implementations of queues, see the FIFO task.) Operations:   push       (aka enqueue) - add element   pop         (aka dequeue) - pop first element   empty     - return truth value when empty See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal Stack
#C
C
#include <stdio.h> #include <stdlib.h> #include <stdbool.h>   #include <sys/queue.h>   /* #include "fifolist.h" */   int main() { int i; FIFOList head;   TAILQ_INIT(&head);   /* insert 20 integer values */ for(i=0; i < 20; i++) { m_enqueue(i, &head); }   /* dequeue and print */ while( m_dequeue(&i, &head) ) printf("%d\n", i);   fprintf(stderr, "FIFO list %s\n", ( m_dequeue(&i, &head) ) ? "had still an element" : "is void!");   exit(0); }
http://rosettacode.org/wiki/Read_a_specific_line_from_a_file
Read a specific line from a file
Some languages have special semantics for obtaining a known line number from a file. Task Demonstrate how to obtain the contents of a specific line within a file. For the purpose of this task demonstrate how the contents of the seventh line of a file can be obtained,   and store it in a variable or in memory   (for potential future use within the program if the code were to become embedded). If the file does not contain seven lines,   or the seventh line is empty,   or too big to be retrieved,   output an appropriate message. If no special semantics are available for obtaining the required line,   it is permissible to read line by line. Note that empty lines are considered and should still be counted. Also note that for functional languages or languages without variables or storage,   it is permissible to output the extracted data to standard output.
#Ring
Ring
  fp = fopen("C:\Ring\ReadMe.txt","r") n = 0   r = "" while isstring(r) while n < 8 r = fgetc(fp) if r = char(10) n++ see nl else see r ok end end fclose(fp)  
http://rosettacode.org/wiki/Quickselect_algorithm
Quickselect algorithm
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort Use the quickselect algorithm on the vector [9, 8, 7, 6, 5, 0, 1, 2, 3, 4] To show the first, second, third, ... up to the tenth largest member of the vector, in order, here on this page. Note: Quicksort has a separate task.
#C.2B.2B
C++
#include <algorithm> #include <iostream>   int main() { for (int i = 0; i < 10; i++) { int a[] = {9, 8, 7, 6, 5, 0, 1, 2, 3, 4}; std::nth_element(a, a + i, a + sizeof(a)/sizeof(*a)); std::cout << a[i]; if (i < 9) std::cout << ", "; } std::cout << std::endl;   return 0; }
http://rosettacode.org/wiki/Ramer-Douglas-Peucker_line_simplification
Ramer-Douglas-Peucker line simplification
Ramer-Douglas-Peucker line simplification You are encouraged to solve this task according to the task description, using any language you may know. The   Ramer–Douglas–Peucker   algorithm is a line simplification algorithm for reducing the number of points used to define its shape. Task Using the   Ramer–Douglas–Peucker   algorithm, simplify the   2D   line defined by the points: (0,0) (1,0.1) (2,-0.1) (3,5) (4,6) (5,7) (6,8.1) (7,9) (8,9) (9,9) The error threshold to be used is:   1.0. Display the remaining points here. Reference   the Wikipedia article:   Ramer-Douglas-Peucker algorithm.
#Openscad
Openscad
function slice(a, v) = [ for (i = v) a[i] ];   // Find the distance from the point to the line function perpendicular_distance(pt, start, end) = let ( d = end - start, dn = d / norm(d), dp = pt - start, // Dot-product of two vectors ddot = dn * dp, ds = dn * ddot ) norm(dp - ds);   // Find the point with the maximum distance from line between start and end. // Returns a vector of [dmax, point_index] function max_distance(pts, cindex=1, iresult=[0,0]) = let ( d = perpendicular_distance(pts[cindex], pts[0],pts[len(pts)-1]), result = (d > iresult[0] ? [d, cindex] : iresult) ) (cindex == len(pts) - 1 ? iresult : max_distance(pts, cindex+1, result));   // Tail recursion optimization is not possible with tree recursion. // // It's probably possible to optimize this with tail recursion by converting to // iterative approach, see // https://namekdev.net/2014/06/iterative-version-of-ramer-douglas-peucker-line-simplification-algorithm/ . // It's not possible to use iterative approach without recursion at all because // of static nature of OpenSCAD arrays. function ramer_douglas_peucker(points, epsilon=1) = let (dmax = max_distance(points)) // Simplify the line recursively if the max distance is greater than epsilon (dmax[0] > epsilon ? let ( lo = ramer_douglas_peucker( slice(points, [0:dmax[1]]), epsilon), hi = ramer_douglas_peucker( slice(points, [dmax[1]:len(points)-1]), epsilon) ) concat(slice(lo, [0:len(lo)-2]), hi) : [points[0],points[len(points)-1]]);   /* -- Demo -- */   module line(points, thickness=1, dot=2) { for (idx = [0:len(points)-2]) { translate(points[idx]) sphere(d=dot); hull() { translate(points[idx]) sphere(d=thickness); translate(points[idx+1]) sphere(d=thickness); } } translate(points[len(points)-1]) sphere(d=dot); }   function addz(pts, z=0) = [ for (p = pts) [p.x, p.y, z] ];   module demo(pts) { rdp = ramer_douglas_peucker(points=pts, epsilon=1); echo(rdp); color("gray") line(points=addz(pts, 0), thickness=0.1, dot=0.3); color("red") line(points=addz(rdp, 1), thickness=0.1, dot=0.3); }   $fn=16; points = [[0,0], [1,0.1], [2,-0.1], [3,5], [4,6], [5,7], [6,8.1], [7,9], [8,9], [9,9]]; demo(points);
http://rosettacode.org/wiki/Ramer-Douglas-Peucker_line_simplification
Ramer-Douglas-Peucker line simplification
Ramer-Douglas-Peucker line simplification You are encouraged to solve this task according to the task description, using any language you may know. The   Ramer–Douglas–Peucker   algorithm is a line simplification algorithm for reducing the number of points used to define its shape. Task Using the   Ramer–Douglas–Peucker   algorithm, simplify the   2D   line defined by the points: (0,0) (1,0.1) (2,-0.1) (3,5) (4,6) (5,7) (6,8.1) (7,9) (8,9) (9,9) The error threshold to be used is:   1.0. Display the remaining points here. Reference   the Wikipedia article:   Ramer-Douglas-Peucker algorithm.
#Perl
Perl
use strict; use warnings; use feature 'say'; use List::MoreUtils qw(firstidx minmax);   my $epsilon = 1;   sub norm { my(@list) = @_; my $sum; $sum += $_**2 for @list; sqrt($sum) }   sub perpendicular_distance { our(@start,@end,@point); local(*start,*end,*point) = (shift, shift, shift); return 0 if $start[0]==$point[0] && $start[1]==$point[1] or $end[0]==$point[0] && $end[1]==$point[1]; my ( $dx, $dy) = ( $end[0]-$start[0], $end[1]-$start[1]); my ($dpx, $dpy) = ($point[0]-$start[0],$point[1]-$start[1]); my $t = norm($dx, $dy); $dx /= $t; $dy /= $t; norm($dpx - $dx*($dx*$dpx + $dy*$dpy), $dpy - $dy*($dx*$dpx + $dy*$dpy)); }   sub Ramer_Douglas_Peucker { my(@points) = @_; return @points if @points == 2; my @d; push @d, perpendicular_distance(@points[0, -1, $_]) for 0..@points-1; my(undef,$dmax) = minmax @d; my $index = firstidx { $_ == $dmax } @d; if ($dmax > $epsilon) { my @lo = Ramer_Douglas_Peucker( @points[0..$index]); my @hi = Ramer_Douglas_Peucker( @points[$index..$#points]); return @lo[0..@lo-2], @hi; } @points[0, -1]; }   say '(' . join(' ', @$_) . ') ' for Ramer_Douglas_Peucker( [0,0],[1,0.1],[2,-0.1],[3,5],[4,6],[5,7],[6,8.1],[7,9],[8,9],[9,9] )
http://rosettacode.org/wiki/Range_extraction
Range extraction
A format for expressing an ordered list of integers is to use a comma separated list of either individual integers Or a range of integers denoted by the starting integer separated from the end integer in the range by a dash, '-'. (The range includes all integers in the interval including both endpoints) The range syntax is to be used only for, and for every range that expands to more than two values. Example The list of integers: -6, -3, -2, -1, 0, 1, 3, 4, 5, 7, 8, 9, 10, 11, 14, 15, 17, 18, 19, 20 Is accurately expressed by the range expression: -6,-3-1,3-5,7-11,14,15,17-20 (And vice-versa). Task Create a function that takes a list of integers in increasing order and returns a correctly formatted string in the range format. Use the function to compute and print the range formatted version of the following ordered list of integers. (The correct answer is: 0-2,4,6-8,11,12,14-25,27-33,35-39). 0, 1, 2, 4, 6, 7, 8, 11, 12, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 27, 28, 29, 30, 31, 32, 33, 35, 36, 37, 38, 39 Show the output of your program. Related task   Range expansion
#Common_Lisp
Common Lisp
(defun format-with-ranges (list) (unless list (return "")) (with-output-to-string (s) (let ((current (first list)) (list (rest list)) (count 1)) (princ current s) (dolist (next list) (if (= next (1+ current)) (incf count) (progn (princ (if (> count 2) "-" ",") s) (when (> count 1) (princ current s) (princ "," s)) (princ next s) (setf count 1))) (setf current next)) (when (> count 1) (princ (if (> count 2) "-" ",") s) (princ current s)))))   CL-USER> (format-with-ranges (list 0 1 2 4 6 7 8 11 12 14 15 16 17 18 19 20 21 22 23 24 25 27 28 29 30 31 32 33 35 36 37 38 39)) "0-2,4,6-8,11,12,14-25,27-33,35-39"  
http://rosettacode.org/wiki/Random_numbers
Random numbers
Task Generate a collection filled with   1000   normally distributed random (or pseudo-random) numbers with a mean of   1.0   and a   standard deviation   of   0.5 Many libraries only generate uniformly distributed random numbers. If so, you may use one of these algorithms. Related task   Standard deviation
#F.23
F#
  let n = MathNet.Numerics.Distributions.Normal(1.0,0.5) List.init 1000 (fun _->n.Sample())  
http://rosettacode.org/wiki/Random_numbers
Random numbers
Task Generate a collection filled with   1000   normally distributed random (or pseudo-random) numbers with a mean of   1.0   and a   standard deviation   of   0.5 Many libraries only generate uniformly distributed random numbers. If so, you may use one of these algorithms. Related task   Standard deviation
#Factor
Factor
USING: random ; 1000 [ 1.0 0.5 normal-random-float ] replicate
http://rosettacode.org/wiki/Random_number_generator_(included)
Random number generator (included)
The task is to: State the type of random number generator algorithm used in a language's built-in random number generator. If the language or its immediate libraries don't provide a random number generator, skip this task. If possible, give a link to a wider explanation of the algorithm used. Note: the task is not to create an RNG, but to report on the languages in-built RNG that would be the most likely RNG used. The main types of pseudo-random number generator (PRNG) that are in use are the Linear Congruential Generator (LCG), and the Generalized Feedback Shift Register (GFSR), (of which the Mersenne twister generator is a subclass). The last main type is where the output of one of the previous ones (typically a Mersenne twister) is fed through a cryptographic hash function to maximize unpredictability of individual bits. Note that neither LCGs nor GFSRs should be used for the most demanding applications (cryptography) without additional steps.
#Lua
Lua
setrand(3) random(6)+1 \\ chosen by fair dice roll. \\ guaranteed to the random.
http://rosettacode.org/wiki/Random_number_generator_(included)
Random number generator (included)
The task is to: State the type of random number generator algorithm used in a language's built-in random number generator. If the language or its immediate libraries don't provide a random number generator, skip this task. If possible, give a link to a wider explanation of the algorithm used. Note: the task is not to create an RNG, but to report on the languages in-built RNG that would be the most likely RNG used. The main types of pseudo-random number generator (PRNG) that are in use are the Linear Congruential Generator (LCG), and the Generalized Feedback Shift Register (GFSR), (of which the Mersenne twister generator is a subclass). The last main type is where the output of one of the previous ones (typically a Mersenne twister) is fed through a cryptographic hash function to maximize unpredictability of individual bits. Note that neither LCGs nor GFSRs should be used for the most demanding applications (cryptography) without additional steps.
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
setrand(3) random(6)+1 \\ chosen by fair dice roll. \\ guaranteed to the random.
http://rosettacode.org/wiki/Random_number_generator_(included)
Random number generator (included)
The task is to: State the type of random number generator algorithm used in a language's built-in random number generator. If the language or its immediate libraries don't provide a random number generator, skip this task. If possible, give a link to a wider explanation of the algorithm used. Note: the task is not to create an RNG, but to report on the languages in-built RNG that would be the most likely RNG used. The main types of pseudo-random number generator (PRNG) that are in use are the Linear Congruential Generator (LCG), and the Generalized Feedback Shift Register (GFSR), (of which the Mersenne twister generator is a subclass). The last main type is where the output of one of the previous ones (typically a Mersenne twister) is fed through a cryptographic hash function to maximize unpredictability of individual bits. Note that neither LCGs nor GFSRs should be used for the most demanding applications (cryptography) without additional steps.
#MATLAB
MATLAB
setrand(3) random(6)+1 \\ chosen by fair dice roll. \\ guaranteed to the random.
http://rosettacode.org/wiki/Random_number_generator_(included)
Random number generator (included)
The task is to: State the type of random number generator algorithm used in a language's built-in random number generator. If the language or its immediate libraries don't provide a random number generator, skip this task. If possible, give a link to a wider explanation of the algorithm used. Note: the task is not to create an RNG, but to report on the languages in-built RNG that would be the most likely RNG used. The main types of pseudo-random number generator (PRNG) that are in use are the Linear Congruential Generator (LCG), and the Generalized Feedback Shift Register (GFSR), (of which the Mersenne twister generator is a subclass). The last main type is where the output of one of the previous ones (typically a Mersenne twister) is fed through a cryptographic hash function to maximize unpredictability of individual bits. Note that neither LCGs nor GFSRs should be used for the most demanding applications (cryptography) without additional steps.
#Maxima
Maxima
setrand(3) random(6)+1 \\ chosen by fair dice roll. \\ guaranteed to the random.
http://rosettacode.org/wiki/Read_a_configuration_file
Read a configuration file
The task is to read a configuration file in standard configuration file format, and set variables accordingly. For this task, we have a configuration file as follows: # This is a configuration file in standard configuration file format # # Lines beginning with a hash or a semicolon are ignored by the application # program. Blank lines are also ignored by the application program. # This is the fullname parameter FULLNAME Foo Barber # This is a favourite fruit FAVOURITEFRUIT banana # This is a boolean that should be set NEEDSPEELING # This boolean is commented out ; SEEDSREMOVED # Configuration option names are not case sensitive, but configuration parameter # data is case sensitive and may be preserved by the application program. # An optional equals sign can be used to separate configuration parameter data # from the option name. This is dropped by the parser. # A configuration option may take multiple parameters separated by commas. # Leading and trailing whitespace around parameter names and parameter data fields # are ignored by the application program. OTHERFAMILY Rhu Barber, Harry Barber For the task we need to set four variables according to the configuration entries as follows: fullname = Foo Barber favouritefruit = banana needspeeling = true seedsremoved = false We also have an option that contains multiple parameters. These may be stored in an array. otherfamily(1) = Rhu Barber otherfamily(2) = Harry Barber Related tasks Update a configuration file
#Go
Go
package config   import ( "errors" "io" "fmt" "bytes" "strings" "io/ioutil" )   var ( ENONE = errors.New("Requested value does not exist") EBADTYPE = errors.New("Requested type and actual type do not match") EBADVAL = errors.New("Value and type do not match") )   type varError struct { err error n string t VarType }   func (err *varError) Error() string { return fmt.Sprintf("%v: (%q, %v)", err.err, err.n, err.t) }   type VarType int   const ( Bool VarType = 1 + iota Array String )   func (t VarType) String() string { switch t { case Bool: return "Bool" case Array: return "Array" case String: return "String" }   panic("Unknown VarType") }   type confvar struct { Type VarType Val interface{} }   type Config struct { m map[string]confvar }   func Parse(r io.Reader) (c *Config, err error) { c = new(Config) c.m = make(map[string]confvar)   buf, err := ioutil.ReadAll(r) if err != nil { return }   lines := bytes.Split(buf, []byte{'\n'})   for _, line := range lines { line = bytes.TrimSpace(line) if len(line) == 0 { continue } switch line[0] { case '#', ';': continue }   parts := bytes.SplitN(line, []byte{' '}, 2) nam := string(bytes.ToLower(parts[0]))   if len(parts) == 1 { c.m[nam] = confvar{Bool, true} continue }   if strings.Contains(string(parts[1]), ",") { tmpB := bytes.Split(parts[1], []byte{','}) for i := range tmpB { tmpB[i] = bytes.TrimSpace(tmpB[i]) } tmpS := make([]string, 0, len(tmpB)) for i := range tmpB { tmpS = append(tmpS, string(tmpB[i])) }   c.m[nam] = confvar{Array, tmpS} continue }   c.m[nam] = confvar{String, string(bytes.TrimSpace(parts[1]))} }   return }   func (c *Config) Bool(name string) (bool, error) { name = strings.ToLower(name)   if _, ok := c.m[name]; !ok { return false, nil }   if c.m[name].Type != Bool { return false, &varError{EBADTYPE, name, Bool} }   v, ok := c.m[name].Val.(bool) if !ok { return false, &varError{EBADVAL, name, Bool} } return v, nil }   func (c *Config) Array(name string) ([]string, error) { name = strings.ToLower(name)   if _, ok := c.m[name]; !ok { return nil, &varError{ENONE, name, Array} }   if c.m[name].Type != Array { return nil, &varError{EBADTYPE, name, Array} }   v, ok := c.m[name].Val.([]string) if !ok { return nil, &varError{EBADVAL, name, Array} } return v, nil }   func (c *Config) String(name string) (string, error) { name = strings.ToLower(name)   if _, ok := c.m[name]; !ok { return "", &varError{ENONE, name, String} }   if c.m[name].Type != String { return "", &varError{EBADTYPE, name, String} }   v, ok := c.m[name].Val.(string) if !ok { return "", &varError{EBADVAL, name, String} }   return v, nil }
http://rosettacode.org/wiki/Rare_numbers
Rare numbers
Definitions and restrictions Rare   numbers are positive integers   n   where:   n   is expressed in base ten   r   is the reverse of   n     (decimal digits)   n   must be non-palindromic   (n ≠ r)   (n+r)   is the   sum   (n-r)   is the   difference   and must be positive   the   sum   and the   difference   must be perfect squares Task   find and show the first   5   rare   numbers   find and show the first   8   rare   numbers       (optional)   find and show more   rare   numbers                (stretch goal) Show all output here, on this page. References   an   OEIS   entry:   A035519          rare numbers.   an   OEIS   entry:   A059755   odd rare numbers.   planetmath entry:   rare numbers.     (some hints)   author's  website:   rare numbers   by Shyam Sunder Gupta.     (lots of hints and some observations).
#Ring
Ring
  load "stdlib.ring"   see "working..." + nl see "the first 5 rare numbers are:" + nl   num = 0   for n = 1 to 2042832002 strn = string(n) nrev = "" for m = len(strn) to 1 step -1 nrev = nrev + strn[m] next nrev = number(nrev) sum = n + nrev diff = n - nrev if diff < 1 loop ok sqrtsum = sqrt(sum) flagsum = (sqrtsum = floor(sqrtsum)) sqrtdiff = sqrt(diff) flagdiff= (sqrtdiff = floor(sqrtdiff)) if flagsum = 1 and flagdiff = 1 num = num + 1 see "" + num + ": " + n + nl ok next see "done..." + nl  
http://rosettacode.org/wiki/Range_expansion
Range expansion
A format for expressing an ordered list of integers is to use a comma separated list of either individual integers Or a range of integers denoted by the starting integer separated from the end integer in the range by a dash, '-'. (The range includes all integers in the interval including both endpoints) The range syntax is to be used only for, and for every range that expands to more than two values. Example The list of integers: -6, -3, -2, -1, 0, 1, 3, 4, 5, 7, 8, 9, 10, 11, 14, 15, 17, 18, 19, 20 Is accurately expressed by the range expression: -6,-3-1,3-5,7-11,14,15,17-20 (And vice-versa). Task Expand the range description: -6,-3--1,3-5,7-11,14,15,17-20 Note that the second element above, is the range from minus 3 to minus 1. Related task   Range extraction
#DWScript
DWScript
  function ExpandRanges(ranges : String) : array of Integer; begin for var range in ranges.Split(',') do begin var separator = range.IndexOf('-', 2); if separator > 0 then begin for var i := range.Left(separator-1).ToInteger to range.Copy(separator+1).ToInteger do Result.Add(i); end else begin Result.Add(range.ToInteger) end; end; end;   var expanded := ExpandRanges('-6,-3--1,3-5,7-11,14,15,17-20'); PrintLn(JSON.Stringify(expanded));  
http://rosettacode.org/wiki/Read_a_file_line_by_line
Read a file line by line
Read a file one line at a time, as opposed to reading the entire file at once. Related tasks Read a file character by character Input loop.
#Elena
Elena
import system'io; import extensions; import extensions'routines;   public program() { File.assign:"file.txt".forEachLine(printingLn) }
http://rosettacode.org/wiki/Read_a_file_line_by_line
Read a file line by line
Read a file one line at a time, as opposed to reading the entire file at once. Related tasks Read a file character by character Input loop.
#Elixir
Elixir
  defmodule FileReader do # Create a File.Stream and inspect each line def by_line(path) do File.stream!(path) |> Stream.map(&(IO.inspect(&1))) |> Stream.run end   def bin_line(path) do # Build the stream in binary instead for performance increase case File.open(path) do # File returns a tuple, {:ok,file}, if successful {:ok, file} -> IO.binstream(file, :line) |> Stream.map(&(IO.inspect(&1))) |> Stream.run # And returns {:error,reason} if unsuccessful {:error,reason} -> # Use Erlang's format_error to return an error string  :file.format_error(reason) end end end  
http://rosettacode.org/wiki/Ranking_methods
Ranking methods
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort The numerical rank of competitors in a competition shows if one is better than, equal to, or worse than another based on their results in a competition. The numerical rank of a competitor can be assigned in several different ways. Task The following scores are accrued for all competitors of a competition (in best-first order): 44 Solomon 42 Jason 42 Errol 41 Garry 41 Bernard 41 Barry 39 Stephen For each of the following ranking methods, create a function/method/procedure/subroutine... that applies the ranking method to an ordered list of scores with scorers: Standard. (Ties share what would have been their first ordinal number). Modified. (Ties share what would have been their last ordinal number). Dense. (Ties share the next available integer). Ordinal. ((Competitors take the next available integer. Ties are not treated otherwise). Fractional. (Ties share the mean of what would have been their ordinal numbers). See the wikipedia article for a fuller description. Show here, on this page, the ranking of the test scores under each of the numbered ranking methods.
#Phix
Phix
with javascript_semantics function ties(sequence scores) sequence t = {}, -- {start,num} pairs tdx = repeat(0,length(scores)) integer last = -1 for i=1 to length(scores) do integer curr = scores[i][1] if curr=last then t[$][2] += 1 else t = append(t,{i,1}) end if tdx[i] = length(t) last = curr end for -- eg {{{1,1},{2,2},{4,3},{7,1}}, -- {1,2,2,3,3,3,4}} return {t,tdx} end function enum STANDARD, -- eg {1,2,2,4,4,4,7} MODIFIED, -- eg {1,3,3,6,6,6,7} DENSE, -- (==tdx) ORDINAL, -- eg {1,2,3,4,5,6,7} FRACTION, -- {1,2.5,2.5,5,5,5,7} METHODS = $ function rank(integer i, method, sequence t, tdx) integer idx = tdx[i], {tx,tn} = t[idx] switch method case STANDARD: return tx case MODIFIED: return tx+tn-1 case DENSE : return idx case ORDINAL : return i case FRACTION: return tx+(tn-1)/2 end switch end function constant scores = {{44, "Solomon"}, {42, "Jason"}, {42, "Errol"}, {41, "Garry"}, {41, "Bernard"}, {41, "Barry"}, {39, "Stephen"}} sequence {t,tdx} = ties(scores) printf(1," score name standard modified dense ordinal fractional\n") for i=1 to length(scores) do sequence ranks = repeat(0,METHODS) for method=1 to METHODS do ranks[method] = rank(i,method,t,tdx) end for printf(1,"%5d  %-7s ",scores[i]) printf(1,"%6g %8g %6g %6g %9g\n",ranks) end for
http://rosettacode.org/wiki/Range_consolidation
Range consolidation
Define a range of numbers   R,   with bounds   b0   and   b1   covering all numbers between and including both bounds. That range can be shown as: [b0, b1]    or equally as: [b1, b0] Given two ranges, the act of consolidation between them compares the two ranges:   If one range covers all of the other then the result is that encompassing range.   If the ranges touch or intersect then the result is   one   new single range covering the overlapping ranges.   Otherwise the act of consolidation is to return the two non-touching ranges. Given   N   ranges where   N > 2   then the result is the same as repeatedly replacing all combinations of two ranges by their consolidation until no further consolidation between range pairs is possible. If   N < 2   then range consolidation has no strict meaning and the input can be returned. Example 1   Given the two ranges   [1, 2.5]   and   [3, 4.2]   then   there is no common region between the ranges and the result is the same as the input. Example 2   Given the two ranges   [1, 2.5]   and   [1.8, 4.7]   then   there is :   an overlap   [2.5, 1.8]   between the ranges and   the result is the single range   [1, 4.7].   Note that order of bounds in a range is not (yet) stated. Example 3   Given the two ranges   [6.1, 7.2]   and   [7.2, 8.3]   then   they touch at   7.2   and   the result is the single range   [6.1, 8.3]. Example 4   Given the three ranges   [1, 2]   and   [4, 8]   and   [2, 5]   then there is no intersection of the ranges   [1, 2]   and   [4, 8]   but the ranges   [1, 2]   and   [2, 5]   overlap and   consolidate to produce the range   [1, 5].   This range, in turn, overlaps the other range   [4, 8],   and   so consolidates to the final output of the single range   [1, 8]. Task Let a normalized range display show the smaller bound to the left;   and show the range with the smaller lower bound to the left of other ranges when showing multiple ranges. Output the normalized result of applying consolidation to these five sets of ranges: [1.1, 2.2] [6.1, 7.2], [7.2, 8.3] [4, 3], [2, 1] [4, 3], [2, 1], [-1, -2], [3.9, 10] [1, 3], [-6, -1], [-4, -5], [8, 2], [-6, -6] Show all output here. See also Set consolidation Set of real numbers
#zkl
zkl
fcn consolidate(rs){ (s:=List()).append( normalize(rs).reduce('wrap(ab,cd){ if(ab[1]>=cd[0]) L(ab[0],ab[1].max(cd[1])); // consolidate else{ s.append(ab); cd } // no overlap }) ) } fcn normalize(s){ s.apply("sort").sort(fcn(a,b){ a[0]<b[0] }) }
http://rosettacode.org/wiki/Reverse_a_string
Reverse a string
Task Take a string and reverse it. For example, "asdf" becomes "fdsa". Extra credit Preserve Unicode combining characters. For example, "as⃝df̅" becomes "f̅ds⃝a", not "̅fd⃝sa". Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#Pascal
Pascal
{ the result array must be at least as large as the original array } procedure reverse(s: array[min .. max: integer] of char, var result: array[min1 .. max1: integer] of char); var i, len: integer; begin len := max-min+1; for i := 0 to len-1 do result[min1 + len-1 - i] := s[min + i] end;
http://rosettacode.org/wiki/Random_number_generator_(device)
Random number generator (device)
Task If your system has a means to generate random numbers involving not only a software algorithm   (like the /dev/urandom devices in Unix),   then: show how to obtain a random 32-bit number from that mechanism. Related task Random_number_generator_(included)
#ProDOS
ProDOS
printline -random-
http://rosettacode.org/wiki/Random_number_generator_(device)
Random number generator (device)
Task If your system has a means to generate random numbers involving not only a software algorithm   (like the /dev/urandom devices in Unix),   then: show how to obtain a random 32-bit number from that mechanism. Related task Random_number_generator_(included)
#PureBasic
PureBasic
If OpenCryptRandom() MyRandom = CryptRandom(#MAXLONG) CloseCryptRandom() EndIf
http://rosettacode.org/wiki/Random_number_generator_(device)
Random number generator (device)
Task If your system has a means to generate random numbers involving not only a software algorithm   (like the /dev/urandom devices in Unix),   then: show how to obtain a random 32-bit number from that mechanism. Related task Random_number_generator_(included)
#Python
Python
import random rand = random.SystemRandom() rand.randint(1,10)
http://rosettacode.org/wiki/Random_Latin_squares
Random Latin squares
A Latin square of size n is an arrangement of n symbols in an n-by-n square in such a way that each row and column has each symbol appearing exactly once. A randomised Latin square generates random configurations of the symbols for any given n. Example n=4 randomised Latin square 0 2 3 1 2 1 0 3 3 0 1 2 1 3 2 0 Task Create a function/routine/procedure/method/... that given n generates a randomised Latin square of size n. Use the function to generate and show here, two randomly generated squares of size 5. Note Strict Uniformity in the random generation is a hard problem and not a requirement of the task. Reference Wikipedia: Latin square OEIS: A002860
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
Clear[RandomLatinSquare] RandomLatinSquare[n_] := Module[{out, ord}, out = Table[RotateLeft[Range[n], i], {i, n}]; out = RandomSample[out]; ord = RandomSample[Range[n]]; out = out[[All, ord]]; out ] RandomLatinSquare[5] // Grid
http://rosettacode.org/wiki/Random_Latin_squares
Random Latin squares
A Latin square of size n is an arrangement of n symbols in an n-by-n square in such a way that each row and column has each symbol appearing exactly once. A randomised Latin square generates random configurations of the symbols for any given n. Example n=4 randomised Latin square 0 2 3 1 2 1 0 3 3 0 1 2 1 3 2 0 Task Create a function/routine/procedure/method/... that given n generates a randomised Latin square of size n. Use the function to generate and show here, two randomly generated squares of size 5. Note Strict Uniformity in the random generation is a hard problem and not a requirement of the task. Reference Wikipedia: Latin square OEIS: A002860
#Nim
Nim
import random, sequtils, strutils   type LatinSquare = seq[seq[char]]   proc get[T](s: set[T]): T = ## Return the first element of a set. for n in s: return n   proc letterAt(n: Natural): char {.inline.} = chr(ord('A') - 1 + n)     proc latinSquare(n: Positive): LatinSquare = result = newSeqWith(n, toSeq(letterAt(1)..letterAt(n))) result[0].shuffle()   for row in 1..(n - 2): var ok = false while not ok: block shuffling: result[row].shuffle() for prev in 0..<row: for col in 0..<n: if result[row][col] == result[prev][col]: break shuffling ok = true   for col in 0..<n: var s = {letterAt(1)..letterAt(n)} for row in 0..(n - 2): s.excl result[row][col] result[^1][col] = s.get()     proc `$`(s: LatinSquare): string = let n = s.len for row in 0..<n: result.add s[row].join(" ") & '\n'     randomize() echo latinSquare(5) echo latinSquare(5) echo latinSquare(10)
http://rosettacode.org/wiki/Ray-casting_algorithm
Ray-casting algorithm
This page uses content from Wikipedia. The original article was at Point_in_polygon. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Given a point and a polygon, check if the point is inside or outside the polygon using the ray-casting algorithm. A pseudocode can be simply: count ← 0 foreach side in polygon: if ray_intersects_segment(P,side) then count ← count + 1 if is_odd(count) then return inside else return outside Where the function ray_intersects_segment return true if the horizontal ray starting from the point P intersects the side (segment), false otherwise. An intuitive explanation of why it works is that every time we cross a border, we change "country" (inside-outside, or outside-inside), but the last "country" we land on is surely outside (since the inside of the polygon is finite, while the ray continues towards infinity). So, if we crossed an odd number of borders we were surely inside, otherwise we were outside; we can follow the ray backward to see it better: starting from outside, only an odd number of crossing can give an inside: outside-inside, outside-inside-outside-inside, and so on (the - represents the crossing of a border). So the main part of the algorithm is how we determine if a ray intersects a segment. The following text explain one of the possible ways. Looking at the image on the right, we can easily be convinced of the fact that rays starting from points in the hatched area (like P1 and P2) surely do not intersect the segment AB. We also can easily see that rays starting from points in the greenish area surely intersect the segment AB (like point P3). So the problematic points are those inside the white area (the box delimited by the points A and B), like P4. Let us take into account a segment AB (the point A having y coordinate always smaller than B's y coordinate, i.e. point A is always below point B) and a point P. Let us use the cumbersome notation PAX to denote the angle between segment AP and AX, where X is always a point on the horizontal line passing by A with x coordinate bigger than the maximum between the x coordinate of A and the x coordinate of B. As explained graphically by the figures on the right, if PAX is greater than the angle BAX, then the ray starting from P intersects the segment AB. (In the images, the ray starting from PA does not intersect the segment, while the ray starting from PB in the second picture, intersects the segment). Points on the boundary or "on" a vertex are someway special and through this approach we do not obtain coherent results. They could be treated apart, but it is not necessary to do so. An algorithm for the previous speech could be (if P is a point, Px is its x coordinate): ray_intersects_segment: P : the point from which the ray starts A : the end-point of the segment with the smallest y coordinate (A must be "below" B) B : the end-point of the segment with the greatest y coordinate (B must be "above" A) if Py = Ay or Py = By then Py ← Py + ε end if if Py < Ay or Py > By then return false else if Px >= max(Ax, Bx) then return false else if Px < min(Ax, Bx) then return true else if Ax ≠ Bx then m_red ← (By - Ay)/(Bx - Ax) else m_red ← ∞ end if if Ax ≠ Px then m_blue ← (Py - Ay)/(Px - Ax) else m_blue ← ∞ end if if m_blue ≥ m_red then return true else return false end if end if end if (To avoid the "ray on vertex" problem, the point is moved upward of a small quantity   ε.)
#Raku
Raku
constant ε = 0.0001;   sub ray-hits-seg([\Px,\Py], [[\Ax,\Ay], [\Bx,\By]] --> Bool) { Py += ε if Py == Ay | By;   if Py < Ay or Py > By or Px > (Ax max Bx) { False; } elsif Px < (Ax min Bx) { True; } else { my \red = Ax == Bx ?? Inf !! (By - Ay) / (Bx - Ax); my \blue = Ax == Px ?? Inf !! (Py - Ay) / (Px - Ax); blue >= red; } }   sub point-in-poly(@point, @polygon --> Bool) { so 2 R% [+] gather for @polygon -> @side { take ray-hits-seg @point, @side.sort(*.[1]); } }   my %poly = squared => [[[ 0.0, 0.0], [10.0, 0.0]], [[10.0, 0.0], [10.0, 10.0]], [[10.0, 10.0], [ 0.0, 10.0]], [[ 0.0, 10.0], [ 0.0, 0.0]]], squaredhole => [[[ 0.0, 0.0], [10.0, 0.0]], [[10.0, 0.0], [10.0, 10.0]], [[10.0, 10.0], [ 0.0, 10.0]], [[ 0.0, 10.0], [ 0.0, 0.0]], [[ 2.5, 2.5], [ 7.5, 2.5]], [[ 7.5, 2.5], [ 7.5, 7.5]], [[ 7.5, 7.5], [ 2.5, 7.5]], [[ 2.5, 7.5], [ 2.5, 2.5]]], strange => [[[ 0.0, 0.0], [ 2.5, 2.5]], [[ 2.5, 2.5], [ 0.0, 10.0]], [[ 0.0, 10.0], [ 2.5, 7.5]], [[ 2.5, 7.5], [ 7.5, 7.5]], [[ 7.5, 7.5], [10.0, 10.0]], [[10.0, 10.0], [10.0, 0.0]], [[10.0, 0.0], [ 2.5, 2.5]], [[ 2.5, 2.5], [ 0.0, 0.0]]], # conjecturally close polygon exagon => [[[ 3.0, 0.0], [ 7.0, 0.0]], [[ 7.0, 0.0], [10.0, 5.0]], [[10.0, 5.0], [ 7.0, 10.0]], [[ 7.0, 10.0], [ 3.0, 10.0]], [[ 3.0, 10.0], [ 0.0, 5.0]], [[ 0.0, 5.0], [ 3.0, 0.0]]];   my @test-points = [ 5.0, 5.0], [ 5.0, 8.0], [-10.0, 5.0], [ 0.0, 5.0], [ 10.0, 5.0], [ 8.0, 5.0], [ 10.0, 10.0];   for <squared squaredhole strange exagon> -> $polywanna { say "$polywanna"; my @poly = %poly{$polywanna}[]; for @test-points -> @point { say "\t(@point.fmt('%.1f',','))\t{ point-in-poly(@point, @poly) ?? 'IN' !! 'OUT' }"; } }
http://rosettacode.org/wiki/Queue/Definition
Queue/Definition
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. Illustration of FIFO behavior Task Implement a FIFO queue. Elements are added at one side and popped from the other in the order of insertion. Operations:   push   (aka enqueue)    - add element   pop     (aka dequeue)    - pop first element   empty                             - return truth value when empty Errors:   handle the error of trying to pop from an empty queue (behavior depends on the language and platform) See   Queue/Usage   for the built-in FIFO or queue of your language or standard library. See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal Stack
#ALGOL_68
ALGOL 68
# -*- coding: utf-8 -*- # CO REQUIRES: MODE OBJLINK = STRUCT( REF OBJLINK next, REF OBJLINK prev, OBJVALUE value # ... etc. required # ); PROC obj link new = REF OBJLINK: ~; PROC obj link free = (REF OBJLINK free)VOID: ~ END CO   # actually a pointer to the last LINK, there ITEMs are ADDED/get # MODE OBJQUEUE = REF OBJLINK;   OBJQUEUE obj queue empty = NIL;   BOOL obj queue par = FALSE; # make code thread safe # SEMA obj queue sema = LEVEL ABS obj queue par; # Warning: 1 SEMA for all queues of type obj, i.e. not 1 SEMA per queue #   PROC obj queue init = (REF OBJQUEUE self)REF OBJQUEUE: self := obj queue empty;   PROC obj queue put = (REF OBJQUEUE self, OBJVALUE obj)REF OBJQUEUE: ( REF OBJLINK out = obj link new; IF obj queue par THEN DOWN obj queue sema FI; IF self IS obj queue empty THEN out := (out, out, obj) # self referal # ELSE # join into list # out := (self, prev OF self, obj); next OF prev OF out := prev OF next OF out := out FI; IF obj queue par THEN UP obj queue sema FI; self := out );   # define a useful prepend/put/plusto (+=:) operator... # PROC obj queue plusto = (OBJVALUE obj, REF OBJQUEUE self)OBJQUEUE: obj queue put(self,obj); OP +=: = (OBJVALUE obj, REF OBJQUEUE self)REF OBJQUEUE: obj queue put(self,obj); # a potential append/plusab (+:=) operator... OP (REF OBJQUEUE, OBJVALUE)OBJQUEUE +:= = obj queue plusab; #   # see if the program/coder wants the OBJ problem mended... # PROC (REF OBJQUEUE #self#)BOOL obj queue index error mended := (REF OBJQUEUE self)BOOL: (abend("obj queue index error"); stop);   PROC on obj queue index error = (REF OBJQUEUE self, PROC(REF OBJQUEUE #self#)BOOL mended)VOID: obj queue index error mended := mended;   PROC obj queue get = (REF OBJQUEUE self)OBJVALUE: ( # DOWN obj queue sema; # IF self IS obj queue empty THEN IF NOT obj queue index error mended(self) THEN abend("obj stack index error") FI FI; OBJQUEUE old tail = prev OF self; IF old tail IS self THEN # free solo member # self := obj queue empty ELSE # free self/tail member # OBJQUEUE new tail = prev OF old tail; next OF new tail := self; prev OF self := new tail FI; #;UP obj queue sema # OBJVALUE out = value OF old tail; # give a recovery hint to the garbage collector # obj link free(old tail); out );   PROC obj queue is empty = (REF OBJQUEUE self)BOOL: self IS obj queue empty;   SKIP
http://rosettacode.org/wiki/Quaternion_type
Quaternion type
Quaternions   are an extension of the idea of   complex numbers. A complex number has a real and complex part,   sometimes written as   a + bi, where   a   and   b   stand for real numbers, and   i   stands for the square root of minus 1. An example of a complex number might be   -3 + 2i,   where the real part,   a   is   -3.0   and the complex part,   b   is   +2.0. A quaternion has one real part and three imaginary parts,   i,   j,   and   k. A quaternion might be written as   a + bi + cj + dk. In the quaternion numbering system:   i∙i = j∙j = k∙k = i∙j∙k = -1,       or more simply,   ii  = jj  = kk  = ijk   = -1. The order of multiplication is important, as, in general, for two quaternions:   q1   and   q2:     q1q2 ≠ q2q1. An example of a quaternion might be   1 +2i +3j +4k There is a list form of notation where just the numbers are shown and the imaginary multipliers   i,   j,   and   k   are assumed by position. So the example above would be written as   (1, 2, 3, 4) Task Given the three quaternions and their components: q = (1, 2, 3, 4) = (a, b, c, d) q1 = (2, 3, 4, 5) = (a1, b1, c1, d1) q2 = (3, 4, 5, 6) = (a2, b2, c2, d2) And a wholly real number   r = 7. Create functions   (or classes)   to perform simple maths with quaternions including computing: The norm of a quaternion: = a 2 + b 2 + c 2 + d 2 {\displaystyle ={\sqrt {a^{2}+b^{2}+c^{2}+d^{2}}}} The negative of a quaternion: = (-a, -b, -c, -d) The conjugate of a quaternion: = ( a, -b, -c, -d) Addition of a real number   r   and a quaternion   q: r + q = q + r = (a+r, b, c, d) Addition of two quaternions: q1 + q2 = (a1+a2, b1+b2, c1+c2, d1+d2) Multiplication of a real number and a quaternion: qr = rq = (ar, br, cr, dr) Multiplication of two quaternions   q1   and   q2   is given by: ( a1a2 − b1b2 − c1c2 − d1d2,   a1b2 + b1a2 + c1d2 − d1c2,   a1c2 − b1d2 + c1a2 + d1b2,   a1d2 + b1c2 − c1b2 + d1a2 ) Show that, for the two quaternions   q1   and   q2: q1q2 ≠ q2q1 If a language has built-in support for quaternions, then use it. C.f.   Vector products   On Quaternions;   or on a new System of Imaginaries in Algebra.   By Sir William Rowan Hamilton LL.D, P.R.I.A., F.R.A.S., Hon. M. R. Soc. Ed. and Dub., Hon. or Corr. M. of the Royal or Imperial Academies of St. Petersburgh, Berlin, Turin and Paris, Member of the American Academy of Arts and Sciences, and of other Scientific Societies at Home and Abroad, Andrews' Prof. of Astronomy in the University of Dublin, and Royal Astronomer of Ireland.
#ALGOL_68
ALGOL 68
# -*- coding: utf-8 -*- #   COMMENT REQUIRES: MODE QUATSCAL = REAL; # Scalar # QUATSCAL quat small scal = small real; END COMMENT   # PROVIDES: # FORMAT quat scal fmt := $g(-0, 4)$; FORMAT signed fmt = $b("+", "")f(quat scal fmt)$;   FORMAT quat fmt = $f(quat scal fmt)"+"f(quat scal fmt)"i+"f(quat scal fmt)"j+"f(quat scal fmt)"k"$; FORMAT squat fmt = $f(signed fmt)f(signed fmt)"i"f(signed fmt)"j"f(signed fmt)"k"$;   MODE QUAT = STRUCT(QUATSCAL r, i, j, k); QUAT i=(0, 1, 0, 0), j=(0, 0, 1, 0), k=(0, 0, 0, 1);   MODE QUATCOSCAL = UNION(INT, SHORT REAL, SHORT INT); MODE QUATSUBSCAL = UNION(QUATCOSCAL, QUATSCAL);   MODE COMPLSCAL = STRUCT(QUATSCAL r, im); # compatable but not the same # MODE ISOQUAT = UNION([]REAL, []INT, []SHORT REAL, []SHORT INT, []QUATSCAL); MODE COQUAT = UNION(COMPLSCAL, QUATCOSCAL, ISOQUAT); MODE SUBQUAT = UNION(COQUAT, QUAT); # subset is itself #   MODE QUATERNION = QUAT;   PROC quat fix type error = (QUAT quat, []STRING msg)BOOL: ( putf(stand error, ($"Type error:"$,$" "g$, msg, quat fmt, quat, $l$)); stop );   COMMENT For a list of coercions expected in A68 c.f. * http://rosettacode.org/wiki/ALGOL_68#Coercion_.28casting.29 # ...   Pre-Strong context: Deproceduring, dereferencing & uniting. e.g. OP arguments * soft(deproceduring for assignment), * weak(dereferencing for slicing and OF selection), * meek(dereferencing for indexing, enquiries and PROC calls), * firm(uniting of OPerators), Strong context only: widening (INT=>REAL=>COMPL), rowing (REAL=>[]REAL) & voiding * strong(widening,rowing,voiding for identities/initialisations, arguments and casts et al) Key points: * arguments to OPerators do not widen or row! * UNITING is permitted in OP/String ccontext.   There are 4 principle scenerios for most operators: +---------------+-------------------------------+-------------------------------+ | OP e.g. * | SCALar | QUATernion | +---------------+-------------------------------+-------------------------------+ | SCALar | SCAL * SCAL ... inherit | SCAL * QUAT | +---------------+-------------------------------+-------------------------------+ | QUATernion | QUAT * SCAL | QUAT * QUAT | +---------------+-------------------------------+-------------------------------+ However this is compounded with SUBtypes of the SCALar & isomorphs the QUATernion, e.g. * SCAL may be a superset of SHORT REAL or INT - a widening coercion is required * QUAT may be a superset eg of COMPL or [4]INT * QUAT may be a structural isomorph eg of [4]REAL +---------------+---------------+---------------+---------------+---------------+ | OP e.g. * | SUBSCAL | SCALar | COQUAT | QUATernion | +---------------+---------------+---------------+---------------+---------------+ | SUBSCAL | | inherit | SUBSCAT*QUAT | +---------------+ inherit +---------------+---------------+ | SCALar | | inherit | SCAL * QUAT | +---------------+---------------+---------------+---------------+---------------+ | COQUAT | inherit | inherit | inherit | COQUAT*QUAT | +---------------+---------------+---------------+---------------+---------------+ | QUATernion | QUAT*SUBSCAL | QUAT*SCAL | QUAT * COQUAT | QUAT * QUAT | +---------------+---------------+---------------+---------------+---------------+ Keypoint: if an EXPLICIT QUAT is not involved, then we can simple inherit, OR QUATINIT! END COMMENT   MODE CLASSQUAT = STRUCT( PROC (REF QUAT #new#, QUATSCAL #r#, QUATSCAL #i#, QUATSCAL #j#, QUATSCAL #k#)REF QUAT new, PROC (REF QUAT #self#)QUAT conjugate, PROC (REF QUAT #self#)QUATSCAL norm sq, PROC (REF QUAT #self#)QUATSCAL norm, PROC (REF QUAT #self#)QUAT reciprocal, PROC (REF QUAT #self#)STRING repr, PROC (REF QUAT #self#)QUAT neg, PROC (REF QUAT #self#, SUBQUAT #other#)QUAT add, PROC (REF QUAT #self#, SUBQUAT #other#)QUAT radd, PROC (REF QUAT #self#, SUBQUAT #other#)QUAT sub, PROC (REF QUAT #self#, SUBQUAT #other#)QUAT mul, PROC (REF QUAT #self#, SUBQUAT #other#)QUAT rmul, PROC (REF QUAT #self#, SUBQUAT #other#)QUAT div, PROC (REF QUAT #self#, SUBQUAT #other#)QUAT rdiv, PROC (REF QUAT #self#)QUAT exp );   CLASSQUAT class quat = (   # PROC new =#(REF QUAT new, QUATSCAL r, i, j, k)REF QUAT: ( # 'Defaults all parts of quaternion to zero' # IF new ISNT REF QUAT(NIL) THEN new ELSE HEAP QUAT FI := (r, i, j, k) ),   # PROC conjugate =#(REF QUAT self)QUAT: (r OF self, -i OF self, -j OF self, -k OF self),   # PROC norm sq =#(REF QUAT self)QUATSCAL: r OF self**2 + i OF self**2 + j OF self**2 + k OF self**2,   # PROC norm =#(REF QUAT self)QUATSCAL: sqrt((norm sq OF class quat)(self)),   # PROC reciprocal =#(REF QUAT self)QUAT:( QUATSCAL n2 = (norm sq OF class quat)(self); QUAT conj = (conjugate OF class quat)(self); (r OF conj/n2, i OF conj/n2, j OF conj/n2, k OF conj/n2) ),   # PROC repr =#(REF QUAT self)STRING: ( # 'Shorter form of Quaternion as string' # FILE f; STRING s; associate(f, s); putf(f, (squat fmt, r OF self>=0, r OF self, i OF self>=0, i OF self, j OF self>=0, j OF self, k OF self>=0, k OF self)); close(f); s ),   # PROC neg =#(REF QUAT self)QUAT: (-r OF self, -i OF self, -j OF self, -k OF self),   # PROC add =#(REF QUAT self, SUBQUAT other)QUAT: CASE other IN (QUAT other): (r OF self + r OF other, i OF self + i OF other, j OF self + j OF other, k OF self + k OF other), (QUATSUBSCAL other): (r OF self + QUATSCALINIT other, i OF self, j OF self, k OF self) OUT IF quat fix type error(SKIP,"in add") THEN SKIP ELSE stop FI ESAC,   # PROC radd =#(REF QUAT self, SUBQUAT other)QUAT: (add OF class quat)(self, other),   # PROC sub =#(REF QUAT self, SUBQUAT other)QUAT: CASE other IN (QUAT other): (r OF self - r OF other, i OF self - i OF other, j OF self - j OF other, k OF self - k OF other), (QUATSCAL other): (r OF self - other, i OF self, j OF self, k OF self) OUT IF quat fix type error(self,"in sub") THEN SKIP ELSE stop FI ESAC,   # PROC mul =#(REF QUAT self, SUBQUAT other)QUAT: CASE other IN (QUAT other):( r OF self*r OF other - i OF self*i OF other - j OF self*j OF other - k OF self*k OF other, r OF self*i OF other + i OF self*r OF other + j OF self*k OF other - k OF self*j OF other, r OF self*j OF other - i OF self*k OF other + j OF self*r OF other + k OF self*i OF other, r OF self*k OF other + i OF self*j OF other - j OF self*i OF other + k OF self*r OF other ), (QUATSCAL other): ( r OF self * other, i OF self * other, j OF self * other, k OF self * other) OUT IF quat fix type error(self,"in mul") THEN SKIP ELSE stop FI ESAC,   # PROC rmul =#(REF QUAT self, SUBQUAT other)QUAT: CASE other IN (QUAT other): (mul OF class quat)(LOC QUAT := other, self), (QUATSCAL other): (mul OF class quat)(self, other) OUT IF quat fix type error(self,"in rmul") THEN SKIP ELSE stop FI ESAC,   # PROC div =#(REF QUAT self, SUBQUAT other)QUAT: CASE other IN (QUAT other): (mul OF class quat)(self, (reciprocal OF class quat)(LOC QUAT := other)), (QUATSCAL other): (mul OF class quat)(self, 1/other) OUT IF quat fix type error(self,"in div") THEN SKIP ELSE stop FI ESAC,   # PROC rdiv =#(REF QUAT self, SUBQUAT other)QUAT: CASE other IN (QUAT other): (div OF class quat)(LOC QUAT := other, self), (QUATSCAL other): (div OF class quat)(LOC QUAT := (other, 0, 0, 0), self) OUT IF quat fix type error(self,"in rdiv") THEN SKIP ELSE stop FI ESAC,   # PROC exp =#(REF QUAT self)QUAT: ( QUAT fac := self; QUAT sum := 1.0 + fac; FOR i FROM 2 TO bits width WHILE ABS(fac + quat small scal) /= quat small scal DO VOID(sum +:= (fac *:= self / ##QUATSCAL(i))) OD; sum ) );   PRIO INIT = 1; OP QUATSCALINIT = (QUATSUBSCAL scal)QUATSCAL: CASE scal IN (INT scal): scal, (SHORT INT scal): scal, (SHORT REAL scal): scal OUT IF quat fix type error(SKIP,"in QUATSCALINIT") THEN SKIP ELSE stop FI ESAC;   OP INIT = (REF QUAT new, SUBQUAT from)REF QUAT: new := CASE from IN (QUATSUBSCAL scal):(QUATSCALINIT scal, 0, 0, 0) #(COQUAT rijk):(new OF class quat)(LOC QUAT := new, rijk[1], rijk[2], rijk[3], rijk[4]),# OUT IF quat fix type error(SKIP,"in INIT") THEN SKIP ELSE stop FI ESAC;     OP QUATINIT = (COQUAT lhs)REF QUAT: (HEAP QUAT)INIT lhs;   OP + = (QUAT q)QUAT: q, - = (QUAT q)QUAT: (neg OF class quat)(LOC QUAT := q), CONJ = (QUAT q)QUAT: (conjugate OF class quat)(LOC QUAT := q), ABS = (QUAT q)QUATSCAL: (norm OF class quat)(LOC QUAT := q), REPR = (QUAT q)STRING: (repr OF class quat)(LOC QUAT := q); # missing: Diadic: I, J, K END #   OP +:= = (REF QUAT a, QUAT b)QUAT: a:=( add OF class quat)(a, b), +:= = (REF QUAT a, COQUAT b)QUAT: a:=( add OF class quat)(a, b), +=: = (QUAT a, REF QUAT b)QUAT: b:=(radd OF class quat)(b, a), +=: = (COQUAT a, REF QUAT b)QUAT: b:=(radd OF class quat)(b, a); # missing: Worthy PLUSAB, PLUSTO for SHORT/LONG INT QUATSCAL & COMPL #   OP -:= = (REF QUAT a, QUAT b)QUAT: a:=( sub OF class quat)(a, b), -:= = (REF QUAT a, COQUAT b)QUAT: a:=( sub OF class quat)(a, b); # missing: Worthy MINUSAB for SHORT/LONG INT ##COQUAT & COMPL #   PRIO *=: = 1, /=: = 1; OP *:= = (REF QUAT a, QUAT b)QUAT: a:=( mul OF class quat)(a, b), *:= = (REF QUAT a, COQUAT b)QUAT: a:=( mul OF class quat)(a, b), *=: = (QUAT a, REF QUAT b)QUAT: b:=(rmul OF class quat)(b, a), *=: = (COQUAT a, REF QUAT b)QUAT: b:=(rmul OF class quat)(b, a); # missing: Worthy TIMESAB, TIMESTO for SHORT/LONG INT ##COQUAT & COMPL #   OP /:= = (REF QUAT a, QUAT b)QUAT: a:=( div OF class quat)(a, b), /:= = (REF QUAT a, COQUAT b)QUAT: a:=( div OF class quat)(a, b), /=: = (QUAT a, REF QUAT b)QUAT: b:=(rdiv OF class quat)(b, a), /=: = (COQUAT a, REF QUAT b)QUAT: b:=(rdiv OF class quat)(b, a); # missing: Worthy OVERAB, OVERTO for SHORT/LONG INT ##COQUAT & COMPL #   OP + = (QUAT a, b)QUAT: ( add OF class quat)(LOC QUAT := a, b), + = (QUAT a, COQUAT b)QUAT: ( add OF class quat)(LOC QUAT := a, b), + = (COQUAT a, QUAT b)QUAT: (radd OF class quat)(LOC QUAT := b, a);   OP - = (QUAT a, b)QUAT: ( sub OF class quat)(LOC QUAT := a, b), - = (QUAT a, COQUAT b)QUAT: ( sub OF class quat)(LOC QUAT := a, b), - = (COQUAT a, QUAT b)QUAT:-( sub OF class quat)(LOC QUAT := b, a);   OP * = (QUAT a, b)QUAT: ( mul OF class quat)(LOC QUAT := a, b), * = (QUAT a, COQUAT b)QUAT: ( mul OF class quat)(LOC QUAT := a, b), * = (COQUAT a, QUAT b)QUAT: (rmul OF class quat)(LOC QUAT := b, a);   OP / = (QUAT a, b)QUAT: ( div OF class quat)(LOC QUAT := a, b), / = (QUAT a, COQUAT b)QUAT: ( div OF class quat)(LOC QUAT := a, b), / = (COQUAT a, QUAT b)QUAT: ( div OF class quat)(LOC QUAT := QUATINIT 1, a);   PROC quat exp = (QUAT q)QUAT: (exp OF class quat)(LOC QUAT := q);   SKIP # missing: quat arc{sin, cos, tan}h, log, exp, ln etc END #
http://rosettacode.org/wiki/Quine
Quine
A quine is a self-referential program that can, without any external access, output its own source. A   quine   (named after Willard Van Orman Quine)   is also known as:   self-reproducing automata   (1972)   self-replicating program         or   self-replicating computer program   self-reproducing program      or   self-reproducing computer program   self-copying program             or   self-copying computer program It is named after the philosopher and logician who studied self-reference and quoting in natural language, as for example in the paradox "'Yields falsehood when preceded by its quotation' yields falsehood when preceded by its quotation." "Source" has one of two meanings. It can refer to the text-based program source. For languages in which program source is represented as a data structure, "source" may refer to the data structure: quines in these languages fall into two categories: programs which print a textual representation of themselves, or expressions which evaluate to a data structure which is equivalent to that expression. The usual way to code a quine works similarly to this paradox: The program consists of two identical parts, once as plain code and once quoted in some way (for example, as a character string, or a literal data structure). The plain code then accesses the quoted code and prints it out twice, once unquoted and once with the proper quotation marks added. Often, the plain code and the quoted code have to be nested. Task Write a program that outputs its own source code in this way. If the language allows it, you may add a variant that accesses the code directly. You are not allowed to read any external files with the source code. The program should also contain some sort of self-reference, so constant expressions which return their own value which some top-level interpreter will print out. Empty programs producing no output are not allowed. There are several difficulties that one runs into when writing a quine, mostly dealing with quoting: Part of the code usually needs to be stored as a string or structural literal in the language, which needs to be quoted somehow. However, including quotation marks in the string literal itself would be troublesome because it requires them to be escaped, which then necessitates the escaping character (e.g. a backslash) in the string, which itself usually needs to be escaped, and so on. Some languages have a function for getting the "source code representation" of a string (i.e. adds quotation marks, etc.); in these languages, this can be used to circumvent the quoting problem. Another solution is to construct the quote character from its character code, without having to write the quote character itself. Then the character is inserted into the string at the appropriate places. The ASCII code for double-quote is 34, and for single-quote is 39. Newlines in the program may have to be reproduced as newlines in the string, which usually requires some kind of escape sequence (e.g. "\n"). This causes the same problem as above, where the escaping character needs to itself be escaped, etc. If the language has a way of getting the "source code representation", it usually handles the escaping of characters, so this is not a problem. Some languages allow you to have a string literal that spans multiple lines, which embeds the newlines into the string without escaping. Write the entire program on one line, for free-form languages (as you can see for some of the solutions here, they run off the edge of the screen), thus removing the need for newlines. However, this may be unacceptable as some languages require a newline at the end of the file; and otherwise it is still generally good style to have a newline at the end of a file. (The task is not clear on whether a newline is required at the end of the file.) Some languages have a print statement that appends a newline; which solves the newline-at-the-end issue; but others do not. Next to the Quines presented here, many other versions can be found on the Quine page. Related task   print itself.
#Applesoft_BASIC
Applesoft BASIC
10 LIST
http://rosettacode.org/wiki/Queue/Usage
Queue/Usage
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. Illustration of FIFO behavior Task Create a queue data structure and demonstrate its operations. (For implementations of queues, see the FIFO task.) Operations:   push       (aka enqueue) - add element   pop         (aka dequeue) - pop first element   empty     - return truth value when empty See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal Stack
#C.23
C#
using System; using System.Collections.Generic;   namespace RosettaCode { class Program { static void Main() { // Create a queue and "push" items into it Queue<int> queue = new Queue<int>(); queue.Enqueue(1); queue.Enqueue(3); queue.Enqueue(5);   // "Pop" items from the queue in FIFO order Console.WriteLine(queue.Dequeue()); // 1 Console.WriteLine(queue.Dequeue()); // 3 Console.WriteLine(queue.Dequeue()); // 5   // To tell if the queue is empty, we check the count bool empty = queue.Count == 0; Console.WriteLine(empty); // "True"   // If we try to pop from an empty queue, an exception // is thrown. try { queue.Dequeue(); } catch (InvalidOperationException exception) { Console.WriteLine(exception.Message); // "Queue empty." } } } }
http://rosettacode.org/wiki/Read_a_specific_line_from_a_file
Read a specific line from a file
Some languages have special semantics for obtaining a known line number from a file. Task Demonstrate how to obtain the contents of a specific line within a file. For the purpose of this task demonstrate how the contents of the seventh line of a file can be obtained,   and store it in a variable or in memory   (for potential future use within the program if the code were to become embedded). If the file does not contain seven lines,   or the seventh line is empty,   or too big to be retrieved,   output an appropriate message. If no special semantics are available for obtaining the required line,   it is permissible to read line by line. Note that empty lines are considered and should still be counted. Also note that for functional languages or languages without variables or storage,   it is permissible to output the extracted data to standard output.
#Ruby
Ruby
seventh_line = open("/etc/passwd").each_line.take(7).last  
http://rosettacode.org/wiki/Read_a_specific_line_from_a_file
Read a specific line from a file
Some languages have special semantics for obtaining a known line number from a file. Task Demonstrate how to obtain the contents of a specific line within a file. For the purpose of this task demonstrate how the contents of the seventh line of a file can be obtained,   and store it in a variable or in memory   (for potential future use within the program if the code were to become embedded). If the file does not contain seven lines,   or the seventh line is empty,   or too big to be retrieved,   output an appropriate message. If no special semantics are available for obtaining the required line,   it is permissible to read line by line. Note that empty lines are considered and should still be counted. Also note that for functional languages or languages without variables or storage,   it is permissible to output the extracted data to standard output.
#Run_BASIC
Run BASIC
fileName$ = "f:\sample.txt" requiredLine = 7 open fileName$ for input as #f   for i = 1 to requiredLine if not(eof(#f)) then line input #f, a$ next i close #f print a$ end
http://rosettacode.org/wiki/Quickselect_algorithm
Quickselect algorithm
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort Use the quickselect algorithm on the vector [9, 8, 7, 6, 5, 0, 1, 2, 3, 4] To show the first, second, third, ... up to the tenth largest member of the vector, in order, here on this page. Note: Quicksort has a separate task.
#CLU
CLU
quick = cluster [T: type] is select where T has lt: proctype (T,T) returns (bool) aT = array[T] sT = sequence[T] rep = null   swap = proc (list: aT, a, b: int) temp: T := list[a] list[a] := list[b] list[b] := temp end swap   partition = proc (list: aT, left, right, pivotIndex: int) returns (int) pivotValue: T := list[pivotIndex] swap(list, pivotIndex, right) storeIndex: int := left for i: int in int$from_to(left, right-1) do if list[i] < pivotValue then swap(list, storeIndex, i) storeIndex := storeIndex + 1 end end swap(list, right, storeIndex) return(storeIndex) end partition   _select = proc (list: aT, left, right, k: int) returns (T) if left = right then return(list[left]) end   pivotIndex: int := left + (right - left + 1) / 2 pivotIndex := partition(list, left, right, pivotIndex) if k = pivotIndex then return(list[k]) elseif k < pivotIndex then return(_select(list, left, pivotIndex-1, k)) else return(_select(list, pivotIndex + 1, right, k)) end end _select   select = proc (list: sT, k: int) returns (T) return(_select(sT$s2a(list), 1, sT$size(list), k)) end select end quick   start_up = proc () po: stream := stream$primary_output() vec: sequence[int] := sequence[int]$[9,8,7,6,5,0,1,2,3,4]   for k: int in int$from_to(1, 10) do item: int := quick[int]$select(vec, k) stream$putl(po, int$unparse(k) || ": " || int$unparse(item)) end end start_up
http://rosettacode.org/wiki/Ramer-Douglas-Peucker_line_simplification
Ramer-Douglas-Peucker line simplification
Ramer-Douglas-Peucker line simplification You are encouraged to solve this task according to the task description, using any language you may know. The   Ramer–Douglas–Peucker   algorithm is a line simplification algorithm for reducing the number of points used to define its shape. Task Using the   Ramer–Douglas–Peucker   algorithm, simplify the   2D   line defined by the points: (0,0) (1,0.1) (2,-0.1) (3,5) (4,6) (5,7) (6,8.1) (7,9) (8,9) (9,9) The error threshold to be used is:   1.0. Display the remaining points here. Reference   the Wikipedia article:   Ramer-Douglas-Peucker algorithm.
#Phix
Phix
with javascript_semantics function rdp(sequence l, atom e) if length(l)<2 then crash("not enough points to simplify") end if integer idx := 0 atom dMax := -1, {p1x,p1y} := l[1], {p2x,p2y} := l[$], x21 := p2x - p1x, y21 := p2y - p1y for i=1 to length(l) do atom {px,py} = l[i], d = abs(y21*px-x21*py + p2x*p1y-p2y*p1x) if d>dMax then idx = i dMax = d end if end for if dMax>e then return rdp(l[1..idx], e) & rdp(l[idx..$], e)[2..$] end if return {l[1], l[$]} end function sequence points = {{0, 0}, {1, 0.1}, {2, -0.1}, {3, 5}, {4, 6}, {5, 7}, {6, 8.1}, {7, 9}, {8, 9}, {9, 9}} ?rdp(points, 1)
http://rosettacode.org/wiki/Range_extraction
Range extraction
A format for expressing an ordered list of integers is to use a comma separated list of either individual integers Or a range of integers denoted by the starting integer separated from the end integer in the range by a dash, '-'. (The range includes all integers in the interval including both endpoints) The range syntax is to be used only for, and for every range that expands to more than two values. Example The list of integers: -6, -3, -2, -1, 0, 1, 3, 4, 5, 7, 8, 9, 10, 11, 14, 15, 17, 18, 19, 20 Is accurately expressed by the range expression: -6,-3-1,3-5,7-11,14,15,17-20 (And vice-versa). Task Create a function that takes a list of integers in increasing order and returns a correctly formatted string in the range format. Use the function to compute and print the range formatted version of the following ordered list of integers. (The correct answer is: 0-2,4,6-8,11,12,14-25,27-33,35-39). 0, 1, 2, 4, 6, 7, 8, 11, 12, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 27, 28, 29, 30, 31, 32, 33, 35, 36, 37, 38, 39 Show the output of your program. Related task   Range expansion
#D
D
import std.stdio, std.conv, std.string, std.algorithm, std.range;   string rangeExtraction(in int[] items) in { assert(items.isSorted); } body { if (items.empty) return null; auto ranges = [[items[0].text]];   foreach (immutable x, immutable y; items.zip(items[1 .. $])) if (x + 1 == y) ranges[$ - 1] ~= y.text; else ranges ~= [y.text];   return ranges .map!(r => r.length > 2 ? r[0] ~ "-" ~ r.back : r.join(',')) .join(','); }   void main() { foreach (data; [[-8, -7, -6, -3, -2, -1, 0, 1, 3, 4, 5, 7, 8, 9, 10, 11, 14, 15, 17, 18, 19, 20], [0, 0, 0, 1, 1], [0, 1, 2, 4, 6, 7, 8, 11, 12, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 27, 28, 29, 30, 31, 32, 33, 35, 36, 37, 38, 39]]) data.rangeExtraction.writeln; }
http://rosettacode.org/wiki/Random_numbers
Random numbers
Task Generate a collection filled with   1000   normally distributed random (or pseudo-random) numbers with a mean of   1.0   and a   standard deviation   of   0.5 Many libraries only generate uniformly distributed random numbers. If so, you may use one of these algorithms. Related task   Standard deviation
#Falcon
Falcon
a = [] for i in [0:1000] : a+= norm_rand_num()   function norm_rand_num() pi = 2*acos(0) return 1 + (cos(2 * pi * random()) * pow(-2 * log(random()) ,1/2)) /2 end
http://rosettacode.org/wiki/Random_number_generator_(included)
Random number generator (included)
The task is to: State the type of random number generator algorithm used in a language's built-in random number generator. If the language or its immediate libraries don't provide a random number generator, skip this task. If possible, give a link to a wider explanation of the algorithm used. Note: the task is not to create an RNG, but to report on the languages in-built RNG that would be the most likely RNG used. The main types of pseudo-random number generator (PRNG) that are in use are the Linear Congruential Generator (LCG), and the Generalized Feedback Shift Register (GFSR), (of which the Mersenne twister generator is a subclass). The last main type is where the output of one of the previous ones (typically a Mersenne twister) is fed through a cryptographic hash function to maximize unpredictability of individual bits. Note that neither LCGs nor GFSRs should be used for the most demanding applications (cryptography) without additional steps.
#Modula-3
Modula-3
setrand(3) random(6)+1 \\ chosen by fair dice roll. \\ guaranteed to the random.
http://rosettacode.org/wiki/Random_number_generator_(included)
Random number generator (included)
The task is to: State the type of random number generator algorithm used in a language's built-in random number generator. If the language or its immediate libraries don't provide a random number generator, skip this task. If possible, give a link to a wider explanation of the algorithm used. Note: the task is not to create an RNG, but to report on the languages in-built RNG that would be the most likely RNG used. The main types of pseudo-random number generator (PRNG) that are in use are the Linear Congruential Generator (LCG), and the Generalized Feedback Shift Register (GFSR), (of which the Mersenne twister generator is a subclass). The last main type is where the output of one of the previous ones (typically a Mersenne twister) is fed through a cryptographic hash function to maximize unpredictability of individual bits. Note that neither LCGs nor GFSRs should be used for the most demanding applications (cryptography) without additional steps.
#Nanoquery
Nanoquery
setrand(3) random(6)+1 \\ chosen by fair dice roll. \\ guaranteed to the random.
http://rosettacode.org/wiki/Random_number_generator_(included)
Random number generator (included)
The task is to: State the type of random number generator algorithm used in a language's built-in random number generator. If the language or its immediate libraries don't provide a random number generator, skip this task. If possible, give a link to a wider explanation of the algorithm used. Note: the task is not to create an RNG, but to report on the languages in-built RNG that would be the most likely RNG used. The main types of pseudo-random number generator (PRNG) that are in use are the Linear Congruential Generator (LCG), and the Generalized Feedback Shift Register (GFSR), (of which the Mersenne twister generator is a subclass). The last main type is where the output of one of the previous ones (typically a Mersenne twister) is fed through a cryptographic hash function to maximize unpredictability of individual bits. Note that neither LCGs nor GFSRs should be used for the most demanding applications (cryptography) without additional steps.
#Nemerle
Nemerle
setrand(3) random(6)+1 \\ chosen by fair dice roll. \\ guaranteed to the random.
http://rosettacode.org/wiki/Random_number_generator_(included)
Random number generator (included)
The task is to: State the type of random number generator algorithm used in a language's built-in random number generator. If the language or its immediate libraries don't provide a random number generator, skip this task. If possible, give a link to a wider explanation of the algorithm used. Note: the task is not to create an RNG, but to report on the languages in-built RNG that would be the most likely RNG used. The main types of pseudo-random number generator (PRNG) that are in use are the Linear Congruential Generator (LCG), and the Generalized Feedback Shift Register (GFSR), (of which the Mersenne twister generator is a subclass). The last main type is where the output of one of the previous ones (typically a Mersenne twister) is fed through a cryptographic hash function to maximize unpredictability of individual bits. Note that neither LCGs nor GFSRs should be used for the most demanding applications (cryptography) without additional steps.
#NetRexx
NetRexx
setrand(3) random(6)+1 \\ chosen by fair dice roll. \\ guaranteed to the random.
http://rosettacode.org/wiki/Read_a_configuration_file
Read a configuration file
The task is to read a configuration file in standard configuration file format, and set variables accordingly. For this task, we have a configuration file as follows: # This is a configuration file in standard configuration file format # # Lines beginning with a hash or a semicolon are ignored by the application # program. Blank lines are also ignored by the application program. # This is the fullname parameter FULLNAME Foo Barber # This is a favourite fruit FAVOURITEFRUIT banana # This is a boolean that should be set NEEDSPEELING # This boolean is commented out ; SEEDSREMOVED # Configuration option names are not case sensitive, but configuration parameter # data is case sensitive and may be preserved by the application program. # An optional equals sign can be used to separate configuration parameter data # from the option name. This is dropped by the parser. # A configuration option may take multiple parameters separated by commas. # Leading and trailing whitespace around parameter names and parameter data fields # are ignored by the application program. OTHERFAMILY Rhu Barber, Harry Barber For the task we need to set four variables according to the configuration entries as follows: fullname = Foo Barber favouritefruit = banana needspeeling = true seedsremoved = false We also have an option that contains multiple parameters. These may be stored in an array. otherfamily(1) = Rhu Barber otherfamily(2) = Harry Barber Related tasks Update a configuration file
#Groovy
Groovy
def config = [:] def loadConfig = { File file -> String regex = /^(;{0,1})\s*(\S+)\s*(.*)$/ file.eachLine { line -> (line =~ regex).each { matcher, invert, key, value -> if (key == '' || key.startsWith("#")) return parts = value ? value.split(/\s*,\s*/) : (invert ? [false] : [true]) if (parts.size() > 1) { parts.eachWithIndex{ part, int i -> config["$key(${i + 1})"] = part} } else { config[key] = parts[0] } } } }
http://rosettacode.org/wiki/Rare_numbers
Rare numbers
Definitions and restrictions Rare   numbers are positive integers   n   where:   n   is expressed in base ten   r   is the reverse of   n     (decimal digits)   n   must be non-palindromic   (n ≠ r)   (n+r)   is the   sum   (n-r)   is the   difference   and must be positive   the   sum   and the   difference   must be perfect squares Task   find and show the first   5   rare   numbers   find and show the first   8   rare   numbers       (optional)   find and show more   rare   numbers                (stretch goal) Show all output here, on this page. References   an   OEIS   entry:   A035519          rare numbers.   an   OEIS   entry:   A059755   odd rare numbers.   planetmath entry:   rare numbers.     (some hints)   author's  website:   rare numbers   by Shyam Sunder Gupta.     (lots of hints and some observations).
#Ruby
Ruby
Term = Struct.new(:coeff, :ix1, :ix2) do end   MAX_DIGITS = 16   def toLong(digits, reverse) sum = 0 if reverse then i = digits.length - 1 while i >=0 sum = sum *10 + digits[i] i = i - 1 end else i = 0 while i < digits.length sum = sum * 10 + digits[i] i = i + 1 end end return sum end   def isSquare(n) root = Math.sqrt(n).to_i return root * root == n end   def seq(from, to, step) res = [] i = from while i <= to res << i i = i + step end return res end   def format_number(number) number.to_s.reverse.gsub(/(\d{3})(?=\d)/, '\\1,').reverse end   def main pow = 1 allTerms = [] for i in 0 .. MAX_DIGITS - 2 allTerms << [] end for r in 2 .. MAX_DIGITS terms = [] pow = pow * 10 pow1 = pow pow2 = 1 i1 = 0 i2 = r - 1 while i1 < i2 terms << Term.new(pow1 - pow2, i1, i2) pow1 = (pow1 / 10).to_i pow2 = pow2 * 10 i1 = i1 + 1 i2 = i2 - 1 end allTerms[r - 2] = terms end # map of first minus last digits for 'n' to pairs giving this value fml = { 0 =>[[2, 2], [8, 8]], 1 =>[[6, 5], [8, 7]], 4 =>[[4, 0]], 6 =>[[6, 0], [8, 2]] } # map of other digit differences for 'n' to pairs giving this value dmd = {} for i in 0 .. 99 a = [(i / 10).to_i, (i % 10)] d = a[0] - a[1] if dmd.include?(d) then dmd[d] << a else dmd[d] = [a] end end fl = [0, 1, 4, 6] dl = seq(-9, 9, 1) # all differences zl = [0] # zero differences only el = seq(-8, 8, 2) # even differences ol = seq(-9, 9, 2) # odd differences only il = seq(0, 9, 1) rares = [] lists = [] for i in 0 .. 3 lists << [] end fl.each_with_index { |f, i| lists[i] = [[f]] } digits = [] count = 0   # Recursive closure to generate (n+r) candidates from (n-r) candidates # and hence find Rare numbers with a given number of digits. fnpr = lambda { |cand, di, dis, indices, nmr, nd, level| if level == dis.length then digits[indices[0][0]] = fml[cand[0]][di[0]][0] digits[indices[0][1]] = fml[cand[0]][di[0]][1] le = di.length if nd % 2 == 1 then le = le - 1 digits[(nd / 2).to_i] = di[le] end di[1 .. le - 1].each_with_index { |d, i| digits[indices[i + 1][0]] = dmd[cand[i + 1]][d][0] digits[indices[i + 1][1]] = dmd[cand[i + 1]][d][1] } r = toLong(digits, true) npr = nmr + 2 * r if not isSquare(npr) then return end count = count + 1 print " R/N %2d:" % [count] n = toLong(digits, false) print " (%s)\n" % [format_number(n)] rares << n else for num in dis[level] di[level] = num fnpr.call(cand, di, dis, indices, nmr, nd, level + 1) end end }   # Recursive closure to generate (n-r) candidates with a given number of digits. fnmr = lambda { |cand, list, indices, nd, level| if level == list.length then nmr = 0 nmr2 = 0 allTerms[nd - 2].each_with_index { |t, i| if cand[i] >= 0 then nmr = nmr + t.coeff * cand[i] else nmr2 = nmr2 = t.coeff * -cand[i] if nmr >= nmr2 then nmr = nmr - nmr2 nmr2 = 0 else nmr2 = nmr2 - nmr nmr = 0 end end } if nmr2 >= nmr then return end nmr = nmr - nmr2 if not isSquare(nmr) then return end dis = [] dis << seq(0, fml[cand[0]].length - 1, 1) for i in 1 .. cand.length - 1 dis << seq(0, dmd[cand[i]].length - 1, 1) end if nd % 2 == 1 then dis << il.dup end di = [] for i in 0 .. dis.length - 1 di << 0 end fnpr.call(cand, di, dis, indices, nmr, nd, 0) else for num in list[level] cand[level] = num fnmr.call(cand, list, indices, nd, level + 1) end end }   #for nd in 2 .. MAX_DIGITS - 1 for nd in 2 .. 10 digits = [] for i in 0 .. nd - 1 digits << 0 end if nd == 4 then lists[0] << zl.dup lists[1] << ol.dup lists[2] << el.dup lists[3] << ol.dup elsif allTerms[nd - 2].length > lists[0].length then for i in 0 .. 3 lists[i] << dl.dup end end indices = [] for t in allTerms[nd - 2] indices << [t.ix1, t.ix2] end for list in lists cand = [] for i in 0 .. list.length - 1 cand << 0 end fnmr.call(cand, list, indices, nd, 0) end print "  %2d digits\n" % [nd] end   rares.sort() print "\nThe rare numbers with up to %d digits are:\n" % [MAX_DIGITS] rares.each_with_index { |rare, i| print "  %2d:  %25s\n" % [i + 1, format_number(rare)] } end   main()
http://rosettacode.org/wiki/Range_expansion
Range expansion
A format for expressing an ordered list of integers is to use a comma separated list of either individual integers Or a range of integers denoted by the starting integer separated from the end integer in the range by a dash, '-'. (The range includes all integers in the interval including both endpoints) The range syntax is to be used only for, and for every range that expands to more than two values. Example The list of integers: -6, -3, -2, -1, 0, 1, 3, 4, 5, 7, 8, 9, 10, 11, 14, 15, 17, 18, 19, 20 Is accurately expressed by the range expression: -6,-3-1,3-5,7-11,14,15,17-20 (And vice-versa). Task Expand the range description: -6,-3--1,3-5,7-11,14,15,17-20 Note that the second element above, is the range from minus 3 to minus 1. Related task   Range extraction
#Dyalect
Dyalect
func main() { let input = "-6,-3--1,3-5,7-11,14,15,17-20" print("range: \(input)") var r = [] var last = 0 for part in input.Split(',') { var i = part[1..].IndexOf('-') if i == -1 { var n = Integer(part) if r.Length() > 0 { return print("duplicate value: \(n)") when last == n return print("values not ordered: \(last) > \(n)") when last > n } r.Add(n) last = n } else { var n1 = Integer(part[..i]) var n2 = Integer(part[(i + 2)..]) return print("invalid range: \(part)") when n2 < n1 + 2   if r.Length() > 0 { return print("duplicate value: \(n1)") when last == n1 return print("values not ordered: \(last) > \(n1)") when last > n1 }   for i in n1..n2 { r.Add(i) } last = n2 } }   print("expanded: \(r)") }   main()
http://rosettacode.org/wiki/Range_expansion
Range expansion
A format for expressing an ordered list of integers is to use a comma separated list of either individual integers Or a range of integers denoted by the starting integer separated from the end integer in the range by a dash, '-'. (The range includes all integers in the interval including both endpoints) The range syntax is to be used only for, and for every range that expands to more than two values. Example The list of integers: -6, -3, -2, -1, 0, 1, 3, 4, 5, 7, 8, 9, 10, 11, 14, 15, 17, 18, 19, 20 Is accurately expressed by the range expression: -6,-3-1,3-5,7-11,14,15,17-20 (And vice-versa). Task Expand the range description: -6,-3--1,3-5,7-11,14,15,17-20 Note that the second element above, is the range from minus 3 to minus 1. Related task   Range extraction
#EchoLisp
EchoLisp
  ;; parsing [spaces][-]digit(s)-[-]digit(s)[spaces] (define R (make-regexp "^ *(\-?\\d+)\-(\-?\\d+) *$" ))   ;; the native (range a b) is [a ... b[ ;; (range+ a b) is [a ... b] (define (range+ a b) (if (< a b) (range a (1+ b)) (if (> a b) (range a (1- b) -1) (list a))))   ;; in : string : "number" or "number-number" ;; out : a range = list of integer(s) (define (do-range str) (define from-to (regexp-exec R str)) ;; "1-3" --> ("1" "3") (if from-to (range+ (string->number (first from-to)) (string->number (second from-to))) (list (string->number str))))   (define (ranges str) (apply append (map do-range (string-split str ","))))     (define task "-6,-3--1,3-5,7-11,14,15,17-20") (ranges task) → (-6 -3 -2 -1 3 4 5 7 8 9 10 11 14 15 17 18 19 20)  
http://rosettacode.org/wiki/Read_a_file_line_by_line
Read a file line by line
Read a file one line at a time, as opposed to reading the entire file at once. Related tasks Read a file character by character Input loop.
#Erlang
Erlang
  -module( read_a_file_line_by_line ).   -export( [into_list/1] ).   into_list( File ) -> {ok, IO} = file:open( File, [read] ), into_list( io:get_line(IO, ''), IO, [] ).     into_list( eof, _IO, Acc ) -> lists:reverse( Acc ); into_list( {error, _Error}, _IO, Acc ) -> lists:reverse( Acc ); into_list( Line, IO, Acc ) -> into_list( io:get_line(IO, ''), IO, [Line | Acc] ).  
http://rosettacode.org/wiki/Ranking_methods
Ranking methods
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort The numerical rank of competitors in a competition shows if one is better than, equal to, or worse than another based on their results in a competition. The numerical rank of a competitor can be assigned in several different ways. Task The following scores are accrued for all competitors of a competition (in best-first order): 44 Solomon 42 Jason 42 Errol 41 Garry 41 Bernard 41 Barry 39 Stephen For each of the following ranking methods, create a function/method/procedure/subroutine... that applies the ranking method to an ordered list of scores with scorers: Standard. (Ties share what would have been their first ordinal number). Modified. (Ties share what would have been their last ordinal number). Dense. (Ties share the next available integer). Ordinal. ((Competitors take the next available integer. Ties are not treated otherwise). Fractional. (Ties share the mean of what would have been their ordinal numbers). See the wikipedia article for a fuller description. Show here, on this page, the ranking of the test scores under each of the numbered ranking methods.
#PowerShell
PowerShell
  function Get-Ranking { [CmdletBinding(DefaultParameterSetName="Standard")] [OutputType([PSCustomObject])] Param ( [Parameter(Mandatory=$true, ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true, Position=0)] [string] $InputObject,   [Parameter(Mandatory=$false, ParameterSetName="Standard")] [switch] $Standard,   [Parameter(Mandatory=$false, ParameterSetName="Modified")] [switch] $Modified,   [Parameter(Mandatory=$false, ParameterSetName="Dense")] [switch] $Dense,   [Parameter(Mandatory=$false, ParameterSetName="Ordinal")] [switch] $Ordinal,   [Parameter(Mandatory=$false, ParameterSetName="Fractional")] [switch] $Fractional )   Begin { function Get-OrdinalRank ([PSCustomObject[]]$Values) { for ($i = 0; $i -lt $Values.Count; $i++) { $Values[$i].Rank = $i + 1 }   $Values }   function Get-Rank ([PSCustomObject[]]$Scores) { foreach ($score in $Scores) { $score.Group | ForEach-Object {$_.Rank = $score.Rank} }   $Scores.Group }   function New-Competitor ([string]$Name, [int]$Score, [int]$Rank = 0) { [PSCustomObject]@{ Name = $Name Score = $Score Rank = $Rank } }   $competitors = @() $scores = @() } Process { @($input) | ForEach-Object {$competitors += New-Competitor -Name $_.Split()[1] -Score $_.Split()[0]} } End { $scores = $competitors | Sort-Object -Property Score -Descending | Group-Object -Property Score | Select-Object -Property @{Name="Score"; Expression={[int]$_.Name}}, @{Name="Rank"; Expression={0}}, Count, Group   switch ($PSCmdlet.ParameterSetName) { "Standard" { $rank = 1   for ($i = 0; $i -lt $scores.Count; $i++) { $scores[$i].Rank = $rank $rank += $scores[$i].Count }   Get-Rank $scores } "Modified" { $rank = 0   foreach ($score in $scores) { $rank = $score.Count + $rank $score.Rank = $rank }   Get-Rank $scores } "Dense" { for ($i = 0; $i -lt $scores.Count; $i++) { $scores[$i].Rank = $i + 1 }   Get-Rank $scores } "Ordinal" { Get-OrdinalRank $competitors } "Fractional" { Get-OrdinalRank $competitors | Group-Object -Property Score | ForEach-Object { if ($_.Count -gt 1) { $rank = ($_.Group.Rank | Measure-Object -Average).Average   foreach ($competitor in $_.Group) { $competitor.Rank = $rank } } }   $competitors } } } }  
http://rosettacode.org/wiki/Reverse_a_string
Reverse a string
Task Take a string and reverse it. For example, "asdf" becomes "fdsa". Extra credit Preserve Unicode combining characters. For example, "as⃝df̅" becomes "f̅ds⃝a", not "̅fd⃝sa". 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
#Peloton
Peloton
<# 显示 指定 变量 反转顺序 字串>集装箱|猫坐在垫子</#>
http://rosettacode.org/wiki/Random_number_generator_(device)
Random number generator (device)
Task If your system has a means to generate random numbers involving not only a software algorithm   (like the /dev/urandom devices in Unix),   then: show how to obtain a random 32-bit number from that mechanism. Related task Random_number_generator_(included)
#Racket
Racket
  #lang racket ;; Assuming a device to provide random bits: (call-with-input-file* "/dev/random" (λ(i) (integer-bytes->integer (read-bytes 4 i) #f)))  
http://rosettacode.org/wiki/Random_number_generator_(device)
Random number generator (device)
Task If your system has a means to generate random numbers involving not only a software algorithm   (like the /dev/urandom devices in Unix),   then: show how to obtain a random 32-bit number from that mechanism. Related task Random_number_generator_(included)
#Raku
Raku
use experimental :pack; my $UR = open("/dev/urandom", :bin) orelse .die; my @random-spigot = $UR.read(1024).unpack("L*") ... *;   .say for @random-spigot[^10];
http://rosettacode.org/wiki/Random_number_generator_(device)
Random number generator (device)
Task If your system has a means to generate random numbers involving not only a software algorithm   (like the /dev/urandom devices in Unix),   then: show how to obtain a random 32-bit number from that mechanism. Related task Random_number_generator_(included)
#REXX
REXX
/*REXX program generates and displays a random 32-bit number using the RANDOM BIF.*/ numeric digits 10 /*ensure REXX has enough decimal digits*/ _=2**16 /*a handy─dandy constant to have around*/ r#= random(0, _-1) * _ + random(0, _-1) /*generate an unsigned 32-bit random #.*/ say r# /*stick a fork in it, we're all done. */
http://rosettacode.org/wiki/Random_Latin_squares
Random Latin squares
A Latin square of size n is an arrangement of n symbols in an n-by-n square in such a way that each row and column has each symbol appearing exactly once. A randomised Latin square generates random configurations of the symbols for any given n. Example n=4 randomised Latin square 0 2 3 1 2 1 0 3 3 0 1 2 1 3 2 0 Task Create a function/routine/procedure/method/... that given n generates a randomised Latin square of size n. Use the function to generate and show here, two randomly generated squares of size 5. Note Strict Uniformity in the random generation is a hard problem and not a requirement of the task. Reference Wikipedia: Latin square OEIS: A002860
#Perl
Perl
use strict; use warnings; use feature 'say'; use List::Util 'shuffle';   sub random_ls { my($n) = @_; my(@cols,@symbols,@ls_sym);   # build n-sized latin square my @ls = [0,]; for my $i (1..$n-1) { @{$ls[$i]} = @{$ls[0]}; splice(@{$ls[$_]}, $_, 0, $i) for 0..$i; }   # shuffle rows and columns @cols = shuffle 0..$n-1; @ls = map [ @{$_}[@cols] ], @ls[shuffle 0..$n-1];   # replace numbers with symbols @symbols = shuffle( ('A'..'Z')[0..$n-1] ); push @ls_sym, [@symbols[@$_]] for @ls; @ls_sym }   sub display { my $str; $str .= join(' ', @$_) . "\n" for @_; $str }   say display random_ls($_) for 2..5, 5;
http://rosettacode.org/wiki/Ray-casting_algorithm
Ray-casting algorithm
This page uses content from Wikipedia. The original article was at Point_in_polygon. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Given a point and a polygon, check if the point is inside or outside the polygon using the ray-casting algorithm. A pseudocode can be simply: count ← 0 foreach side in polygon: if ray_intersects_segment(P,side) then count ← count + 1 if is_odd(count) then return inside else return outside Where the function ray_intersects_segment return true if the horizontal ray starting from the point P intersects the side (segment), false otherwise. An intuitive explanation of why it works is that every time we cross a border, we change "country" (inside-outside, or outside-inside), but the last "country" we land on is surely outside (since the inside of the polygon is finite, while the ray continues towards infinity). So, if we crossed an odd number of borders we were surely inside, otherwise we were outside; we can follow the ray backward to see it better: starting from outside, only an odd number of crossing can give an inside: outside-inside, outside-inside-outside-inside, and so on (the - represents the crossing of a border). So the main part of the algorithm is how we determine if a ray intersects a segment. The following text explain one of the possible ways. Looking at the image on the right, we can easily be convinced of the fact that rays starting from points in the hatched area (like P1 and P2) surely do not intersect the segment AB. We also can easily see that rays starting from points in the greenish area surely intersect the segment AB (like point P3). So the problematic points are those inside the white area (the box delimited by the points A and B), like P4. Let us take into account a segment AB (the point A having y coordinate always smaller than B's y coordinate, i.e. point A is always below point B) and a point P. Let us use the cumbersome notation PAX to denote the angle between segment AP and AX, where X is always a point on the horizontal line passing by A with x coordinate bigger than the maximum between the x coordinate of A and the x coordinate of B. As explained graphically by the figures on the right, if PAX is greater than the angle BAX, then the ray starting from P intersects the segment AB. (In the images, the ray starting from PA does not intersect the segment, while the ray starting from PB in the second picture, intersects the segment). Points on the boundary or "on" a vertex are someway special and through this approach we do not obtain coherent results. They could be treated apart, but it is not necessary to do so. An algorithm for the previous speech could be (if P is a point, Px is its x coordinate): ray_intersects_segment: P : the point from which the ray starts A : the end-point of the segment with the smallest y coordinate (A must be "below" B) B : the end-point of the segment with the greatest y coordinate (B must be "above" A) if Py = Ay or Py = By then Py ← Py + ε end if if Py < Ay or Py > By then return false else if Px >= max(Ax, Bx) then return false else if Px < min(Ax, Bx) then return true else if Ax ≠ Bx then m_red ← (By - Ay)/(Bx - Ax) else m_red ← ∞ end if if Ax ≠ Px then m_blue ← (Py - Ay)/(Px - Ax) else m_blue ← ∞ end if if m_blue ≥ m_red then return true else return false end if end if end if (To avoid the "ray on vertex" problem, the point is moved upward of a small quantity   ε.)
#REXX
REXX
/*REXX program verifies if a horizontal ray from point P intersects a polygon. */ call points 5 5, 5 8, -10 5, 0 5, 10 5, 8 5, 10 10 A= 2.5; B= 7.5 /* ◄───── used for shorter arguments (below).*/ call poly 0 0, 10 0, 10 10, 0 10  ; call test 'square' call poly 0 0, 10 0, 10 10, 0 10, A A, B A, B B, A B ; call test 'square hole' call poly 0 0, A A, 0 10, A B, B B, 10 10, 10 0  ; call test 'irregular' call poly 3 0, 7 0, 10 5, 7 10, 3 10, 0 5  ; call test 'hexagon' exit 0 /*stick a fork in it, we're all done. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ in$out: procedure expose point. poly.; parse arg p; #= 0 do side=1 to poly.0 by 2; #= # +intersect(p, side); end /*side*/ return # // 2 /*ODD is inside. EVEN is outside.*/ /*──────────────────────────────────────────────────────────────────────────────────────*/ intersect: procedure expose point. poly.; parse arg ?,s; sp= s + 1 epsilon= '1e' || (-digits() % 2) Px= point.?.x; Ax= poly.s.x; Bx= poly.sp.x Py= point.?.y; Ay= poly.s.y; By= poly.sp.y /* [↓] do vertex swap.*/ if Ay>By then parse value Ax Ay Bx By with Bx By Ax Ay if Py=Ay | Py=By then Py= Py + epsilon if Py<Ay | Py>By | Px>max(Ax, Bx) then return 0 if Px<min(Ax, Bx) then return 1 if Ax\=Bx then red = (By-Ay) / (Bx-Ax) else red = i"1e" || (digits() *2) /* ◄─── infinity.*/ if Ax\=Px then return (Py-Ay) / (Px-Ax) >= red else return 1 /*──────────────────────────────────────────────────────────────────────────────────────*/ points: wx= 0; wy= 0; do j=1 for arg(); parse value arg(j) with xx yy wx= max(wx, length(xx) ); call value 'POINT.'j".X", xx wy= max(wy, length(yy) ); call value 'POINT.'j".Y", yy end /*j*/ call value point.0, j-1 /*define the number of points. */ return /* [↑] adjust J (for DO loop)*/ /*──────────────────────────────────────────────────────────────────────────────────────*/ poly: @= 'POLY.'; parse arg Fx Fy /* [↓] process the X,Y points.*/ n= 0 do j=1 for arg(); n= n + 1; parse value arg(j) with xx yy call value @ || n'.X', xx ; call value @ || n".Y", yy if n//2 then iterate; n= n + 1 /*Inside? Then skip this point.*/ call value @ || n'.X', xx ; call value @ || n".Y", yy end /*j*/ n= n + 1 /*POLY.0 is # segments(sides).*/ call value @ || n'.X', Fx; call value @ || n".Y", Fy; call value @'0', n return /*──────────────────────────────────────────────────────────────────────────────────────*/ test: say; do k=1 for point.0; w= wx + wy + 2 /*W, WX, WY ≡are various widths*/ say right(' ['arg(1)"] point:", 30), right( right(point.k.x, wx)', 'right(point.k.y, wy), w) " is ", right( word('outside inside', in$out(k) + 1), 7) end /*k*/ return /* [↑] format the output nicely*/
http://rosettacode.org/wiki/Queue/Definition
Queue/Definition
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. Illustration of FIFO behavior Task Implement a FIFO queue. Elements are added at one side and popped from the other in the order of insertion. Operations:   push   (aka enqueue)    - add element   pop     (aka dequeue)    - pop first element   empty                             - return truth value when empty Errors:   handle the error of trying to pop from an empty queue (behavior depends on the language and platform) See   Queue/Usage   for the built-in FIFO or queue of your language or standard library. See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal Stack
#ALGOL_W
ALGOL W
begin  % define a Queue type that will hold StringQueueElements % record StringQueue ( reference(StringQueueElement) front, back );  % define the StringQueueElement type % record StringQueueElement ( string(8) element  ; reference(StringQueueElement) next );  % we would need separate types for other element types  %  % adds s to the end of the StringQueue q  % procedure pushString ( reference(StringQueue) value q  ; string(8) value e ) ; begin reference(StringQueueElement) newElement; newElement := StringQueueElement( e, null ); if front(q) = null then begin  % adding to an empty queue % front(q) := newElement; back(q)  := newElement end else begin  % the queue is not empty % next(back(q)) := newElement; back(q)  := newElement end end pushString ;  % removes an element from the front of the StringQueue q %  % asserts the queue is not empty, which will stop the  %  % program if it is  % string(8) procedure popString ( reference(StringQueue) value q ) ; begin string(8) v; assert( not isEmptyStringQueue( q ) ); v  := element(front(q)); front(q) := next(front(q)); if front(q) = null then % just popped the last element % back(q) := null; v end popStringQueue ;  % returns true if the StringQueue q is empty, false otherwise % logical procedure isEmptyStringQueue ( reference(StringQueue) value q ) ; front(q) = null;   begin % test the StringQueue operations % reference(StringQueue) q; q := StringQueue( null, null ); pushString( q, "fred" ); pushString( q, "whilma" ); pushString( q, "betty" ); pushString( q, "barney" ); while not isEmptyStringQueue( q ) do write( popString( q ) ) end end.
http://rosettacode.org/wiki/Quaternion_type
Quaternion type
Quaternions   are an extension of the idea of   complex numbers. A complex number has a real and complex part,   sometimes written as   a + bi, where   a   and   b   stand for real numbers, and   i   stands for the square root of minus 1. An example of a complex number might be   -3 + 2i,   where the real part,   a   is   -3.0   and the complex part,   b   is   +2.0. A quaternion has one real part and three imaginary parts,   i,   j,   and   k. A quaternion might be written as   a + bi + cj + dk. In the quaternion numbering system:   i∙i = j∙j = k∙k = i∙j∙k = -1,       or more simply,   ii  = jj  = kk  = ijk   = -1. The order of multiplication is important, as, in general, for two quaternions:   q1   and   q2:     q1q2 ≠ q2q1. An example of a quaternion might be   1 +2i +3j +4k There is a list form of notation where just the numbers are shown and the imaginary multipliers   i,   j,   and   k   are assumed by position. So the example above would be written as   (1, 2, 3, 4) Task Given the three quaternions and their components: q = (1, 2, 3, 4) = (a, b, c, d) q1 = (2, 3, 4, 5) = (a1, b1, c1, d1) q2 = (3, 4, 5, 6) = (a2, b2, c2, d2) And a wholly real number   r = 7. Create functions   (or classes)   to perform simple maths with quaternions including computing: The norm of a quaternion: = a 2 + b 2 + c 2 + d 2 {\displaystyle ={\sqrt {a^{2}+b^{2}+c^{2}+d^{2}}}} The negative of a quaternion: = (-a, -b, -c, -d) The conjugate of a quaternion: = ( a, -b, -c, -d) Addition of a real number   r   and a quaternion   q: r + q = q + r = (a+r, b, c, d) Addition of two quaternions: q1 + q2 = (a1+a2, b1+b2, c1+c2, d1+d2) Multiplication of a real number and a quaternion: qr = rq = (ar, br, cr, dr) Multiplication of two quaternions   q1   and   q2   is given by: ( a1a2 − b1b2 − c1c2 − d1d2,   a1b2 + b1a2 + c1d2 − d1c2,   a1c2 − b1d2 + c1a2 + d1b2,   a1d2 + b1c2 − c1b2 + d1a2 ) Show that, for the two quaternions   q1   and   q2: q1q2 ≠ q2q1 If a language has built-in support for quaternions, then use it. C.f.   Vector products   On Quaternions;   or on a new System of Imaginaries in Algebra.   By Sir William Rowan Hamilton LL.D, P.R.I.A., F.R.A.S., Hon. M. R. Soc. Ed. and Dub., Hon. or Corr. M. of the Royal or Imperial Academies of St. Petersburgh, Berlin, Turin and Paris, Member of the American Academy of Arts and Sciences, and of other Scientific Societies at Home and Abroad, Andrews' Prof. of Astronomy in the University of Dublin, and Royal Astronomer of Ireland.
#ALGOL_W
ALGOL W
begin  % Quaternion record type  % record Quaternion ( real a, b, c, d );    % returns the norm of the specified quaternion  % real procedure normQ ( reference(Quaternion) value q ) ; sqrt( (a(q) * a(q)) + (b(q) * b(q)) + (c(q) * c(q)) + (d(q) * d(q)) );    % returns the negative of the specified quaternion  % reference(Quaternion) procedure negQ ( reference(Quaternion) value q ) ; Quaternion( - a(q), - b(q), - c(q), - d(q) );    % returns the conjugate of the specified quaternion  % reference(Quaternion) procedure conjQ ( reference(Quaternion) value q ) ; Quaternion( a(q), - b(q), - c(q), - d(q) );    % returns the sum of a real and a quaternion  % reference(Quaternion) procedure addRQ ( real value r  ; reference(Quaternion) value q ) ; Quaternion( r + a(q), b(q), c(q), d(q) );    % returns the sum of a quaternion and a real  % reference(Quaternion) procedure addQR ( reference(Quaternion) value q  ; real value r ) ; Quaternion( r + a(q), b(q), c(q), d(q) );    % returns the sum of the specified quaternions  % reference(Quaternion) procedure addQQ ( reference(Quaternion) value q1  ; reference(Quaternion) value q2 ) ; Quaternion( a(q1) + a(q2), b(q1) + b(q2), c(q1) + c(q2), d(q1) + d(q2) );    % returns the specified quaternion multiplied by a real  % reference(Quaternion) procedure mulQR ( reference(Quaternion) value q  ; real value r ) ; Quaternion( r * a(q), r * b(q), r * c(q), r * d(q) );    % returns a real multiplied by the specified quaternion  % reference(Quaternion) procedure mulRQ ( real value r  ; reference(Quaternion) value q ) ; mulQR( q, r );    % returns the Quaternion product of the specified quaternions  % reference(Quaternion) procedure mulQQ( reference(Quaternion) value q1  ; reference(Quaternion) value q2 ) ; Quaternion( (a(q1) * a(q2)) - (b(q1) * b(q2)) - (c(q1) * c(q2)) - (d(q1) * d(q2)) , (a(q1) * b(q2)) + (b(q1) * a(q2)) + (c(q1) * d(q2)) - (d(q1) * c(q2)) , (a(q1) * c(q2)) - (b(q1) * d(q2)) + (c(q1) * a(q2)) + (d(q1) * b(q2)) , (a(q1) * d(q2)) + (b(q1) * c(q2)) - (c(q1) * b(q2)) + (d(q1) * a(q2)) );    % returns true if the two quaternions are equal, false otherwise  % logical procedure equalQ( reference(Quaternion) value q1  ; reference(Quaternion) value q2 ) ; a(q1) = a(q2) and b(q1) = b(q2) and c(q1) = c(q2) and d(q1) = d(q2);    % writes a quaternion  % procedure writeonQ( reference(Quaternion) value q ) ; writeon( "(", a(q), ", ", b(q), ", ", c(q), ", ", d(q), ")" );      % test q1q2 = q2q1  % reference(Quaternion) q, q1, q2;   q  := Quaternion( 1, 2, 3, 4 ); q1 := Quaternion( 2, 3, 4, 5 ); q2 := Quaternion( 3, 4, 5, 6 );    % set output format  % s_w := 0; r_format := "A"; r_w := 5; r_d := 1;   write( " q:" );writeonQ( q ); write( " q1:" );writeonQ( q1 ); write( " q2:" );writeonQ( q2 ); write( "norm q:" );writeon( normQ( q ) ); write( "norm q1:" );writeon( normQ( q1 ) ); write( "norm q2:" );writeon( normQ( q2 ) );   write( " conj q:" );writeonQ( conjQ( q ) ); write( " - q:" );writeonQ( negQ( q ) ); write( " 7 + q:" );writeonQ( addRQ( 7, q ) ); write( " q + 9:" );writeonQ( addQR( q, 9 ) ); write( " q + q1:" );writeonQ( addQQ( q, q1 ) ); write( " 3 * q:" );writeonQ( mulRQ( 3, q ) ); write( " q * 4:" );writeonQ( mulQR( q, 4 ) );    % check that q1q2 not = q2q1  % if equalQ( mulQQ( q1, q2 ), mulQQ( q2, q1 ) ) then write( "q1q2 = q2q1 ??" ) else write( "q1q2 <> q2q1" );   write( " q1q2:" );writeonQ( mulQQ( q1, q2 ) ); write( " q2q1:" );writeonQ( mulQQ( q2, q1 ) );   end.  
http://rosettacode.org/wiki/Quine
Quine
A quine is a self-referential program that can, without any external access, output its own source. A   quine   (named after Willard Van Orman Quine)   is also known as:   self-reproducing automata   (1972)   self-replicating program         or   self-replicating computer program   self-reproducing program      or   self-reproducing computer program   self-copying program             or   self-copying computer program It is named after the philosopher and logician who studied self-reference and quoting in natural language, as for example in the paradox "'Yields falsehood when preceded by its quotation' yields falsehood when preceded by its quotation." "Source" has one of two meanings. It can refer to the text-based program source. For languages in which program source is represented as a data structure, "source" may refer to the data structure: quines in these languages fall into two categories: programs which print a textual representation of themselves, or expressions which evaluate to a data structure which is equivalent to that expression. The usual way to code a quine works similarly to this paradox: The program consists of two identical parts, once as plain code and once quoted in some way (for example, as a character string, or a literal data structure). The plain code then accesses the quoted code and prints it out twice, once unquoted and once with the proper quotation marks added. Often, the plain code and the quoted code have to be nested. Task Write a program that outputs its own source code in this way. If the language allows it, you may add a variant that accesses the code directly. You are not allowed to read any external files with the source code. The program should also contain some sort of self-reference, so constant expressions which return their own value which some top-level interpreter will print out. Empty programs producing no output are not allowed. There are several difficulties that one runs into when writing a quine, mostly dealing with quoting: Part of the code usually needs to be stored as a string or structural literal in the language, which needs to be quoted somehow. However, including quotation marks in the string literal itself would be troublesome because it requires them to be escaped, which then necessitates the escaping character (e.g. a backslash) in the string, which itself usually needs to be escaped, and so on. Some languages have a function for getting the "source code representation" of a string (i.e. adds quotation marks, etc.); in these languages, this can be used to circumvent the quoting problem. Another solution is to construct the quote character from its character code, without having to write the quote character itself. Then the character is inserted into the string at the appropriate places. The ASCII code for double-quote is 34, and for single-quote is 39. Newlines in the program may have to be reproduced as newlines in the string, which usually requires some kind of escape sequence (e.g. "\n"). This causes the same problem as above, where the escaping character needs to itself be escaped, etc. If the language has a way of getting the "source code representation", it usually handles the escaping of characters, so this is not a problem. Some languages allow you to have a string literal that spans multiple lines, which embeds the newlines into the string without escaping. Write the entire program on one line, for free-form languages (as you can see for some of the solutions here, they run off the edge of the screen), thus removing the need for newlines. However, this may be unacceptable as some languages require a newline at the end of the file; and otherwise it is still generally good style to have a newline at the end of a file. (The task is not clear on whether a newline is required at the end of the file.) Some languages have a print statement that appends a newline; which solves the newline-at-the-end issue; but others do not. Next to the Quines presented here, many other versions can be found on the Quine page. Related task   print itself.
#Arturo
Arturo
block: [print ["block:" as .code block "do block"]] do block
http://rosettacode.org/wiki/Queue/Usage
Queue/Usage
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. Illustration of FIFO behavior Task Create a queue data structure and demonstrate its operations. (For implementations of queues, see the FIFO task.) Operations:   push       (aka enqueue) - add element   pop         (aka dequeue) - pop first element   empty     - return truth value when empty See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal Stack
#C.2B.2B
C++
#include <queue> #include <cassert> // for run time assertions   int main() { std::queue<int> q; assert( q.empty() ); // initially the queue is empty   q.push(1); // add an element assert( !q.empty() ); // now the queue isn't empty any more assert( q.front() == 1 ); // the first element is, of course, 1   q.push(2); // add another element assert( !q.empty() ); // it's of course not empty again assert( q.front() == 1 ); // the first element didn't change   q.push(3); // add yet an other element assert( !q.empty() ); // the queue is still not empty assert( q.front() == 1 ); // and the first element is still 1   q.pop(); // remove the first element assert( !q.empty() ); // the queue is not yet empty assert( q.front() == 2); // the first element is now 2 (the 1 is gone)   q.pop(); assert( !q.empty() ); assert( q.front() == 3);   q.push(4); assert( !q.empty() ); assert( q.front() == 3);   q.pop(); assert( !q.empty() ); assert( q.front() == 4);   q.pop(); assert( q.empty() );   q.push(5); assert( !q.empty() ); assert( q.front() == 5);   q.pop(); assert( q.empty() ); }
http://rosettacode.org/wiki/Read_a_specific_line_from_a_file
Read a specific line from a file
Some languages have special semantics for obtaining a known line number from a file. Task Demonstrate how to obtain the contents of a specific line within a file. For the purpose of this task demonstrate how the contents of the seventh line of a file can be obtained,   and store it in a variable or in memory   (for potential future use within the program if the code were to become embedded). If the file does not contain seven lines,   or the seventh line is empty,   or too big to be retrieved,   output an appropriate message. If no special semantics are available for obtaining the required line,   it is permissible to read line by line. Note that empty lines are considered and should still be counted. Also note that for functional languages or languages without variables or storage,   it is permissible to output the extracted data to standard output.
#Rust
Rust
use std::fs::File; use std::io::BufRead; use std::io::BufReader; use std::io::Error; use std::path::Path;   fn main() { let path = Path::new("file.txt"); let line_num = 7usize; let line = get_line_at(&path, line_num - 1); println!("{}", line.unwrap()); }   fn get_line_at(path: &Path, line_num: usize) -> Result<String, Error> { let file = File::open(path).expect("File not found or cannot be opened"); let content = BufReader::new(&file); let mut lines = content.lines(); lines.nth(line_num).expect("No line found at that position") }
http://rosettacode.org/wiki/Read_a_specific_line_from_a_file
Read a specific line from a file
Some languages have special semantics for obtaining a known line number from a file. Task Demonstrate how to obtain the contents of a specific line within a file. For the purpose of this task demonstrate how the contents of the seventh line of a file can be obtained,   and store it in a variable or in memory   (for potential future use within the program if the code were to become embedded). If the file does not contain seven lines,   or the seventh line is empty,   or too big to be retrieved,   output an appropriate message. If no special semantics are available for obtaining the required line,   it is permissible to read line by line. Note that empty lines are considered and should still be counted. Also note that for functional languages or languages without variables or storage,   it is permissible to output the extracted data to standard output.
#Scala
Scala
val lines = io.Source.fromFile("input.txt").getLines val seventhLine = lines drop(6) next
http://rosettacode.org/wiki/Quickselect_algorithm
Quickselect algorithm
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort Use the quickselect algorithm on the vector [9, 8, 7, 6, 5, 0, 1, 2, 3, 4] To show the first, second, third, ... up to the tenth largest member of the vector, in order, here on this page. Note: Quicksort has a separate task.
#COBOL
COBOL
CLASS-ID MainProgram.   METHOD-ID Partition STATIC USING T. CONSTRAINTS. CONSTRAIN T IMPLEMENTS type IComparable.   DATA DIVISION. LOCAL-STORAGE SECTION. 01 pivot-val T.   PROCEDURE DIVISION USING VALUE arr AS T OCCURS ANY, left-idx AS BINARY-LONG, right-idx AS BINARY-LONG, pivot-idx AS BINARY-LONG RETURNING ret AS BINARY-LONG. MOVE arr (pivot-idx) TO pivot-val INVOKE self::Swap(arr, pivot-idx, right-idx) DECLARE store-idx AS BINARY-LONG = left-idx PERFORM VARYING i AS BINARY-LONG FROM left-idx BY 1 UNTIL i > right-idx IF arr (i) < pivot-val INVOKE self::Swap(arr, i, store-idx) ADD 1 TO store-idx END-IF END-PERFORM INVOKE self::Swap(arr, right-idx, store-idx)   MOVE store-idx TO ret END METHOD.   METHOD-ID Quickselect STATIC USING T. CONSTRAINTS. CONSTRAIN T IMPLEMENTS type IComparable.   PROCEDURE DIVISION USING VALUE arr AS T OCCURS ANY, left-idx AS BINARY-LONG, right-idx AS BINARY-LONG, n AS BINARY-LONG RETURNING ret AS T. IF left-idx = right-idx MOVE arr (left-idx) TO ret GOBACK END-IF   DECLARE rand AS TYPE Random = NEW Random() DECLARE pivot-idx AS BINARY-LONG = rand::Next(left-idx, right-idx) DECLARE pivot-new-idx AS BINARY-LONG = self::Partition(arr, left-idx, right-idx, pivot-idx) DECLARE pivot-dist AS BINARY-LONG = pivot-new-idx - left-idx + 1   EVALUATE TRUE WHEN pivot-dist = n MOVE arr (pivot-new-idx) TO ret   WHEN n < pivot-dist INVOKE self::Quickselect(arr, left-idx, pivot-new-idx - 1, n) RETURNING ret   WHEN OTHER INVOKE self::Quickselect(arr, pivot-new-idx + 1, right-idx, n - pivot-dist) RETURNING ret END-EVALUATE END METHOD.   METHOD-ID Swap STATIC USING T. CONSTRAINTS. CONSTRAIN T IMPLEMENTS type IComparable.   DATA DIVISION. LOCAL-STORAGE SECTION. 01 temp T.   PROCEDURE DIVISION USING arr AS T OCCURS ANY, VALUE idx-1 AS BINARY-LONG, idx-2 AS BINARY-LONG. IF idx-1 <> idx-2 MOVE arr (idx-1) TO temp MOVE arr (idx-2) TO arr (idx-1) MOVE temp TO arr (idx-2) END-IF END METHOD.   METHOD-ID Main STATIC. PROCEDURE DIVISION. DECLARE input-array AS BINARY-LONG OCCURS ANY = TABLE OF BINARY-LONG(9, 8, 7, 6, 5, 0, 1, 2, 3, 4) DISPLAY "Loop quick select 10 times." PERFORM VARYING i AS BINARY-LONG FROM 1 BY 1 UNTIL i > 10 DISPLAY self::Quickselect(input-array, 1, input-array::Length, i) NO ADVANCING   IF i < 10 DISPLAY ", " NO ADVANCING END-IF END-PERFORM DISPLAY SPACE END METHOD. END CLASS.
http://rosettacode.org/wiki/Ramer-Douglas-Peucker_line_simplification
Ramer-Douglas-Peucker line simplification
Ramer-Douglas-Peucker line simplification You are encouraged to solve this task according to the task description, using any language you may know. The   Ramer–Douglas–Peucker   algorithm is a line simplification algorithm for reducing the number of points used to define its shape. Task Using the   Ramer–Douglas–Peucker   algorithm, simplify the   2D   line defined by the points: (0,0) (1,0.1) (2,-0.1) (3,5) (4,6) (5,7) (6,8.1) (7,9) (8,9) (9,9) The error threshold to be used is:   1.0. Display the remaining points here. Reference   the Wikipedia article:   Ramer-Douglas-Peucker algorithm.
#PHP
PHP
function perpendicular_distance(array $pt, array $line) { // Calculate the normalized delta x and y of the line. $dx = $line[1][0] - $line[0][0]; $dy = $line[1][1] - $line[0][1]; $mag = sqrt($dx * $dx + $dy * $dy); if ($mag > 0) { $dx /= $mag; $dy /= $mag; }   // Calculate dot product, projecting onto normalized direction. $pvx = $pt[0] - $line[0][0]; $pvy = $pt[1] - $line[0][1]; $pvdot = $dx * $pvx + $dy * $pvy;   // Scale line direction vector and subtract from pv. $dsx = $pvdot * $dx; $dsy = $pvdot * $dy; $ax = $pvx - $dsx; $ay = $pvy - $dsy;   return sqrt($ax * $ax + $ay * $ay); }   function ramer_douglas_peucker(array $points, $epsilon) { if (count($points) < 2) { throw new InvalidArgumentException('Not enough points to simplify'); }   // Find the point with the maximum distance from the line between start/end. $dmax = 0; $index = 0; $end = count($points) - 1; $start_end_line = [$points[0], $points[$end]]; for ($i = 1; $i < $end; $i++) { $dist = perpendicular_distance($points[$i], $start_end_line); if ($dist > $dmax) { $index = $i; $dmax = $dist; } }   // If max distance is larger than epsilon, recursively simplify. if ($dmax > $epsilon) { $new_start = ramer_douglas_peucker(array_slice($points, 0, $index + 1), $epsilon); $new_end = ramer_douglas_peucker(array_slice($points, $index), $epsilon); array_pop($new_start); return array_merge($new_start, $new_end); }   // Max distance is below epsilon, so return a line from with just the // start and end points. return [ $points[0], $points[$end]]; }   $polyline = [ [0,0], [1,0.1], [2,-0.1], [3,5], [4,6], [5,7], [6,8.1], [7,9], [8,9], [9,9], ];   $result = ramer_douglas_peucker($polyline, 1.0); print "Result:\n"; foreach ($result as $point) { print $point[0] . ',' . $point[1] . "\n"; }
http://rosettacode.org/wiki/Range_extraction
Range extraction
A format for expressing an ordered list of integers is to use a comma separated list of either individual integers Or a range of integers denoted by the starting integer separated from the end integer in the range by a dash, '-'. (The range includes all integers in the interval including both endpoints) The range syntax is to be used only for, and for every range that expands to more than two values. Example The list of integers: -6, -3, -2, -1, 0, 1, 3, 4, 5, 7, 8, 9, 10, 11, 14, 15, 17, 18, 19, 20 Is accurately expressed by the range expression: -6,-3-1,3-5,7-11,14,15,17-20 (And vice-versa). Task Create a function that takes a list of integers in increasing order and returns a correctly formatted string in the range format. Use the function to compute and print the range formatted version of the following ordered list of integers. (The correct answer is: 0-2,4,6-8,11,12,14-25,27-33,35-39). 0, 1, 2, 4, 6, 7, 8, 11, 12, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 27, 28, 29, 30, 31, 32, 33, 35, 36, 37, 38, 39 Show the output of your program. Related task   Range expansion
#Delphi
Delphi
procedure ExtractRanges(const values : array of Integer); begin var i:=0; while i<values.Length do begin if i>0 then Print(','); Print(values[i]); var j:=i+1; while (j<values.Length) and (values[j]=values[j-1]+1) do Inc(j); Dec(j); if j>i then begin if j=i+1 then Print(',') else Print('-'); Print(values[j]); end; i:=j+1; end; end;   ExtractRanges([ 0, 1, 2, 4, 6, 7, 8, 11, 12, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 27, 28, 29, 30, 31, 32, 33, 35, 36, 37, 38, 39]);
http://rosettacode.org/wiki/Random_numbers
Random numbers
Task Generate a collection filled with   1000   normally distributed random (or pseudo-random) numbers with a mean of   1.0   and a   standard deviation   of   0.5 Many libraries only generate uniformly distributed random numbers. If so, you may use one of these algorithms. Related task   Standard deviation
#Fantom
Fantom
  class Main { static const Float PI := 0.0f.acos * 2 // we need to precompute PI   static Float randomNormal () { return (Float.random * PI * 2).cos * (Float.random.log * -2).sqrt }   public static Void main () { mean := 1.0f sd := 0.5f Float[] values := [,] // this is the collection to fill with random numbers 1000.times { values.add (randomNormal * sd + mean) } } }  
http://rosettacode.org/wiki/Random_numbers
Random numbers
Task Generate a collection filled with   1000   normally distributed random (or pseudo-random) numbers with a mean of   1.0   and a   standard deviation   of   0.5 Many libraries only generate uniformly distributed random numbers. If so, you may use one of these algorithms. Related task   Standard deviation
#Forth
Forth
require random.fs here to seed   -1. 1 rshift 2constant MAX-D \ or s" MAX-D" ENVIRONMENT? drop   : frnd ( -- f ) \ uniform distribution 0..1 rnd rnd dabs d>f MAX-D d>f f/ ;   : frnd-normal ( -- f ) \ centered on 0, std dev 1 frnd pi f* 2e f* fcos frnd fln -2e f* fsqrt f* ;   : ,normals ( n -- ) \ store many, centered on 1, std dev 0.5 0 do frnd-normal 0.5e f* 1e f+ f, loop ;   create rnd-array 1000 ,normals
http://rosettacode.org/wiki/Random_number_generator_(included)
Random number generator (included)
The task is to: State the type of random number generator algorithm used in a language's built-in random number generator. If the language or its immediate libraries don't provide a random number generator, skip this task. If possible, give a link to a wider explanation of the algorithm used. Note: the task is not to create an RNG, but to report on the languages in-built RNG that would be the most likely RNG used. The main types of pseudo-random number generator (PRNG) that are in use are the Linear Congruential Generator (LCG), and the Generalized Feedback Shift Register (GFSR), (of which the Mersenne twister generator is a subclass). The last main type is where the output of one of the previous ones (typically a Mersenne twister) is fed through a cryptographic hash function to maximize unpredictability of individual bits. Note that neither LCGs nor GFSRs should be used for the most demanding applications (cryptography) without additional steps.
#Nim
Nim
setrand(3) random(6)+1 \\ chosen by fair dice roll. \\ guaranteed to the random.
http://rosettacode.org/wiki/Random_number_generator_(included)
Random number generator (included)
The task is to: State the type of random number generator algorithm used in a language's built-in random number generator. If the language or its immediate libraries don't provide a random number generator, skip this task. If possible, give a link to a wider explanation of the algorithm used. Note: the task is not to create an RNG, but to report on the languages in-built RNG that would be the most likely RNG used. The main types of pseudo-random number generator (PRNG) that are in use are the Linear Congruential Generator (LCG), and the Generalized Feedback Shift Register (GFSR), (of which the Mersenne twister generator is a subclass). The last main type is where the output of one of the previous ones (typically a Mersenne twister) is fed through a cryptographic hash function to maximize unpredictability of individual bits. Note that neither LCGs nor GFSRs should be used for the most demanding applications (cryptography) without additional steps.
#OCaml
OCaml
setrand(3) random(6)+1 \\ chosen by fair dice roll. \\ guaranteed to the random.
http://rosettacode.org/wiki/Random_number_generator_(included)
Random number generator (included)
The task is to: State the type of random number generator algorithm used in a language's built-in random number generator. If the language or its immediate libraries don't provide a random number generator, skip this task. If possible, give a link to a wider explanation of the algorithm used. Note: the task is not to create an RNG, but to report on the languages in-built RNG that would be the most likely RNG used. The main types of pseudo-random number generator (PRNG) that are in use are the Linear Congruential Generator (LCG), and the Generalized Feedback Shift Register (GFSR), (of which the Mersenne twister generator is a subclass). The last main type is where the output of one of the previous ones (typically a Mersenne twister) is fed through a cryptographic hash function to maximize unpredictability of individual bits. Note that neither LCGs nor GFSRs should be used for the most demanding applications (cryptography) without additional steps.
#Octave
Octave
setrand(3) random(6)+1 \\ chosen by fair dice roll. \\ guaranteed to the random.
http://rosettacode.org/wiki/Random_number_generator_(included)
Random number generator (included)
The task is to: State the type of random number generator algorithm used in a language's built-in random number generator. If the language or its immediate libraries don't provide a random number generator, skip this task. If possible, give a link to a wider explanation of the algorithm used. Note: the task is not to create an RNG, but to report on the languages in-built RNG that would be the most likely RNG used. The main types of pseudo-random number generator (PRNG) that are in use are the Linear Congruential Generator (LCG), and the Generalized Feedback Shift Register (GFSR), (of which the Mersenne twister generator is a subclass). The last main type is where the output of one of the previous ones (typically a Mersenne twister) is fed through a cryptographic hash function to maximize unpredictability of individual bits. Note that neither LCGs nor GFSRs should be used for the most demanding applications (cryptography) without additional steps.
#Oz
Oz
setrand(3) random(6)+1 \\ chosen by fair dice roll. \\ guaranteed to the random.