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/Stair-climbing_puzzle | Stair-climbing puzzle | From Chung-Chieh Shan (LtU):
Your stair-climbing robot has a very simple low-level API: the "step" function takes no argument and attempts to climb one step as a side effect. Unfortunately, sometimes the attempt fails and the robot clumsily falls one step instead. The "step" function detects what happens and returns a boolean flag: true on success, false on failure.
Write a function "step_up" that climbs one step up [from the initial position] (by repeating "step" attempts if necessary). Assume that the robot is not already at the top of the stairs, and neither does it ever reach the bottom of the stairs. How small can you make "step_up"? Can you avoid using variables (even immutable ones) and numbers?
Here's a pseudo-code of a simple recursive solution without using variables:
func step_up()
{
if not step() {
step_up();
step_up();
}
}
Inductive proof that step_up() steps up one step, if it terminates:
Base case (if the step() call returns true): it stepped up one step. QED
Inductive case (if the step() call returns false): Assume that recursive calls to step_up() step up one step. It stepped down one step (because step() returned false), but now we step up two steps using two step_up() calls. QED
The second (tail) recursion above can be turned into an iteration, as follows:
func step_up()
{
while not step() {
step_up();
}
}
| #Lua | Lua |
function step_up()
while not step() do step_up() end
end
|
http://rosettacode.org/wiki/Square_but_not_cube | Square but not cube | Task
Show the first 30 positive integers which are squares but not cubes of such integers.
Optionally, show also the first 3 positive integers which are both squares and cubes, and mark them as such.
| #8086_Assembly | 8086 Assembly | cpu 8086
org 100h
section .text
mov si,1 ; Square counter
mov di,si ; Current square
mov bp,si ; Cube counter
mov bx,si ; Current cube
xor cx,cx ; Counter
loop: cmp di,bx ; Square > cube?
jbe check
inc bp ; Calculate next cube
mov ax,bp
mul bp
mul bp
mov bx,ax
jmp loop
check: je next ; Square != cube?
inc cx ; Then count it
mov ax,di
call print ; Print it
next: inc si ; Next square
mov ax,si
mul si
mov di,ax
cmp cx,30 ; Done yet?
jb loop
ret
print: push bx ; Print AX - save registers
push cx
mov cx,10
mov bx,num ; End of number buffer
dgt: xor dx,dx ; Extract digit
div cx
add dl,'0'
dec bx ; Store digit
mov [bx],dl
test ax,ax ; More digits?
jnz dgt ; If so, go get them
mov dx,bx ; If not, print string
mov ah,9
int 21h
pop cx ; Restore registers
pop bx
ret
section .data
db '*****' ; Placeholder for number
num: db ' $' |
http://rosettacode.org/wiki/Square_form_factorization | Square form factorization | Task.
Daniel Shanks's Square Form Factorization (SquFoF).
Invented around 1975, ‘On a 32-bit computer, SquFoF is the clear champion factoring algorithm
for numbers between 1010 and 1018, and will likely remain so.’
An integral binary quadratic form is a polynomial
f(x,y) = ax2 + bxy + cy2
with integer coefficients and discriminant D = b2 – 4ac.
For each positive discriminant there are multiple forms (a, b, c).
The next form in a periodic sequence (cycle) of adjacent forms is found by applying a reduction operator
rho, essentially a variant of Euclid's algorithm for finding the continued fraction of a square root.
Using floor(√N), rho constructs a principal form
(1, b, c) with D = 4N.
SquFoF is based on the existence of cycles containing ambiguous forms, with the property that a divides b.
They come in pairs of associated forms (a, b, c) and (c, b, a) called symmetry points.
If an ambiguous form is found (there is one for each divisor of D), write the discriminant as
(ak)2 – 4ac = a(a·k2 – 4c) = 4N
and (if a is not equal to 1 or 2) N is split.
Shanks used square forms to jump to a random ambiguous cycle. Fact: if any form in an ambiguous cycle
is squared, that square form will always land in the principal cycle. Conversely, the square root of any
form in the principal cycle lies in an ambiguous cycle. (Possibly the principal cycle itself).
A square form is easy to find: the last coefficient c is a perfect square. This happens about once
every ∜N-th cycle step and for even indices only. Let rho compute the inverse square root form and track
the ambiguous cycle backward until the symmetry point is reached. (Taking the inverse reverses the cycle).
Then a or a/2 divides D and therefore N.
To avoid trivial factorizations, Shanks created a list (queue) to hold small coefficients appearing
early in the principal cycle, that may be roots of square forms found later on. If these forms are skipped,
no roots land in the principal cycle itself and cases a = 1 or a = 2 do not happen.
Sometimes the cycle length is too short to find a proper square form. This is fixed by running five instances
of SquFoF in parallel, with input N and 3, 5, 7, 11 times N; the discriminants then will have different periods.
If N is prime or the cube of a prime, there are improper squares only and the program will duly report failure.
Reference.
[1] A detailed analysis of SquFoF (2007)
| #Perl | Perl | use strict;
use warnings;
use feature 'say';
use ntheory <is_prime gcd forcomb vecprod>;
my @multiplier;
my @p = <3 5 7 11>;
forcomb { push @multiplier, vecprod @p[@_] } scalar @p;
sub sff {
my($N) = shift;
return 1 if is_prime $N; # if n is prime
return sqrt $N if sqrt($N) == int sqrt $N; # if n is a perfect square
for my $k (@multiplier) {
my $P0 = int sqrt($k*$N); # P[0]=floor(sqrt(N)
my $Q0 = 1; # Q[0]=1
my $Q = $k*$N - $P0**2; # Q[1]=N-P[0]^2 & Q[i]
my $P1 = $P0; # P[i-1] = P[0]
my $Q1 = $Q0; # Q[i-1] = Q[0]
my $P = 0; # P[i]
my $Qn = 0; # $P[$i+1];
my $b = 0; # b[i]
until (sqrt($Q) == int(sqrt($Q))) { # until Q[i] is a perfect square
$b = int( int(sqrt($k*$N) + $P1 ) / $Q); # floor(floor(sqrt(N+P[i-1])/Q[i])
$P = $b*$Q - $P1; # P[i]=b*Q[i]-P[i-1]
$Qn = $Q1 + $b*($P1 - $P); # Q[i+1]=Q[i-1]+b(P[i-1]-P[i])
($Q1, $Q, $P1) = ($Q, $Qn, $P);
}
$b = int( int( sqrt($k*$N)+$P ) / $Q ); # b=floor((floor(sqrt(N)+P[i])/Q[0])
$P1 = $b*$Q0 - $P; # P[i-1]=b*Q[0]-P[i]
$Q = ( $k*$N - $P1**2 )/$Q0; # Q[1]=(N-P[0]^2)/Q[0] & Q[i]
$Q1 = $Q0; # Q[i-1] = Q[0]
while () {
$b = int( int(sqrt($k*$N)+$P1 ) / $Q ); # b=floor(floor(sqrt(N)+P[i-1])/Q[i])
$P = $b*$Q - $P1; # P[i]=b*Q[i]-P[i-1]
$Qn = $Q1 + $b*($P1 - $P); # Q[i+1]=Q[i-1]+b(P[i-1]-P[i])
last if $P == $P1; # until P[i+1]=P[i]
($Q1, $Q, $P1) = ($Q, $Qn, $P);
}
for (gcd $N, $P) { return $_ if $_ != 1 and $_ != $N }
}
return 0
}
for my $data (
11111, 2501, 12851, 13289, 75301, 120787, 967009, 997417, 4558849, 7091569, 13290059,
42854447, 223553581, 2027651281, 11111111111, 100895598169, 1002742628021, 60012462237239,
287129523414791, 11111111111111111, 384307168202281507, 1000000000000000127, 9007199254740931,
922337203685477563, 314159265358979323, 1152921505680588799, 658812288346769681,
419244183493398773, 1537228672809128917) {
my $v = sff($data);
if ($v == 0) { say 'The number ' . $data . ' is not factored.' }
elsif ($v == 1) { say 'The number ' . $data . ' is a prime.' }
else { say "$data = " . join ' * ', sort {$a <=> $b} $v, int $data/int($v) }
} |
http://rosettacode.org/wiki/Statistics/Basic | Statistics/Basic | Statistics is all about large groups of numbers.
When talking about a set of sampled data, most frequently used is their mean value and standard deviation (stddev).
If you have set of data
x
i
{\displaystyle x_{i}}
where
i
=
1
,
2
,
…
,
n
{\displaystyle i=1,2,\ldots ,n\,\!}
, the mean is
x
¯
≡
1
n
∑
i
x
i
{\displaystyle {\bar {x}}\equiv {1 \over n}\sum _{i}x_{i}}
, while the stddev is
σ
≡
1
n
∑
i
(
x
i
−
x
¯
)
2
{\displaystyle \sigma \equiv {\sqrt {{1 \over n}\sum _{i}\left(x_{i}-{\bar {x}}\right)^{2}}}}
.
When examining a large quantity of data, one often uses a histogram, which shows the counts of data samples falling into a prechosen set of intervals (or bins).
When plotted, often as bar graphs, it visually indicates how often each data value occurs.
Task Using your language's random number routine, generate real numbers in the range of [0, 1]. It doesn't matter if you chose to use open or closed range.
Create 100 of such numbers (i.e. sample size 100) and calculate their mean and stddev.
Do so for sample size of 1,000 and 10,000, maybe even higher if you feel like.
Show a histogram of any of these sets.
Do you notice some patterns about the standard deviation?
Extra Sometimes so much data need to be processed that it's impossible to keep all of them at once. Can you calculate the mean, stddev and histogram of a trillion numbers? (You don't really need to do a trillion numbers, just show how it can be done.)
Hint
For a finite population with equal probabilities at all points, one can derive:
(
x
−
x
¯
)
2
¯
=
x
2
¯
−
x
¯
2
{\displaystyle {\overline {(x-{\overline {x}})^{2}}}={\overline {x^{2}}}-{\overline {x}}^{2}}
Or, more verbosely:
1
N
∑
i
=
1
N
(
x
i
−
x
¯
)
2
=
1
N
(
∑
i
=
1
N
x
i
2
)
−
x
¯
2
.
{\displaystyle {\frac {1}{N}}\sum _{i=1}^{N}(x_{i}-{\overline {x}})^{2}={\frac {1}{N}}\left(\sum _{i=1}^{N}x_{i}^{2}\right)-{\overline {x}}^{2}.}
See also
Statistics/Normal distribution
Tasks for calculating statistical measures
in one go
moving (sliding window)
moving (cumulative)
Mean
Arithmetic
Statistics/Basic
Averages/Arithmetic mean
Averages/Pythagorean means
Averages/Simple moving average
Geometric
Averages/Pythagorean means
Harmonic
Averages/Pythagorean means
Quadratic
Averages/Root mean square
Circular
Averages/Mean angle
Averages/Mean time of day
Median
Averages/Median
Mode
Averages/Mode
Standard deviation
Statistics/Basic
Cumulative standard deviation
| #C.23 | C# | using System;
using MathNet.Numerics.Statistics;
class Program
{
static void Run(int sampleSize)
{
double[] X = new double[sampleSize];
var r = new Random();
for (int i = 0; i < sampleSize; i++)
X[i] = r.NextDouble();
const int numBuckets = 10;
var histogram = new Histogram(X, numBuckets);
Console.WriteLine("Sample size: {0:N0}", sampleSize);
for (int i = 0; i < numBuckets; i++)
{
string bar = new String('#', (int)(histogram[i].Count * 360 / sampleSize));
Console.WriteLine(" {0:0.00} : {1}", histogram[i].LowerBound, bar);
}
var statistics = new DescriptiveStatistics(X);
Console.WriteLine(" Mean: " + statistics.Mean);
Console.WriteLine("StdDev: " + statistics.StandardDeviation);
Console.WriteLine();
}
static void Main(string[] args)
{
Run(100);
Run(1000);
Run(10000);
}
} |
http://rosettacode.org/wiki/Square-free_integers | Square-free integers | Task
Write a function to test if a number is square-free.
A square-free is an integer which is divisible by no perfect square other
than 1 (unity).
For this task, only positive square-free numbers will be used.
Show here (on this page) all square-free integers (in a horizontal format) that are between:
1 ───► 145 (inclusive)
1 trillion ───► 1 trillion + 145 (inclusive)
(One trillion = 1,000,000,000,000)
Show here (on this page) the count of square-free integers from:
1 ───► one hundred (inclusive)
1 ───► one thousand (inclusive)
1 ───► ten thousand (inclusive)
1 ───► one hundred thousand (inclusive)
1 ───► one million (inclusive)
See also
the Wikipedia entry: square-free integer
| #FreeBASIC | FreeBASIC | ' version 06-07-2018
' compile with: fbc -s console
Const As ULongInt trillion = 1000000000000ull
Const As ULong max = Sqr(trillion + 145)
Dim As UByte list(), sieve()
Dim As ULong prime()
ReDim list(max), prime(max\12), sieve(max)
Dim As ULong a, b, c, i, k, stop_ = Sqr(max)
For i = 4 To max Step 2 ' prime sieve remove even numbers except 2
sieve(i) = 1
Next
For i = 3 To stop_ Step 2 ' proces odd numbers
If sieve(i) = 0 Then
For a = i * i To max Step i * 2
sieve(a) = 1
Next
End If
Next
For i = 2 To max ' move primes to a list
If sieve(i) = 0 Then
c += 1
prime(c) = i
End If
Next
ReDim sieve(145): ReDim Preserve prime(c)
For i = 1 To c ' find all square free integers between 1 and 1000000
a = prime(i) * prime(i)
If a > 1000000 Then Exit For
For k = a To 1000000 Step a
list(k) = 1
Next
Next
k = 0
For i = 1 To 145 ' show all between 1 and 145
If list(i) = 0 Then
Print Using"####"; i;
k +=1
If k Mod 20 = 0 Then Print
End If
Next
Print : Print
sieve(0) = 1 ' = trillion
For i = 1 To 5 ' process primes 2, 3, 5, 7, 11
a = prime(i) * prime(i)
b = a - trillion Mod a
For k = b To 145 Step a
sieve(k) = 1
Next
Next
For i = 6 To c ' process the rest of the primes
a = prime(i) * prime(i)
k = a - trillion Mod a
If k <= 145 Then sieve(k) = 1
Next
k = 0
For i = 0 To 145
If sieve(i) = 0 Then
Print Using "################"; (trillion + i);
k += 1
If k Mod 5 = 0 Then print
End If
Next
Print : Print
a = 1 : b = 100 : k = 0
Do Until b > 1000000 ' count them
For i = a To b
If list(i) = 0 Then k += 1
Next
Print "There are "; k; " square free integers between 1 and "; b
a = b : b *= 10
Loop
' empty keyboard buffer
While Inkey <> "" : Wend
Print : Print "hit any key to end program"
Sleep
End |
http://rosettacode.org/wiki/State_name_puzzle | State name puzzle | Background
This task is inspired by Mark Nelson's DDJ Column "Wordplay" and one of the weekly puzzle challenges from Will Shortz on NPR Weekend Edition [1] and originally attributed to David Edelheit.
The challenge was to take the names of two U.S. States, mix them all together, then rearrange the letters to form the names of two different U.S. States (so that all four state names differ from one another).
What states are these?
The problem was reissued on the Unicon Discussion Web which includes several solutions with analysis. Several techniques may be helpful and you may wish to refer to Gödel numbering, equivalence relations, and equivalence classes. The basic merits of these were discussed in the Unicon Discussion Web.
A second challenge in the form of a set of fictitious new states was also presented.
Task
Write a program to solve the challenge using both the original list of states and the fictitious list.
Caveats
case and spacing aren't significant - just letters (harmonize case)
don't expect the names to be in any order - such as being sorted
don't rely on names to be unique (eliminate duplicates - meaning if Iowa appears twice you can only use it once)
Comma separated list of state names used in the original puzzle:
"Alabama", "Alaska", "Arizona", "Arkansas",
"California", "Colorado", "Connecticut", "Delaware",
"Florida", "Georgia", "Hawaii", "Idaho", "Illinois",
"Indiana", "Iowa", "Kansas", "Kentucky", "Louisiana",
"Maine", "Maryland", "Massachusetts", "Michigan",
"Minnesota", "Mississippi", "Missouri", "Montana",
"Nebraska", "Nevada", "New Hampshire", "New Jersey",
"New Mexico", "New York", "North Carolina", "North Dakota",
"Ohio", "Oklahoma", "Oregon", "Pennsylvania", "Rhode Island",
"South Carolina", "South Dakota", "Tennessee", "Texas",
"Utah", "Vermont", "Virginia",
"Washington", "West Virginia", "Wisconsin", "Wyoming"
Comma separated list of additional fictitious state names to be added to the original (Includes a duplicate):
"New Kory", "Wen Kory", "York New", "Kory New", "New Kory"
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #REXX | REXX | /*REXX program (state name puzzle) rearranges two state's names ──► two new states. */
!='Alabama, Alaska, Arizona, Arkansas, California, Colorado, Connecticut, Delaware, Florida, Georgia,',
'Hawaii, Idaho, Illinois, Indiana, Iowa, Kansas, Kentucky, Louisiana, Maine, Maryland, Massachusetts, ',
'Michigan, Minnesota, Mississippi, Missouri, Montana, Nebraska, Nevada, New Hampshire, New Jersey, New Mexico,',
'New York, North Carolina, North Dakota, Ohio, Oklahoma, Oregon, Pennsylvania, Rhode Island, South Carolina,',
'South Dakota, Tennessee, Texas, Utah, Vermont, Virginia, Washington, West Virginia, Wisconsin, Wyoming'
parse arg xtra; !=! ',' xtra /*add optional (fictitious) names.*/
@abcU= 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'; !=space(!) /*!: the state list, no extra blanks*/
deads=0; dups=0; L.=0; !orig=!; @@.= /*initialize some REXX variables. */
z=0 /* [↑] elide dend─end (DE) states.*/
do de=0 for 2; !=!orig /*use original state list for each. */
@.=
do states=0 by 0 until !=='' /*parse until the cows come home. */
parse var ! x ',' !; x=space(x) /*remove all blanks from state name.*/
if @.x\=='' then do /*was state was already specified? */
if de then iterate /*don't tell error if doing 2nd pass*/
dups=dups + 1 /*bump the duplicate counter. */
say 'ignoring the 2nd naming of the state: ' x; iterate
end
@.x=x /*indicate this state name exists. */
y=space(x,0); upper y; yLen=length(y) /*get upper name with no spaces; Len*/
if de then do /*Is the firstt pass? Then process.*/
do j=1 for yLen /*see if it's a dead─end state name.*/
_=substr(y, j, 1) /* _: is some state name character.*/
if L._ \== 1 then iterate /*Count ¬ 1? Then state name is OK.*/
say 'removing dead─end state [which has the letter ' _"]: " x
deads=deads + 1 /*bump number of dead─ends states. */
iterate states /*go and process another state name.*/
end /*j*/
z=z+1 /*bump counter of the state names. */
#.z=y; ##.z=x /*assign state name; also original.*/
end
else do k=1 for yLen /*inventorize letters of state name.*/
_=substr(y,k,1); L._=L._ + 1 /*count each letter in state name. */
end /*k*/
end /*states*/ /*the index STATES isn't incremented*/
end /*de*/
call list /*list state names in order given. */
say z 'state name's(z) "are useable."
if dups \==0 then say dups 'duplicate of a state's(dups) 'ignored.'
if deads\==0 then say deads 'dead─end state's(deads) 'deleted.'
sols=0 /*number of solutions found (so far)*/
say /*[↑] look for mix and match states*/
do j=1 for z /* ◄──────────────────────────────────────────────────────────┐ */
do k=j+1 to z /* ◄─── state K, state J ►─────┘ */
if #.j<<#.k then JK=#.j || #.k /*is the state in the proper order? */
else JK=#.k || #.j /*No, then use the new state name. */
do m=1 for z; if m==j | m==k then iterate /*no state overlaps are allowed. */
if verify(#.m, jk) \== 0 then iterate /*is this state name even possible? */
nJK=elider(JK, #.m) /*a new JK, after eliding #.m chars.*/
do n=m+1 to z; if n==j | n==k then iterate /*no overlaps are allowed. */
if verify(#.n, nJK) \== 0 then iterate /*is it possible? */
if elider(nJK, #.n) \== '' then iterate /*any leftovers letters? */
if #.m<<#.n then MN=#.m || #.n /*is it in the proper order?*/
else MN=#.n || #.m /*we found a new state name.*/
if @@.JK.MN\=='' | @@.MN.JK\=="" then iterate /*was it done before? */
say 'found: ' ##.j',' ##.k " ───► " ##.m',' ##.n
@@.JK.MN=1 /*indicate this solution as being found*/
sols=sols+1 /*bump the number of solutions found. */
end /*n*/
end /*m*/
end /*k*/
end /*j*/
say /*show a blank line for easier reading.*/
if sols==0 then sols= 'No' /*use mucher gooder (sic) Englishings. */
say sols 'solution's(sols) "found." /*display the number of solutions found*/
exit /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
elider: parse arg hay,pins /*remove letters (pins) from haystack. */
do e=1 for length(pins); p=pos( substr( pins, e, 1), hay)
if p==0 then iterate ; hay=overlay(' ', hay, p)
end /*e*/ /* [↑] remove a letter from haystack. */
return space(hay, 0) /*remove blanks from the haystack. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
list: say; do i=1 for z; say right(i, 9) ##.i; end; say; return
s: if arg(1)==1 then return arg(3); return word(arg(2) 's', 1) /*pluralizer.*/ |
http://rosettacode.org/wiki/String_append | String append |
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
Concatenation |
Interpolation |
Comparison |
Matching
Memory Operations
Pointers & references |
Addresses
Most languages provide a way to concatenate two string values, but some languages also provide a convenient way to append in-place to an existing string variable without referring to the variable twice.
Task
Create a string variable equal to any text value.
Append the string variable with another string literal in the most idiomatic way, without double reference if your language supports it.
Show the contents of the variable after the append operation.
| #Scala | Scala | var d = "Hello" // Mutables are discouraged //> d : String = Hello
d += ", World!" // var contains a totally new re-instantiationed String
val s = "Hello" // Immutables are recommended //> s : String = Hello
val s1 = s + s //> s1 : String = HelloHello
val f2 = () => " !" //Function assigned to variable
//> f2 : () => String = <function0>
println(s1 + f2()); //> HelloHello ! |
http://rosettacode.org/wiki/String_append | String append |
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
Concatenation |
Interpolation |
Comparison |
Matching
Memory Operations
Pointers & references |
Addresses
Most languages provide a way to concatenate two string values, but some languages also provide a convenient way to append in-place to an existing string variable without referring to the variable twice.
Task
Create a string variable equal to any text value.
Append the string variable with another string literal in the most idiomatic way, without double reference if your language supports it.
Show the contents of the variable after the append operation.
| #Seed7 | Seed7 | $ include "seed7_05.s7i";
const proc: main is func
local
var string: str is "12345678";
begin
str &:= "9!";
writeln(str);
end func; |
http://rosettacode.org/wiki/Statistics/Normal_distribution | Statistics/Normal distribution | The Normal (or Gaussian) distribution is a frequently used distribution in statistics. While most programming languages provide a uniformly distributed random number generator, one can derive normally distributed random numbers from a uniform generator.
The task
Take a uniform random number generator and create a large (you decide how large) set of numbers that follow a normal (Gaussian) distribution. Calculate the dataset's mean and standard deviation, and show a histogram of the data.
Mention any native language support for the generation of normally distributed random numbers.
Reference
You may refer to code in Statistics/Basic if available.
| #Ruby | Ruby | # Class to implement a Normal distribution, generated from a Uniform distribution.
# Uses the Marsaglia polar method.
class NormalFromUniform
# Initialize an instance.
def initialize()
@next = nil
end
# Generate and return the next Normal distribution value.
def rand()
if @next
retval, @next = @next, nil
return retval
else
u = v = s = nil
loop do
u = Random.rand(-1.0..1.0)
v = Random.rand(-1.0..1.0)
s = u**2 + v**2
break if (s > 0.0) && (s <= 1.0)
end
f = Math.sqrt(-2.0 * Math.log(s) / s)
@next = v * f
return u * f
end
end
end |
http://rosettacode.org/wiki/Stem-and-leaf_plot | Stem-and-leaf plot | Create a well-formatted stem-and-leaf plot from the following data set, where the leaves are the last digits:
12 127 28 42 39 113 42 18 44 118 44 37 113 124 37 48 127 36 29 31 125 139 131 115 105 132 104 123 35 113 122 42 117 119 58 109 23 105 63 27 44 105 99 41 128 121 116 125 32 61 37 127 29 113 121 58 114 126 53 114 96 25 109 7 31 141 46 13 27 43 117 116 27 7 68 40 31 115 124 42 128 52 71 118 117 38 27 106 33 117 116 111 40 119 47 105 57 122 109 124 115 43 120 43 27 27 18 28 48 125 107 114 34 133 45 120 30 127 31 116 146
The primary intent of this task is the presentation of information. It is acceptable to hardcode the data set or characteristics of it (such as what the stems are) in the example, insofar as it is impractical to make the example generic to any data set. For example, in a computation-less language like HTML the data set may be entirely prearranged within the example; the interesting characteristics are how the proper visual formatting is arranged.
If possible, the output should not be a bitmap image. Monospaced plain text is acceptable, but do better if you can. It may be a window, i.e. not a file.
Note: If you wish to try multiple data sets, you might try this generator.
| #jq | jq | def stem_and_leaf:
# align-right:
def right: tostring | (4-length) * " " + .;
sort
| .[0] as $min
| .[length-1] as $max
| "\($min/10|floor|right) | " as $stem
| reduce .[] as $d
# state: [ stem, string ]
( [ 0, $stem ];
.[0] as $stem
| if ($d/10) | floor == $stem
then [ $stem, (.[1] + "\($d % 10)" )]
else [ $stem + 1, (.[1] + "\n\($stem+1|right) | \($d % 10)" )]
end )
| .[1] ; |
http://rosettacode.org/wiki/Stern-Brocot_sequence | Stern-Brocot sequence | For this task, the Stern-Brocot sequence is to be generated by an algorithm similar to that employed in generating the Fibonacci sequence.
The first and second members of the sequence are both 1:
1, 1
Start by considering the second member of the sequence
Sum the considered member of the sequence and its precedent, (1 + 1) = 2, and append it to the end of the sequence:
1, 1, 2
Append the considered member of the sequence to the end of the sequence:
1, 1, 2, 1
Consider the next member of the series, (the third member i.e. 2)
GOTO 3
─── Expanding another loop we get: ───
Sum the considered member of the sequence and its precedent, (2 + 1) = 3, and append it to the end of the sequence:
1, 1, 2, 1, 3
Append the considered member of the sequence to the end of the sequence:
1, 1, 2, 1, 3, 2
Consider the next member of the series, (the fourth member i.e. 1)
The task is to
Create a function/method/subroutine/procedure/... to generate the Stern-Brocot sequence of integers using the method outlined above.
Show the first fifteen members of the sequence. (This should be: 1, 1, 2, 1, 3, 2, 3, 1, 4, 3, 5, 2, 5, 3, 4)
Show the (1-based) index of where the numbers 1-to-10 first appears in the sequence.
Show the (1-based) index of where the number 100 first appears in the sequence.
Check that the greatest common divisor of all the two consecutive members of the series up to the 1000th member, is always one.
Show your output on this page.
Related tasks
Fusc sequence.
Continued fraction/Arithmetic
Ref
Infinite Fractions - Numberphile (Video).
Trees, Teeth, and Time: The mathematics of clock making.
A002487 The On-Line Encyclopedia of Integer Sequences.
| #Go | Go | package main
import (
"fmt"
"sternbrocot"
)
func main() {
// Task 1, using the conventional sort of generator that generates
// terms endlessly.
g := sb.Generator()
// Task 2, demonstrating the generator.
fmt.Println("First 15:")
for i := 1; i <= 15; i++ {
fmt.Printf("%2d: %d\n", i, g())
}
// Task 2 again, showing a simpler technique that might or might not be
// considered to "generate" terms.
s := sb.New()
fmt.Println("First 15:", s.FirstN(15))
// Tasks 3 and 4.
for _, x := range []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 100} {
fmt.Printf("%3d at 1-based index %d\n", x, 1+s.Find(x))
}
// Task 5.
fmt.Println("1-based indexes: gcd")
for n, f := range s.FirstN(1000)[:999] {
g := gcd(f, (*s)[n+1])
fmt.Printf("%d,%d: gcd(%d, %d) = %d\n", n+1, n+2, f, (*s)[n+1], g)
if g != 1 {
panic("oh no!")
return
}
}
}
// gcd copied from greatest common divisor task
func gcd(x, y int) int {
for y != 0 {
x, y = y, x%y
}
return x
} |
http://rosettacode.org/wiki/Stack_traces | Stack traces | Many programming languages allow for introspection of the current call stack environment. This can be for a variety of purposes such as enforcing security checks, debugging, or for getting access to the stack frame of callers.
Task
Print out (in a manner considered suitable for the platform) the current call stack.
The amount of information printed for each frame on the call stack is not constrained, but should include at least the name of the function or method at that level of the stack frame.
You may explicitly add a call to produce the stack trace to the (example) code being instrumented for examination.
The task should allow the program to continue after generating the stack trace.
The task report here must include the trace from a sample program.
| #PHP | PHP | <?php
class StackTraceDemo {
static function inner() {
debug_print_backtrace();
}
static function middle() {
self::inner();
}
static function outer() {
self::middle();
}
}
StackTraceDemo::outer();
?> |
http://rosettacode.org/wiki/Stack_traces | Stack traces | Many programming languages allow for introspection of the current call stack environment. This can be for a variety of purposes such as enforcing security checks, debugging, or for getting access to the stack frame of callers.
Task
Print out (in a manner considered suitable for the platform) the current call stack.
The amount of information printed for each frame on the call stack is not constrained, but should include at least the name of the function or method at that level of the stack frame.
You may explicitly add a call to produce the stack trace to the (example) code being instrumented for examination.
The task should allow the program to continue after generating the stack trace.
The task report here must include the trace from a sample program.
| #PicoLisp | PicoLisp | (off "Stack")
(de $$ "Prg"
(let "Stack" (cons (cons (car "Prg") (env)) "Stack") # Build stack frame
(set "Stack"
(delq (asoq '"Stack" (car "Stack")) # Remove self-created entries
(delq (asoq '"Prg" (car "Stack"))
(car "Stack") ) ) )
(run (cdr "Prg")) ) ) # Run body
(de stackAll (Excl)
(let *Dbg NIL
(for "X" (all)
(or
(memq "X" Excl)
(memq "X" '($$ @ @@ @@@))
(= `(char "*") (char "X"))
(cond
((= `(char "+") (char "X"))
(for "Y" (pair (val "X"))
(and
(pair "Y")
(fun? (cdr "Y"))
(unless (== '$$ (caaddr "Y"))
(con (cdr "Y")
(list
(cons '$$ (cons (car "Y" "X") (cddr "Y"))) ) ) ) ) ) )
((pair (getd "X"))
(let "Y" @
(unless (== '$$ (caadr "Y"))
(con "Y"
(list (cons '$$ "X" (cdr "Y"))) ) ) ) ) ) ) ) ) )
(de dumpStack ()
(more (reverse (cdr "Stack")))
T ) |
http://rosettacode.org/wiki/Stair-climbing_puzzle | Stair-climbing puzzle | From Chung-Chieh Shan (LtU):
Your stair-climbing robot has a very simple low-level API: the "step" function takes no argument and attempts to climb one step as a side effect. Unfortunately, sometimes the attempt fails and the robot clumsily falls one step instead. The "step" function detects what happens and returns a boolean flag: true on success, false on failure.
Write a function "step_up" that climbs one step up [from the initial position] (by repeating "step" attempts if necessary). Assume that the robot is not already at the top of the stairs, and neither does it ever reach the bottom of the stairs. How small can you make "step_up"? Can you avoid using variables (even immutable ones) and numbers?
Here's a pseudo-code of a simple recursive solution without using variables:
func step_up()
{
if not step() {
step_up();
step_up();
}
}
Inductive proof that step_up() steps up one step, if it terminates:
Base case (if the step() call returns true): it stepped up one step. QED
Inductive case (if the step() call returns false): Assume that recursive calls to step_up() step up one step. It stepped down one step (because step() returned false), but now we step up two steps using two step_up() calls. QED
The second (tail) recursion above can be turned into an iteration, as follows:
func step_up()
{
while not step() {
step_up();
}
}
| #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | StepUp[] := If[!Step[], StepUp[]; StepUp[]] |
http://rosettacode.org/wiki/Stair-climbing_puzzle | Stair-climbing puzzle | From Chung-Chieh Shan (LtU):
Your stair-climbing robot has a very simple low-level API: the "step" function takes no argument and attempts to climb one step as a side effect. Unfortunately, sometimes the attempt fails and the robot clumsily falls one step instead. The "step" function detects what happens and returns a boolean flag: true on success, false on failure.
Write a function "step_up" that climbs one step up [from the initial position] (by repeating "step" attempts if necessary). Assume that the robot is not already at the top of the stairs, and neither does it ever reach the bottom of the stairs. How small can you make "step_up"? Can you avoid using variables (even immutable ones) and numbers?
Here's a pseudo-code of a simple recursive solution without using variables:
func step_up()
{
if not step() {
step_up();
step_up();
}
}
Inductive proof that step_up() steps up one step, if it terminates:
Base case (if the step() call returns true): it stepped up one step. QED
Inductive case (if the step() call returns false): Assume that recursive calls to step_up() step up one step. It stepped down one step (because step() returned false), but now we step up two steps using two step_up() calls. QED
The second (tail) recursion above can be turned into an iteration, as follows:
func step_up()
{
while not step() {
step_up();
}
}
| #MATLAB | MATLAB | function step_up()
while ~step()
step_up();
end |
http://rosettacode.org/wiki/Stair-climbing_puzzle | Stair-climbing puzzle | From Chung-Chieh Shan (LtU):
Your stair-climbing robot has a very simple low-level API: the "step" function takes no argument and attempts to climb one step as a side effect. Unfortunately, sometimes the attempt fails and the robot clumsily falls one step instead. The "step" function detects what happens and returns a boolean flag: true on success, false on failure.
Write a function "step_up" that climbs one step up [from the initial position] (by repeating "step" attempts if necessary). Assume that the robot is not already at the top of the stairs, and neither does it ever reach the bottom of the stairs. How small can you make "step_up"? Can you avoid using variables (even immutable ones) and numbers?
Here's a pseudo-code of a simple recursive solution without using variables:
func step_up()
{
if not step() {
step_up();
step_up();
}
}
Inductive proof that step_up() steps up one step, if it terminates:
Base case (if the step() call returns true): it stepped up one step. QED
Inductive case (if the step() call returns false): Assume that recursive calls to step_up() step up one step. It stepped down one step (because step() returned false), but now we step up two steps using two step_up() calls. QED
The second (tail) recursion above can be turned into an iteration, as follows:
func step_up()
{
while not step() {
step_up();
}
}
| #Nim | Nim | proc stepUp = (while not step(): stepUp()) |
http://rosettacode.org/wiki/Stack | Stack |
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.
A stack is a container of elements with last in, first out access policy. Sometimes it also called LIFO.
The stack is accessed through its top.
The basic stack operations are:
push stores a new element onto the stack top;
pop returns the last pushed stack element, while removing it from the stack;
empty tests if the stack contains no elements.
Sometimes the last pushed stack element is made accessible for immutable access (for read) or mutable access (for write):
top (sometimes called peek to keep with the p theme) returns the topmost element without modifying the stack.
Stacks allow a very simple hardware implementation.
They are common in almost all processors.
In programming, stacks are also very popular for their way (LIFO) of resource management, usually memory.
Nested scopes of language objects are naturally implemented by a stack (sometimes by multiple stacks).
This is a classical way to implement local variables of a re-entrant or recursive subprogram. Stacks are also used to describe a formal computational framework.
See stack machine.
Many algorithms in pattern matching, compiler construction (e.g. recursive descent parsers), and machine learning (e.g. based on tree traversal) have a natural representation in terms of stacks.
Task
Create a stack supporting the basic operations: push, pop, 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
| #11l | 11l | [Int] stack
L(i) 1..10
stack.append(i)
L 10
print(stack.pop()) |
http://rosettacode.org/wiki/Square_but_not_cube | Square but not cube | Task
Show the first 30 positive integers which are squares but not cubes of such integers.
Optionally, show also the first 3 positive integers which are both squares and cubes, and mark them as such.
| #Action.21 | Action! | BYTE FUNC IsCube(INT n)
INT i,c
i=1
DO
c=i*i*i
IF c=n THEN
RETURN (1)
FI
i==+1
UNTIL c>n
OD
RETURN (0)
PROC Main()
INT n,sq,count
PrintE("First 30 squares but not cubes:")
n=1 count=0
WHILE count<30
DO
sq=n*n
IF IsCube(sq)=0 THEN
PrintF("%I ",sq)
count==+1
FI
n==+1
OD
PutE() PutE()
PrintE("First 3 squares and cubes:")
n=1 count=0
WHILE count<3
DO
sq=n*n
IF IsCube(sq) THEN
PrintF("%I ",sq)
count==+1
FI
n==+1
OD
RETURN |
http://rosettacode.org/wiki/Square_but_not_cube | Square but not cube | Task
Show the first 30 positive integers which are squares but not cubes of such integers.
Optionally, show also the first 3 positive integers which are both squares and cubes, and mark them as such.
| #Ada | Ada | with Ada.Text_IO;
procedure Square_But_Not_Cube is
function Is_Cube (N : in Positive) return Boolean is
Cube : Positive;
begin
for I in Positive loop
Cube := I**3;
if Cube = N then return True;
elsif Cube > N then return False;
end if;
end loop;
raise Program_Error;
end Is_Cube;
procedure Show (Limit : in Natural) is
Count : Natural := 0;
Square : Natural;
use Ada.Text_IO;
begin
for N in Positive loop
Square := N**2;
if not Is_Cube (Square) then
Count := Count + 1;
Put (Square'Image);
exit when Count = Limit;
end if;
end loop;
New_Line;
end Show;
begin
Show (Limit => 30);
end Square_But_Not_Cube; |
http://rosettacode.org/wiki/Square_form_factorization | Square form factorization | Task.
Daniel Shanks's Square Form Factorization (SquFoF).
Invented around 1975, ‘On a 32-bit computer, SquFoF is the clear champion factoring algorithm
for numbers between 1010 and 1018, and will likely remain so.’
An integral binary quadratic form is a polynomial
f(x,y) = ax2 + bxy + cy2
with integer coefficients and discriminant D = b2 – 4ac.
For each positive discriminant there are multiple forms (a, b, c).
The next form in a periodic sequence (cycle) of adjacent forms is found by applying a reduction operator
rho, essentially a variant of Euclid's algorithm for finding the continued fraction of a square root.
Using floor(√N), rho constructs a principal form
(1, b, c) with D = 4N.
SquFoF is based on the existence of cycles containing ambiguous forms, with the property that a divides b.
They come in pairs of associated forms (a, b, c) and (c, b, a) called symmetry points.
If an ambiguous form is found (there is one for each divisor of D), write the discriminant as
(ak)2 – 4ac = a(a·k2 – 4c) = 4N
and (if a is not equal to 1 or 2) N is split.
Shanks used square forms to jump to a random ambiguous cycle. Fact: if any form in an ambiguous cycle
is squared, that square form will always land in the principal cycle. Conversely, the square root of any
form in the principal cycle lies in an ambiguous cycle. (Possibly the principal cycle itself).
A square form is easy to find: the last coefficient c is a perfect square. This happens about once
every ∜N-th cycle step and for even indices only. Let rho compute the inverse square root form and track
the ambiguous cycle backward until the symmetry point is reached. (Taking the inverse reverses the cycle).
Then a or a/2 divides D and therefore N.
To avoid trivial factorizations, Shanks created a list (queue) to hold small coefficients appearing
early in the principal cycle, that may be roots of square forms found later on. If these forms are skipped,
no roots land in the principal cycle itself and cases a = 1 or a = 2 do not happen.
Sometimes the cycle length is too short to find a proper square form. This is fixed by running five instances
of SquFoF in parallel, with input N and 3, 5, 7, 11 times N; the discriminants then will have different periods.
If N is prime or the cube of a prime, there are improper squares only and the program will duly report failure.
Reference.
[1] A detailed analysis of SquFoF (2007)
| #Phix | Phix | --requires(64) -- (decided to limit 32-bit explicitly instead)
constant MxN = power(2,iff(machine_bits()=32?53:63)),
m = {1, 3, 5, 7, 11}
function squfof(atom N)
-- square form factorization
integer h, a=0, b, c, u=0, v, w, rN, q, r, t
if remainder(N,2)==0 then return 2 end if
h = floor(sqrt(N) + 0.5)
if h*h==N then return h end if
for k=1 to length(m) do
integer mk = m[k]
if mk>1 and remainder(N,mk)==0 then return mk end if
//check overflow m * N
if N>MxN/mk then exit end if
atom mN = N*mk
r = floor(sqrt(mN))
if r*r>mN then r -= 1 end if
rN = r
//principal form
{b,a} = {r,1}
h = floor((rN+b)/a)*a-b
c = floor((mN-h*h)/a)
for i=2 to floor(sqrt(2*r)) * 4-1 do
//search principal cycle
{a,c,t} = {c,a,b}
q = floor((rN+b)/a)
b = q*a-b
c += q*(t-b)
if remainder(i,2)==0 then
r = floor(sqrt(c)+0.5)
if r*r==c then
//square form found
//inverse square root
q = floor((rN-b)/r)
v = q*r+b
w = floor((mN-v*v)/r)
//search ambiguous cycle
u = r
while true do
{u,w,r} = {w,u,v}
q = floor((rN+v)/u)
v = q*u-v
if v==r then exit end if
w += q*(r-v)
end while
//symmetry point
h = gcd(N,u)
if h!= |
http://rosettacode.org/wiki/Statistics/Basic | Statistics/Basic | Statistics is all about large groups of numbers.
When talking about a set of sampled data, most frequently used is their mean value and standard deviation (stddev).
If you have set of data
x
i
{\displaystyle x_{i}}
where
i
=
1
,
2
,
…
,
n
{\displaystyle i=1,2,\ldots ,n\,\!}
, the mean is
x
¯
≡
1
n
∑
i
x
i
{\displaystyle {\bar {x}}\equiv {1 \over n}\sum _{i}x_{i}}
, while the stddev is
σ
≡
1
n
∑
i
(
x
i
−
x
¯
)
2
{\displaystyle \sigma \equiv {\sqrt {{1 \over n}\sum _{i}\left(x_{i}-{\bar {x}}\right)^{2}}}}
.
When examining a large quantity of data, one often uses a histogram, which shows the counts of data samples falling into a prechosen set of intervals (or bins).
When plotted, often as bar graphs, it visually indicates how often each data value occurs.
Task Using your language's random number routine, generate real numbers in the range of [0, 1]. It doesn't matter if you chose to use open or closed range.
Create 100 of such numbers (i.e. sample size 100) and calculate their mean and stddev.
Do so for sample size of 1,000 and 10,000, maybe even higher if you feel like.
Show a histogram of any of these sets.
Do you notice some patterns about the standard deviation?
Extra Sometimes so much data need to be processed that it's impossible to keep all of them at once. Can you calculate the mean, stddev and histogram of a trillion numbers? (You don't really need to do a trillion numbers, just show how it can be done.)
Hint
For a finite population with equal probabilities at all points, one can derive:
(
x
−
x
¯
)
2
¯
=
x
2
¯
−
x
¯
2
{\displaystyle {\overline {(x-{\overline {x}})^{2}}}={\overline {x^{2}}}-{\overline {x}}^{2}}
Or, more verbosely:
1
N
∑
i
=
1
N
(
x
i
−
x
¯
)
2
=
1
N
(
∑
i
=
1
N
x
i
2
)
−
x
¯
2
.
{\displaystyle {\frac {1}{N}}\sum _{i=1}^{N}(x_{i}-{\overline {x}})^{2}={\frac {1}{N}}\left(\sum _{i=1}^{N}x_{i}^{2}\right)-{\overline {x}}^{2}.}
See also
Statistics/Normal distribution
Tasks for calculating statistical measures
in one go
moving (sliding window)
moving (cumulative)
Mean
Arithmetic
Statistics/Basic
Averages/Arithmetic mean
Averages/Pythagorean means
Averages/Simple moving average
Geometric
Averages/Pythagorean means
Harmonic
Averages/Pythagorean means
Quadratic
Averages/Root mean square
Circular
Averages/Mean angle
Averages/Mean time of day
Median
Averages/Median
Mode
Averages/Mode
Standard deviation
Statistics/Basic
Cumulative standard deviation
| #C.2B.2B | C++ | #include <iostream>
#include <random>
#include <vector>
#include <cstdlib>
#include <algorithm>
#include <cmath>
void printStars ( int number ) {
if ( number > 0 ) {
for ( int i = 0 ; i < number + 1 ; i++ )
std::cout << '*' ;
}
std::cout << '\n' ;
}
int main( int argc , char *argv[] ) {
const int numberOfRandoms = std::atoi( argv[1] ) ;
std::random_device rd ;
std::mt19937 gen( rd( ) ) ;
std::uniform_real_distribution<> distri( 0.0 , 1.0 ) ;
std::vector<double> randoms ;
for ( int i = 0 ; i < numberOfRandoms + 1 ; i++ )
randoms.push_back ( distri( gen ) ) ;
std::sort ( randoms.begin( ) , randoms.end( ) ) ;
double start = 0.0 ;
for ( int i = 0 ; i < 9 ; i++ ) {
double to = start + 0.1 ;
int howmany = std::count_if ( randoms.begin( ) , randoms.end( ),
[&start , &to] ( double c ) { return c >= start
&& c < to ; } ) ;
if ( start == 0.0 ) //double 0.0 output as 0
std::cout << "0.0" << " - " << to << ": " ;
else
std::cout << start << " - " << to << ": " ;
if ( howmany > 50 ) //scales big interval numbers to printable length
howmany = howmany / ( howmany / 50 ) ;
printStars ( howmany ) ;
start += 0.1 ;
}
double mean = std::accumulate( randoms.begin( ) , randoms.end( ) , 0.0 ) / randoms.size( ) ;
double sum = 0.0 ;
for ( double num : randoms )
sum += std::pow( num - mean , 2 ) ;
double stddev = std::pow( sum / randoms.size( ) , 0.5 ) ;
std::cout << "The mean is " << mean << " !" << std::endl ;
std::cout << "Standard deviation is " << stddev << " !" << std::endl ;
return 0 ;
} |
http://rosettacode.org/wiki/Square-free_integers | Square-free integers | Task
Write a function to test if a number is square-free.
A square-free is an integer which is divisible by no perfect square other
than 1 (unity).
For this task, only positive square-free numbers will be used.
Show here (on this page) all square-free integers (in a horizontal format) that are between:
1 ───► 145 (inclusive)
1 trillion ───► 1 trillion + 145 (inclusive)
(One trillion = 1,000,000,000,000)
Show here (on this page) the count of square-free integers from:
1 ───► one hundred (inclusive)
1 ───► one thousand (inclusive)
1 ───► ten thousand (inclusive)
1 ───► one hundred thousand (inclusive)
1 ───► one million (inclusive)
See also
the Wikipedia entry: square-free integer
| #Go | Go | package main
import (
"fmt"
"math"
)
func sieve(limit uint64) []uint64 {
primes := []uint64{2}
c := make([]bool, limit+1) // composite = true
// no need to process even numbers > 2
p := uint64(3)
for {
p2 := p * p
if p2 > limit {
break
}
for i := p2; i <= limit; i += 2 * p {
c[i] = true
}
for {
p += 2
if !c[p] {
break
}
}
}
for i := uint64(3); i <= limit; i += 2 {
if !c[i] {
primes = append(primes, i)
}
}
return primes
}
func squareFree(from, to uint64) (results []uint64) {
limit := uint64(math.Sqrt(float64(to)))
primes := sieve(limit)
outer:
for i := from; i <= to; i++ {
for _, p := range primes {
p2 := p * p
if p2 > i {
break
}
if i%p2 == 0 {
continue outer
}
}
results = append(results, i)
}
return
}
const trillion uint64 = 1000000000000
func main() {
fmt.Println("Square-free integers from 1 to 145:")
sf := squareFree(1, 145)
for i := 0; i < len(sf); i++ {
if i > 0 && i%20 == 0 {
fmt.Println()
}
fmt.Printf("%4d", sf[i])
}
fmt.Printf("\n\nSquare-free integers from %d to %d:\n", trillion, trillion+145)
sf = squareFree(trillion, trillion+145)
for i := 0; i < len(sf); i++ {
if i > 0 && i%5 == 0 {
fmt.Println()
}
fmt.Printf("%14d", sf[i])
}
fmt.Println("\n\nNumber of square-free integers:\n")
a := [...]uint64{100, 1000, 10000, 100000, 1000000}
for _, n := range a {
fmt.Printf(" from %d to %d = %d\n", 1, n, len(squareFree(1, n)))
}
} |
http://rosettacode.org/wiki/State_name_puzzle | State name puzzle | Background
This task is inspired by Mark Nelson's DDJ Column "Wordplay" and one of the weekly puzzle challenges from Will Shortz on NPR Weekend Edition [1] and originally attributed to David Edelheit.
The challenge was to take the names of two U.S. States, mix them all together, then rearrange the letters to form the names of two different U.S. States (so that all four state names differ from one another).
What states are these?
The problem was reissued on the Unicon Discussion Web which includes several solutions with analysis. Several techniques may be helpful and you may wish to refer to Gödel numbering, equivalence relations, and equivalence classes. The basic merits of these were discussed in the Unicon Discussion Web.
A second challenge in the form of a set of fictitious new states was also presented.
Task
Write a program to solve the challenge using both the original list of states and the fictitious list.
Caveats
case and spacing aren't significant - just letters (harmonize case)
don't expect the names to be in any order - such as being sorted
don't rely on names to be unique (eliminate duplicates - meaning if Iowa appears twice you can only use it once)
Comma separated list of state names used in the original puzzle:
"Alabama", "Alaska", "Arizona", "Arkansas",
"California", "Colorado", "Connecticut", "Delaware",
"Florida", "Georgia", "Hawaii", "Idaho", "Illinois",
"Indiana", "Iowa", "Kansas", "Kentucky", "Louisiana",
"Maine", "Maryland", "Massachusetts", "Michigan",
"Minnesota", "Mississippi", "Missouri", "Montana",
"Nebraska", "Nevada", "New Hampshire", "New Jersey",
"New Mexico", "New York", "North Carolina", "North Dakota",
"Ohio", "Oklahoma", "Oregon", "Pennsylvania", "Rhode Island",
"South Carolina", "South Dakota", "Tennessee", "Texas",
"Utah", "Vermont", "Virginia",
"Washington", "West Virginia", "Wisconsin", "Wyoming"
Comma separated list of additional fictitious state names to be added to the original (Includes a duplicate):
"New Kory", "Wen Kory", "York New", "Kory New", "New Kory"
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
| #Ruby | Ruby | require 'set'
# 26 prime numbers
Primes = [ 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41,
43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101]
States = [
"Alabama", "Alaska", "Arizona", "Arkansas", "California", "Colorado",
"Connecticut", "Delaware", "Florida", "Georgia", "Hawaii", "Idaho",
"Illinois", "Indiana", "Iowa", "Kansas", "Kentucky", "Louisiana", "Maine",
"Maryland", "Massachusetts", "Michigan", "Minnesota", "Mississippi",
"Missouri", "Montana", "Nebraska", "Nevada", "New Hampshire", "New Jersey",
"New Mexico", "New York", "North Carolina", "North Dakota", "Ohio",
"Oklahoma", "Oregon", "Pennsylvania", "Rhode Island", "South Carolina",
"South Dakota", "Tennessee", "Texas", "Utah", "Vermont", "Virginia",
"Washington", "West Virginia", "Wisconsin", "Wyoming"
]
def print_answer(states)
# find goedel numbers for all pairs of states
goedel = lambda {|str| str.chars.map {|c| Primes[c.ord - 65]}.reduce(:*)}
pairs = Hash.new {|h,k| h[k] = Array.new}
map = states.uniq.map {|state| [state, goedel[state.upcase.delete("^A-Z")]]}
map.combination(2) {|(s1,g1), (s2,g2)| pairs[g1 * g2] << [s1, s2]}
# find pairs without duplicates
result = []
pairs.values.select {|val| val.length > 1}.each do |list_of_pairs|
list_of_pairs.combination(2) do |pair1, pair2|
if Set[*pair1, *pair2].length == 4
result << [pair1, pair2]
end
end
end
# output the results
result.each_with_index do |(pair1, pair2), i|
puts "%d\t%s\t%s" % [i+1, pair1.join(', '), pair2.join(', ')]
end
end
puts "real states only"
print_answer(States)
puts ""
puts "with fictional states"
print_answer(States + ["New Kory", "Wen Kory", "York New", "Kory New", "New Kory"]) |
http://rosettacode.org/wiki/String_append | String append |
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
Concatenation |
Interpolation |
Comparison |
Matching
Memory Operations
Pointers & references |
Addresses
Most languages provide a way to concatenate two string values, but some languages also provide a convenient way to append in-place to an existing string variable without referring to the variable twice.
Task
Create a string variable equal to any text value.
Append the string variable with another string literal in the most idiomatic way, without double reference if your language supports it.
Show the contents of the variable after the append operation.
| #Sidef | Sidef | var str = 'Foo';
str += 'bar';
say str; |
http://rosettacode.org/wiki/String_append | String append |
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
Concatenation |
Interpolation |
Comparison |
Matching
Memory Operations
Pointers & references |
Addresses
Most languages provide a way to concatenate two string values, but some languages also provide a convenient way to append in-place to an existing string variable without referring to the variable twice.
Task
Create a string variable equal to any text value.
Append the string variable with another string literal in the most idiomatic way, without double reference if your language supports it.
Show the contents of the variable after the append operation.
| #SNOBOL4 | SNOBOL4 | s = "Hello"
s = s ", World!"
OUTPUT = s
END |
http://rosettacode.org/wiki/String_append | String append |
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
Concatenation |
Interpolation |
Comparison |
Matching
Memory Operations
Pointers & references |
Addresses
Most languages provide a way to concatenate two string values, but some languages also provide a convenient way to append in-place to an existing string variable without referring to the variable twice.
Task
Create a string variable equal to any text value.
Append the string variable with another string literal in the most idiomatic way, without double reference if your language supports it.
Show the contents of the variable after the append operation.
| #Stata | Stata | sca s="Ars Longa"
sca s=s+" Vita Brevis"
di s
Ars Longa Vita Brevis |
http://rosettacode.org/wiki/Statistics/Normal_distribution | Statistics/Normal distribution | The Normal (or Gaussian) distribution is a frequently used distribution in statistics. While most programming languages provide a uniformly distributed random number generator, one can derive normally distributed random numbers from a uniform generator.
The task
Take a uniform random number generator and create a large (you decide how large) set of numbers that follow a normal (Gaussian) distribution. Calculate the dataset's mean and standard deviation, and show a histogram of the data.
Mention any native language support for the generation of normally distributed random numbers.
Reference
You may refer to code in Statistics/Basic if available.
| #Run_BASIC | Run BASIC |
s = 100000
h$ = "============================================================="
h$ = h$ + h$
dim ndis(s)
' mean and standard deviation.
mx = -9999
mn = 9999
sum = 0
sumSqr = 0
for i = 1 to s ' find minimum and maximum
ms = rnd(1)
ss = rnd(1)
nd = (-2 * log(ms))^0.5 * cos(2 *3.14159265 * ss) ' normal distribution
ndis(i) = nd
mx = max(mx, nd)
mn = min(mn, nd)
sum = sum + nd
sumSqr = sumSqr + nd ^ 2
next i
mean = sum / s
range = mx - mn
print "Samples :"; s
print "Largest :"; mx
print "Smallest :"; mn
print "Range :"; range
print "Mean :"; mean
print "Stand Dev :"; (sumSqr /s -mean^2)^0.5
'Show chart of histogram
nBins = 50
dim bins(nBins)
for i = 1 to s
z = int((ndis(i) -mn) /range *nBins)
bins(z) = bins(z) + 1
mb = max(bins(z),mb)
next i
for b = 0 to nBins -1
print using("##",b);" ";using("#####",bins(b));" ";left$(h$,(bins(b) / mb) * 90)
next b
END |
http://rosettacode.org/wiki/Statistics/Normal_distribution | Statistics/Normal distribution | The Normal (or Gaussian) distribution is a frequently used distribution in statistics. While most programming languages provide a uniformly distributed random number generator, one can derive normally distributed random numbers from a uniform generator.
The task
Take a uniform random number generator and create a large (you decide how large) set of numbers that follow a normal (Gaussian) distribution. Calculate the dataset's mean and standard deviation, and show a histogram of the data.
Mention any native language support for the generation of normally distributed random numbers.
Reference
You may refer to code in Statistics/Basic if available.
| #Rust | Rust | //! Rust rosetta example for normal distribution
use math::{histogram::Histogram, traits::ToIterator};
use rand;
use rand_distr::{Distribution, Normal};
/// Returns the mean of the provided samples
///
/// ## Arguments
/// * data -- reference to float32 array
fn mean(data: &[f32]) -> Option<f32> {
let sum: f32 = data.iter().sum();
Some(sum / data.len() as f32)
}
/// Returns standard deviation of the provided samples
///
/// ## Arguments
/// * data -- reference to float32 array
fn standard_deviation(data: &[f32]) -> Option<f32> {
let mean = mean(data).expect("invalid mean");
let sum = data.iter().fold(0.0, |acc, &x| acc + (x - mean).powi(2));
Some((sum / data.len() as f32).sqrt())
}
/// Prints a histogram in the shell
///
/// ## Arguments
/// * data -- reference to float32 array
/// * maxwidth -- the maxwidth of the histogram in # of characters
/// * bincount -- number of bins in the histogram
/// * ch -- character used to plot the graph
fn print_histogram(data: &[f32], maxwidth: usize, bincount: usize, ch: char) {
let min_val = data.iter().cloned().fold(f32::NAN, f32::min);
let max_val = data.iter().cloned().fold(f32::NAN, f32::max);
let histogram = Histogram::new(Some(&data.to_vec()), bincount, min_val, max_val).unwrap();
let max_bin_value = histogram.get_counters().iter().max().unwrap();
println!();
for x in histogram.to_iter() {
let (bin_min, bin_max, freq) = x;
let bar_width = (((freq as f64) / (*max_bin_value as f64)) * (maxwidth as f64)) as u32;
let bar_as_string = (1..bar_width).fold(String::new(), |b, _| b + &ch.to_string());
println!(
"({:>6},{:>6}) |{} {:.2}%",
format!("{:.2}", bin_min),
format!("{:.2}", bin_max),
bar_as_string,
(freq as f64) * 100.0 / (data.len() as f64)
);
}
println!();
}
/// Runs the demo to generate normal distribution of three different sample sizes
fn main() {
let expected_mean: f32 = 0.0;
let expected_std_deviation: f32 = 4.0;
let normal = Normal::new(expected_mean, expected_std_deviation).unwrap();
let mut rng = rand::thread_rng();
for &number_of_samples in &[1000, 10_000, 1_000_000] {
let data: Vec<f32> = normal
.sample_iter(&mut rng)
.take(number_of_samples)
.collect();
println!("Statistics for sample size {}:", number_of_samples);
println!("\tMean: {:?}", mean(&data).expect("invalid mean"));
println!(
"\tStandard deviation: {:?}",
standard_deviation(&data).expect("invalid standard deviation")
);
print_histogram(&data, 80, 40, '-');
}
} |
http://rosettacode.org/wiki/Stem-and-leaf_plot | Stem-and-leaf plot | Create a well-formatted stem-and-leaf plot from the following data set, where the leaves are the last digits:
12 127 28 42 39 113 42 18 44 118 44 37 113 124 37 48 127 36 29 31 125 139 131 115 105 132 104 123 35 113 122 42 117 119 58 109 23 105 63 27 44 105 99 41 128 121 116 125 32 61 37 127 29 113 121 58 114 126 53 114 96 25 109 7 31 141 46 13 27 43 117 116 27 7 68 40 31 115 124 42 128 52 71 118 117 38 27 106 33 117 116 111 40 119 47 105 57 122 109 124 115 43 120 43 27 27 18 28 48 125 107 114 34 133 45 120 30 127 31 116 146
The primary intent of this task is the presentation of information. It is acceptable to hardcode the data set or characteristics of it (such as what the stems are) in the example, insofar as it is impractical to make the example generic to any data set. For example, in a computation-less language like HTML the data set may be entirely prearranged within the example; the interesting characteristics are how the proper visual formatting is arranged.
If possible, the output should not be a bitmap image. Monospaced plain text is acceptable, but do better if you can. It may be a window, i.e. not a file.
Note: If you wish to try multiple data sets, you might try this generator.
| #Julia | Julia |
function stemleaf{T<:Real}(a::Array{T,1}, leafsize=1)
ls = 10^int(log10(leafsize))
(stem, leaf) = divrem(sort(int(a/ls)), 10)
leaf[sign(stem) .== -1] *= -1
negzero = leaf .< 0
if any(negzero)
leaf[negzero] *= -1
nz = @sprintf "%10s | " "-0"
nz *= join(map(string, leaf[negzero]), " ")
nz *= "\n"
stem = stem[!negzero]
leaf = leaf[!negzero]
else
nz = ""
end
slp = ""
for i in stem[1]:stem[end]
i != 0 || (slp *= nz)
slp *= @sprintf "%10d | " i
slp *= join(map(string, leaf[stem .== i]), " ")
slp *= "\n"
end
slp *= " Leaf Unit = " * string(convert(T, ls)) * "\n"
return slp
end
|
http://rosettacode.org/wiki/Stern-Brocot_sequence | Stern-Brocot sequence | For this task, the Stern-Brocot sequence is to be generated by an algorithm similar to that employed in generating the Fibonacci sequence.
The first and second members of the sequence are both 1:
1, 1
Start by considering the second member of the sequence
Sum the considered member of the sequence and its precedent, (1 + 1) = 2, and append it to the end of the sequence:
1, 1, 2
Append the considered member of the sequence to the end of the sequence:
1, 1, 2, 1
Consider the next member of the series, (the third member i.e. 2)
GOTO 3
─── Expanding another loop we get: ───
Sum the considered member of the sequence and its precedent, (2 + 1) = 3, and append it to the end of the sequence:
1, 1, 2, 1, 3
Append the considered member of the sequence to the end of the sequence:
1, 1, 2, 1, 3, 2
Consider the next member of the series, (the fourth member i.e. 1)
The task is to
Create a function/method/subroutine/procedure/... to generate the Stern-Brocot sequence of integers using the method outlined above.
Show the first fifteen members of the sequence. (This should be: 1, 1, 2, 1, 3, 2, 3, 1, 4, 3, 5, 2, 5, 3, 4)
Show the (1-based) index of where the numbers 1-to-10 first appears in the sequence.
Show the (1-based) index of where the number 100 first appears in the sequence.
Check that the greatest common divisor of all the two consecutive members of the series up to the 1000th member, is always one.
Show your output on this page.
Related tasks
Fusc sequence.
Continued fraction/Arithmetic
Ref
Infinite Fractions - Numberphile (Video).
Trees, Teeth, and Time: The mathematics of clock making.
A002487 The On-Line Encyclopedia of Integer Sequences.
| #Haskell | Haskell | import Data.List (elemIndex)
sb :: [Int]
sb = 1 : 1 : f (tail sb) sb
where
f (a : aa) (b : bb) = a + b : a : f aa bb
main :: IO ()
main = do
print $ take 15 sb
print
[ (i, 1 + (\(Just i) -> i) (elemIndex i sb))
| i <- [1 .. 10] <> [100]
]
print $
all (\(a, b) -> 1 == gcd a b) $
take 1000 $ zip sb (tail sb) |
http://rosettacode.org/wiki/Stack_traces | Stack traces | Many programming languages allow for introspection of the current call stack environment. This can be for a variety of purposes such as enforcing security checks, debugging, or for getting access to the stack frame of callers.
Task
Print out (in a manner considered suitable for the platform) the current call stack.
The amount of information printed for each frame on the call stack is not constrained, but should include at least the name of the function or method at that level of the stack frame.
You may explicitly add a call to produce the stack trace to the (example) code being instrumented for examination.
The task should allow the program to continue after generating the stack trace.
The task report here must include the trace from a sample program.
| #PL.2FI | PL/I |
/* The SNAP option in the ON statement is sufficient to obtain */
/* a traceback. The SYSTEM option specifies that standard */
/* system action is to occur, which resume execution after the */
/* SIGNAL statement. */
on condition(traceback) snap system;
...
signal condition(traceback);
|
http://rosettacode.org/wiki/Stack_traces | Stack traces | Many programming languages allow for introspection of the current call stack environment. This can be for a variety of purposes such as enforcing security checks, debugging, or for getting access to the stack frame of callers.
Task
Print out (in a manner considered suitable for the platform) the current call stack.
The amount of information printed for each frame on the call stack is not constrained, but should include at least the name of the function or method at that level of the stack frame.
You may explicitly add a call to produce the stack trace to the (example) code being instrumented for examination.
The task should allow the program to continue after generating the stack trace.
The task report here must include the trace from a sample program.
| #PureBasic | PureBasic | Procedure Three()
a=7
ShowCallstack()
CallDebugger
EndProcedure
Procedure Two()
a=4
Three()
EndProcedure
Procedure One()
a=2
Two()
EndProcedure
One() |
http://rosettacode.org/wiki/Stack_traces | Stack traces | Many programming languages allow for introspection of the current call stack environment. This can be for a variety of purposes such as enforcing security checks, debugging, or for getting access to the stack frame of callers.
Task
Print out (in a manner considered suitable for the platform) the current call stack.
The amount of information printed for each frame on the call stack is not constrained, but should include at least the name of the function or method at that level of the stack frame.
You may explicitly add a call to produce the stack trace to the (example) code being instrumented for examination.
The task should allow the program to continue after generating the stack trace.
The task report here must include the trace from a sample program.
| #Python | Python | import traceback
def f(): return g()
def g(): traceback.print_stack()
f() |
http://rosettacode.org/wiki/Stair-climbing_puzzle | Stair-climbing puzzle | From Chung-Chieh Shan (LtU):
Your stair-climbing robot has a very simple low-level API: the "step" function takes no argument and attempts to climb one step as a side effect. Unfortunately, sometimes the attempt fails and the robot clumsily falls one step instead. The "step" function detects what happens and returns a boolean flag: true on success, false on failure.
Write a function "step_up" that climbs one step up [from the initial position] (by repeating "step" attempts if necessary). Assume that the robot is not already at the top of the stairs, and neither does it ever reach the bottom of the stairs. How small can you make "step_up"? Can you avoid using variables (even immutable ones) and numbers?
Here's a pseudo-code of a simple recursive solution without using variables:
func step_up()
{
if not step() {
step_up();
step_up();
}
}
Inductive proof that step_up() steps up one step, if it terminates:
Base case (if the step() call returns true): it stepped up one step. QED
Inductive case (if the step() call returns false): Assume that recursive calls to step_up() step up one step. It stepped down one step (because step() returned false), but now we step up two steps using two step_up() calls. QED
The second (tail) recursion above can be turned into an iteration, as follows:
func step_up()
{
while not step() {
step_up();
}
}
| #OCaml | OCaml | let rec step_up() =
while not(step()) do
step_up()
done
;; |
http://rosettacode.org/wiki/Stair-climbing_puzzle | Stair-climbing puzzle | From Chung-Chieh Shan (LtU):
Your stair-climbing robot has a very simple low-level API: the "step" function takes no argument and attempts to climb one step as a side effect. Unfortunately, sometimes the attempt fails and the robot clumsily falls one step instead. The "step" function detects what happens and returns a boolean flag: true on success, false on failure.
Write a function "step_up" that climbs one step up [from the initial position] (by repeating "step" attempts if necessary). Assume that the robot is not already at the top of the stairs, and neither does it ever reach the bottom of the stairs. How small can you make "step_up"? Can you avoid using variables (even immutable ones) and numbers?
Here's a pseudo-code of a simple recursive solution without using variables:
func step_up()
{
if not step() {
step_up();
step_up();
}
}
Inductive proof that step_up() steps up one step, if it terminates:
Base case (if the step() call returns true): it stepped up one step. QED
Inductive case (if the step() call returns false): Assume that recursive calls to step_up() step up one step. It stepped down one step (because step() returned false), but now we step up two steps using two step_up() calls. QED
The second (tail) recursion above can be turned into an iteration, as follows:
func step_up()
{
while not step() {
step_up();
}
}
| #Oz | Oz | proc {StepUp}
if {Not {Step}} then
{StepUp} %% make up for the fall
{StepUp} %% repeat original attempt
end
end |
http://rosettacode.org/wiki/Stack | Stack |
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.
A stack is a container of elements with last in, first out access policy. Sometimes it also called LIFO.
The stack is accessed through its top.
The basic stack operations are:
push stores a new element onto the stack top;
pop returns the last pushed stack element, while removing it from the stack;
empty tests if the stack contains no elements.
Sometimes the last pushed stack element is made accessible for immutable access (for read) or mutable access (for write):
top (sometimes called peek to keep with the p theme) returns the topmost element without modifying the stack.
Stacks allow a very simple hardware implementation.
They are common in almost all processors.
In programming, stacks are also very popular for their way (LIFO) of resource management, usually memory.
Nested scopes of language objects are naturally implemented by a stack (sometimes by multiple stacks).
This is a classical way to implement local variables of a re-entrant or recursive subprogram. Stacks are also used to describe a formal computational framework.
See stack machine.
Many algorithms in pattern matching, compiler construction (e.g. recursive descent parsers), and machine learning (e.g. based on tree traversal) have a natural representation in terms of stacks.
Task
Create a stack supporting the basic operations: push, pop, 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
| #6502_Assembly | 6502 Assembly | PHA |
http://rosettacode.org/wiki/Square_but_not_cube | Square but not cube | Task
Show the first 30 positive integers which are squares but not cubes of such integers.
Optionally, show also the first 3 positive integers which are both squares and cubes, and mark them as such.
| #ALGOL_68 | ALGOL 68 | BEGIN
# list the first 30 numbers that are squares but not cubes and also #
# show the numbers that are both squares and cubes #
INT count := 0;
INT c := 1;
INT c3 := 1;
FOR s WHILE count < 30 DO
INT sq = s * s;
WHILE c3 < sq DO
c +:= 1;
c3 := c * c * c
OD;
print( ( whole( sq, -5 ) ) );
IF c3 = sq THEN
# the square is also a cube #
print( ( " is also the cube of ", whole( c, -5 ) ) )
ELSE
# square only #
count +:= 1
FI;
print( ( newline ) )
OD
END |
http://rosettacode.org/wiki/Statistics/Basic | Statistics/Basic | Statistics is all about large groups of numbers.
When talking about a set of sampled data, most frequently used is their mean value and standard deviation (stddev).
If you have set of data
x
i
{\displaystyle x_{i}}
where
i
=
1
,
2
,
…
,
n
{\displaystyle i=1,2,\ldots ,n\,\!}
, the mean is
x
¯
≡
1
n
∑
i
x
i
{\displaystyle {\bar {x}}\equiv {1 \over n}\sum _{i}x_{i}}
, while the stddev is
σ
≡
1
n
∑
i
(
x
i
−
x
¯
)
2
{\displaystyle \sigma \equiv {\sqrt {{1 \over n}\sum _{i}\left(x_{i}-{\bar {x}}\right)^{2}}}}
.
When examining a large quantity of data, one often uses a histogram, which shows the counts of data samples falling into a prechosen set of intervals (or bins).
When plotted, often as bar graphs, it visually indicates how often each data value occurs.
Task Using your language's random number routine, generate real numbers in the range of [0, 1]. It doesn't matter if you chose to use open or closed range.
Create 100 of such numbers (i.e. sample size 100) and calculate their mean and stddev.
Do so for sample size of 1,000 and 10,000, maybe even higher if you feel like.
Show a histogram of any of these sets.
Do you notice some patterns about the standard deviation?
Extra Sometimes so much data need to be processed that it's impossible to keep all of them at once. Can you calculate the mean, stddev and histogram of a trillion numbers? (You don't really need to do a trillion numbers, just show how it can be done.)
Hint
For a finite population with equal probabilities at all points, one can derive:
(
x
−
x
¯
)
2
¯
=
x
2
¯
−
x
¯
2
{\displaystyle {\overline {(x-{\overline {x}})^{2}}}={\overline {x^{2}}}-{\overline {x}}^{2}}
Or, more verbosely:
1
N
∑
i
=
1
N
(
x
i
−
x
¯
)
2
=
1
N
(
∑
i
=
1
N
x
i
2
)
−
x
¯
2
.
{\displaystyle {\frac {1}{N}}\sum _{i=1}^{N}(x_{i}-{\overline {x}})^{2}={\frac {1}{N}}\left(\sum _{i=1}^{N}x_{i}^{2}\right)-{\overline {x}}^{2}.}
See also
Statistics/Normal distribution
Tasks for calculating statistical measures
in one go
moving (sliding window)
moving (cumulative)
Mean
Arithmetic
Statistics/Basic
Averages/Arithmetic mean
Averages/Pythagorean means
Averages/Simple moving average
Geometric
Averages/Pythagorean means
Harmonic
Averages/Pythagorean means
Quadratic
Averages/Root mean square
Circular
Averages/Mean angle
Averages/Mean time of day
Median
Averages/Median
Mode
Averages/Mode
Standard deviation
Statistics/Basic
Cumulative standard deviation
| #CoffeeScript | CoffeeScript |
generate_statistics = (n) ->
hist = {}
update_hist = (r) ->
hist[Math.floor 10*r] ||= 0
hist[Math.floor 10*r] += 1
sum = 0
sum_squares = 0.0
for i in [1..n]
r = Math.random()
sum += r
sum_squares += r*r
update_hist r
mean = sum / n
stddev = Math.sqrt((sum_squares / n) - mean*mean)
[n, mean, stddev, hist]
display_statistics = (n, mean, stddev, hist) ->
console.log "-- Stats for sample size #{n}"
console.log "mean: #{mean}"
console.log "sdev: #{stddev}"
for x, cnt of hist
bars = repeat "=", Math.floor(cnt*300/n)
console.log "#{x/10}: #{bars} #{cnt}"
repeat = (c, n) ->
s = ''
s += c for i in [1..n]
s
for n in [100, 1000, 10000, 1000000]
[n, mean, stddev, hist] = generate_statistics n
display_statistics n, mean, stddev, hist
|
http://rosettacode.org/wiki/Square-free_integers | Square-free integers | Task
Write a function to test if a number is square-free.
A square-free is an integer which is divisible by no perfect square other
than 1 (unity).
For this task, only positive square-free numbers will be used.
Show here (on this page) all square-free integers (in a horizontal format) that are between:
1 ───► 145 (inclusive)
1 trillion ───► 1 trillion + 145 (inclusive)
(One trillion = 1,000,000,000,000)
Show here (on this page) the count of square-free integers from:
1 ───► one hundred (inclusive)
1 ───► one thousand (inclusive)
1 ───► ten thousand (inclusive)
1 ───► one hundred thousand (inclusive)
1 ───► one million (inclusive)
See also
the Wikipedia entry: square-free integer
| #Haskell | Haskell | import Data.List.Split (chunksOf)
import Math.NumberTheory.Primes (factorise)
import Text.Printf (printf)
-- True iff the argument is a square-free number.
isSquareFree :: Integer -> Bool
isSquareFree = all ((== 1) . snd) . factorise
-- All square-free numbers in the range [lo, hi].
squareFrees :: Integer -> Integer -> [Integer]
squareFrees lo hi = filter isSquareFree [lo..hi]
-- The result of `counts limits values' is the number of values less than or
-- equal to each successive limit. Both limits and values are assumed to be
-- in increasing order.
counts :: (Ord a, Num b) => [a] -> [a] -> [b]
counts = go 0
where go c lims@(l:ls) (v:vs) | v > l = c : go (c+1) ls vs
| otherwise = go (c+1) lims vs
go _ [] _ = []
go c ls [] = replicate (length ls) c
printSquareFrees :: Int -> Integer -> Integer -> IO ()
printSquareFrees cols lo hi =
let ns = squareFrees lo hi
title = printf "Square free numbers from %d to %d\n" lo hi
body = unlines $ map concat $ chunksOf cols $ map (printf " %3d") ns
in putStrLn $ title ++ body
printSquareFreeCounts :: [Integer] -> Integer -> Integer -> IO ()
printSquareFreeCounts lims lo hi =
let cs = counts lims $ squareFrees lo hi :: [Integer]
title = printf "Counts of square-free numbers\n"
body = unlines $ zipWith (printf " from 1 to %d: %d") lims cs
in putStrLn $ title ++ body
main :: IO ()
main = do
printSquareFrees 20 1 145
printSquareFrees 5 1000000000000 1000000000145
printSquareFreeCounts [100, 1000, 10000, 100000, 1000000] 1 1000000 |
http://rosettacode.org/wiki/State_name_puzzle | State name puzzle | Background
This task is inspired by Mark Nelson's DDJ Column "Wordplay" and one of the weekly puzzle challenges from Will Shortz on NPR Weekend Edition [1] and originally attributed to David Edelheit.
The challenge was to take the names of two U.S. States, mix them all together, then rearrange the letters to form the names of two different U.S. States (so that all four state names differ from one another).
What states are these?
The problem was reissued on the Unicon Discussion Web which includes several solutions with analysis. Several techniques may be helpful and you may wish to refer to Gödel numbering, equivalence relations, and equivalence classes. The basic merits of these were discussed in the Unicon Discussion Web.
A second challenge in the form of a set of fictitious new states was also presented.
Task
Write a program to solve the challenge using both the original list of states and the fictitious list.
Caveats
case and spacing aren't significant - just letters (harmonize case)
don't expect the names to be in any order - such as being sorted
don't rely on names to be unique (eliminate duplicates - meaning if Iowa appears twice you can only use it once)
Comma separated list of state names used in the original puzzle:
"Alabama", "Alaska", "Arizona", "Arkansas",
"California", "Colorado", "Connecticut", "Delaware",
"Florida", "Georgia", "Hawaii", "Idaho", "Illinois",
"Indiana", "Iowa", "Kansas", "Kentucky", "Louisiana",
"Maine", "Maryland", "Massachusetts", "Michigan",
"Minnesota", "Mississippi", "Missouri", "Montana",
"Nebraska", "Nevada", "New Hampshire", "New Jersey",
"New Mexico", "New York", "North Carolina", "North Dakota",
"Ohio", "Oklahoma", "Oregon", "Pennsylvania", "Rhode Island",
"South Carolina", "South Dakota", "Tennessee", "Texas",
"Utah", "Vermont", "Virginia",
"Washington", "West Virginia", "Wisconsin", "Wyoming"
Comma separated list of additional fictitious state names to be added to the original (Includes a duplicate):
"New Kory", "Wen Kory", "York New", "Kory New", "New Kory"
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
| #Scala | Scala | object StateNamePuzzle extends App {
// Logic:
def disjointPairs(pairs: Seq[Set[String]]) =
for (a <- pairs; b <- pairs; if a.intersect(b).isEmpty) yield Set(a,b)
def anagramPairs(words: Seq[String]) =
(for (a <- words; b <- words; if a != b) yield Set(a, b)) // all pairs
.groupBy(_.mkString.toLowerCase.replaceAll("[^a-z]", "").sorted) // grouped anagram pairs
.values.map(disjointPairs).flatMap(_.distinct) // unique non-overlapping anagram pairs
// Test:
val states = List(
"New Kory", "Wen Kory", "York New", "Kory New", "New Kory",
"Alabama", "Alaska", "Arizona", "Arkansas", "California", "Colorado",
"Connecticut", "Delaware", "Florida", "Georgia", "Hawaii", "Idaho",
"Illinois", "Indiana", "Iowa", "Kansas", "Kentucky", "Louisiana", "Maine",
"Maryland", "Massachusetts", "Michigan", "Minnesota", "Mississippi",
"Missouri", "Montana", "Nebraska", "Nevada", "New Hampshire", "New Jersey",
"New Mexico", "New York", "North Carolina", "North Dakota", "Ohio",
"Oklahoma", "Oregon", "Pennsylvania", "Rhode Island", "South Carolina",
"South Dakota", "Tennessee", "Texas", "Utah", "Vermont", "Virginia",
"Washington", "West Virginia", "Wisconsin", "Wyoming"
)
println(anagramPairs(states).map(_.map(_ mkString " + ") mkString " = ") mkString "\n")
} |
http://rosettacode.org/wiki/String_append | String append |
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
Concatenation |
Interpolation |
Comparison |
Matching
Memory Operations
Pointers & references |
Addresses
Most languages provide a way to concatenate two string values, but some languages also provide a convenient way to append in-place to an existing string variable without referring to the variable twice.
Task
Create a string variable equal to any text value.
Append the string variable with another string literal in the most idiomatic way, without double reference if your language supports it.
Show the contents of the variable after the append operation.
| #Swift | Swift | var s = "foo" // "foo"
s += "bar" // "foobar"
print(s) // "foobar"
s.appendContentsOf("baz") // "foobarbaz"
print(s) // "foobarbaz" |
http://rosettacode.org/wiki/String_append | String append |
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
Concatenation |
Interpolation |
Comparison |
Matching
Memory Operations
Pointers & references |
Addresses
Most languages provide a way to concatenate two string values, but some languages also provide a convenient way to append in-place to an existing string variable without referring to the variable twice.
Task
Create a string variable equal to any text value.
Append the string variable with another string literal in the most idiomatic way, without double reference if your language supports it.
Show the contents of the variable after the append operation.
| #Tcl | Tcl | set s "he"
set s "${s}llo wo"; # The braces distinguish varname from text to concatenate
append s "rld"
puts $s |
http://rosettacode.org/wiki/Statistics/Normal_distribution | Statistics/Normal distribution | The Normal (or Gaussian) distribution is a frequently used distribution in statistics. While most programming languages provide a uniformly distributed random number generator, one can derive normally distributed random numbers from a uniform generator.
The task
Take a uniform random number generator and create a large (you decide how large) set of numbers that follow a normal (Gaussian) distribution. Calculate the dataset's mean and standard deviation, and show a histogram of the data.
Mention any native language support for the generation of normally distributed random numbers.
Reference
You may refer to code in Statistics/Basic if available.
| #SAS | SAS | data test;
n=100000;
twopi=2*constant('pi');
do i=1 to n;
u=ranuni(0);
v=ranuni(0);
r=sqrt(-2*log(u));
x=r*cos(twopi*v);
y=r*sin(twopi*v);
z=rannor(0);
output;
end;
keep x y z;
proc means mean stddev;
proc univariate;
histogram /normal;
run;
/*
Variable Mean Std Dev
----------------------------------------
x -0.0052720 0.9988467
y 0.000023995 1.0019996
z 0.0012857 1.0056536
*/ |
http://rosettacode.org/wiki/Stem-and-leaf_plot | Stem-and-leaf plot | Create a well-formatted stem-and-leaf plot from the following data set, where the leaves are the last digits:
12 127 28 42 39 113 42 18 44 118 44 37 113 124 37 48 127 36 29 31 125 139 131 115 105 132 104 123 35 113 122 42 117 119 58 109 23 105 63 27 44 105 99 41 128 121 116 125 32 61 37 127 29 113 121 58 114 126 53 114 96 25 109 7 31 141 46 13 27 43 117 116 27 7 68 40 31 115 124 42 128 52 71 118 117 38 27 106 33 117 116 111 40 119 47 105 57 122 109 124 115 43 120 43 27 27 18 28 48 125 107 114 34 133 45 120 30 127 31 116 146
The primary intent of this task is the presentation of information. It is acceptable to hardcode the data set or characteristics of it (such as what the stems are) in the example, insofar as it is impractical to make the example generic to any data set. For example, in a computation-less language like HTML the data set may be entirely prearranged within the example; the interesting characteristics are how the proper visual formatting is arranged.
If possible, the output should not be a bitmap image. Monospaced plain text is acceptable, but do better if you can. It may be a window, i.e. not a file.
Note: If you wish to try multiple data sets, you might try this generator.
| #Kotlin | Kotlin | // version 1.1.2
fun leafPlot(x: IntArray) {
x.sort()
var i = x[0] / 10 - 1
for (j in 0 until x.size) {
val d = x[j] / 10
while (d > i) print("%s%3d |".format(if (j != 0) "\n" else "", ++i))
print(" ${x[j] % 10}")
}
println()
}
fun main(args: Array<String>) {
val data = intArrayOf(
12, 127, 28, 42, 39, 113, 42, 18, 44, 118, 44, 37, 113, 124,
37, 48, 127, 36, 29, 31, 125, 139, 131, 115, 105, 132, 104, 123,
35, 113, 122, 42, 117, 119, 58, 109, 23, 105, 63, 27, 44, 105,
99, 41, 128, 121, 116, 125, 32, 61, 37, 127, 29, 113, 121, 58,
114, 126, 53, 114, 96, 25, 109, 7, 31, 141, 46, 13, 27, 43,
117, 116, 27, 7, 68, 40, 31, 115, 124, 42, 128, 52, 71, 118,
117, 38, 27, 106, 33, 117, 116, 111, 40, 119, 47, 105, 57, 122,
109, 124, 115, 43, 120, 43, 27, 27, 18, 28, 48, 125, 107, 114,
34, 133, 45, 120, 30, 127, 31, 116, 146
)
leafPlot(data)
} |
http://rosettacode.org/wiki/Stern-Brocot_sequence | Stern-Brocot sequence | For this task, the Stern-Brocot sequence is to be generated by an algorithm similar to that employed in generating the Fibonacci sequence.
The first and second members of the sequence are both 1:
1, 1
Start by considering the second member of the sequence
Sum the considered member of the sequence and its precedent, (1 + 1) = 2, and append it to the end of the sequence:
1, 1, 2
Append the considered member of the sequence to the end of the sequence:
1, 1, 2, 1
Consider the next member of the series, (the third member i.e. 2)
GOTO 3
─── Expanding another loop we get: ───
Sum the considered member of the sequence and its precedent, (2 + 1) = 3, and append it to the end of the sequence:
1, 1, 2, 1, 3
Append the considered member of the sequence to the end of the sequence:
1, 1, 2, 1, 3, 2
Consider the next member of the series, (the fourth member i.e. 1)
The task is to
Create a function/method/subroutine/procedure/... to generate the Stern-Brocot sequence of integers using the method outlined above.
Show the first fifteen members of the sequence. (This should be: 1, 1, 2, 1, 3, 2, 3, 1, 4, 3, 5, 2, 5, 3, 4)
Show the (1-based) index of where the numbers 1-to-10 first appears in the sequence.
Show the (1-based) index of where the number 100 first appears in the sequence.
Check that the greatest common divisor of all the two consecutive members of the series up to the 1000th member, is always one.
Show your output on this page.
Related tasks
Fusc sequence.
Continued fraction/Arithmetic
Ref
Infinite Fractions - Numberphile (Video).
Trees, Teeth, and Time: The mathematics of clock making.
A002487 The On-Line Encyclopedia of Integer Sequences.
| #J | J | sternbrocot=:1 :0
ind=. 0
seq=. 1 1
while. -. u seq do.
ind=. ind+1
seq=. seq, +/\. seq {~ _1 0 +ind
end.
) |
http://rosettacode.org/wiki/Stack_traces | Stack traces | Many programming languages allow for introspection of the current call stack environment. This can be for a variety of purposes such as enforcing security checks, debugging, or for getting access to the stack frame of callers.
Task
Print out (in a manner considered suitable for the platform) the current call stack.
The amount of information printed for each frame on the call stack is not constrained, but should include at least the name of the function or method at that level of the stack frame.
You may explicitly add a call to produce the stack trace to the (example) code being instrumented for examination.
The task should allow the program to continue after generating the stack trace.
The task report here must include the trace from a sample program.
| #Quackery | Quackery | > quackery
Welcome to Quackery.
Enter "leave" to leave the shell.
Building extensions.
/O> echoreturn
...
{[...] 0} {quackery 1} {[...] 11} {shell 5} {quackery 1} {[...] 0}
Stack empty.
/O> [ cr echoreturn
... cr echostack
... dup 2 < if done
... dup 1 - swap 2 -
... recurse swap recurse + ] is fib
...
Stack empty.
/O> 5 fib echo
...
{[...] 0} {quackery 1} {[...] 11} {shell 5} {quackery 1} {[...] 1} {fib 1}
Stack: 5
{[...] 0} {quackery 1} {[...] 11} {shell 5} {quackery 1} {[...] 1} {fib 15} {recurse 1} {fib 1}
Stack: 4 3
{[...] 0} {quackery 1} {[...] 11} {shell 5} {quackery 1} {[...] 1} {fib 15} {recurse 1} {fib 15} {recurse 1} {fib 1}
Stack: 4 2 1
{[...] 0} {quackery 1} {[...] 11} {shell 5} {quackery 1} {[...] 1} {fib 15} {recurse 1} {fib 17} {recurse 1} {fib 1}
Stack: 4 1 2
{[...] 0} {quackery 1} {[...] 11} {shell 5} {quackery 1} {[...] 1} {fib 15} {recurse 1} {fib 17} {recurse 1} {fib 15} {recurse 1} {fib 1}
Stack: 4 1 1 0
{[...] 0} {quackery 1} {[...] 11} {shell 5} {quackery 1} {[...] 1} {fib 15} {recurse 1} {fib 17} {recurse 1} {fib 17} {recurse 1} {fib 1}
Stack: 4 1 0 1
{[...] 0} {quackery 1} {[...] 11} {shell 5} {quackery 1} {[...] 1} {fib 17} {recurse 1} {fib 1}
Stack: 2 4
{[...] 0} {quackery 1} {[...] 11} {shell 5} {quackery 1} {[...] 1} {fib 17} {recurse 1} {fib 15} {recurse 1} {fib 1}
Stack: 2 3 2
{[...] 0} {quackery 1} {[...] 11} {shell 5} {quackery 1} {[...] 1} {fib 17} {recurse 1} {fib 15} {recurse 1} {fib 15} {recurse 1} {fib 1}
Stack: 2 3 1 0
{[...] 0} {quackery 1} {[...] 11} {shell 5} {quackery 1} {[...] 1} {fib 17} {recurse 1} {fib 15} {recurse 1} {fib 17} {recurse 1} {fib 1}
Stack: 2 3 0 1
{[...] 0} {quackery 1} {[...] 11} {shell 5} {quackery 1} {[...] 1} {fib 17} {recurse 1} {fib 17} {recurse 1} {fib 1}
Stack: 2 1 3
{[...] 0} {quackery 1} {[...] 11} {shell 5} {quackery 1} {[...] 1} {fib 17} {recurse 1} {fib 17} {recurse 1} {fib 15} {recurse 1} {fib 1}
Stack: 2 1 2 1
{[...] 0} {quackery 1} {[...] 11} {shell 5} {quackery 1} {[...] 1} {fib 17} {recurse 1} {fib 17} {recurse 1} {fib 17} {recurse 1} {fib 1}
Stack: 2 1 1 2
{[...] 0} {quackery 1} {[...] 11} {shell 5} {quackery 1} {[...] 1} {fib 17} {recurse 1} {fib 17} {recurse 1} {fib 17} {recurse 1} {fib 15} {recurse 1} {fib 1}
Stack: 2 1 1 1 0
{[...] 0} {quackery 1} {[...] 11} {shell 5} {quackery 1} {[...] 1} {fib 17} {recurse 1} {fib 17} {recurse 1} {fib 17} {recurse 1} {fib 17} {recurse 1} {fib 1}
Stack: 2 1 1 0 1
5
Stack empty.
/O> |
http://rosettacode.org/wiki/Stack_traces | Stack traces | Many programming languages allow for introspection of the current call stack environment. This can be for a variety of purposes such as enforcing security checks, debugging, or for getting access to the stack frame of callers.
Task
Print out (in a manner considered suitable for the platform) the current call stack.
The amount of information printed for each frame on the call stack is not constrained, but should include at least the name of the function or method at that level of the stack frame.
You may explicitly add a call to produce the stack trace to the (example) code being instrumented for examination.
The task should allow the program to continue after generating the stack trace.
The task report here must include the trace from a sample program.
| #R | R | foo <- function()
{
bar <- function()
{
sys.calls()
}
bar()
}
foo() |
http://rosettacode.org/wiki/Stair-climbing_puzzle | Stair-climbing puzzle | From Chung-Chieh Shan (LtU):
Your stair-climbing robot has a very simple low-level API: the "step" function takes no argument and attempts to climb one step as a side effect. Unfortunately, sometimes the attempt fails and the robot clumsily falls one step instead. The "step" function detects what happens and returns a boolean flag: true on success, false on failure.
Write a function "step_up" that climbs one step up [from the initial position] (by repeating "step" attempts if necessary). Assume that the robot is not already at the top of the stairs, and neither does it ever reach the bottom of the stairs. How small can you make "step_up"? Can you avoid using variables (even immutable ones) and numbers?
Here's a pseudo-code of a simple recursive solution without using variables:
func step_up()
{
if not step() {
step_up();
step_up();
}
}
Inductive proof that step_up() steps up one step, if it terminates:
Base case (if the step() call returns true): it stepped up one step. QED
Inductive case (if the step() call returns false): Assume that recursive calls to step_up() step up one step. It stepped down one step (because step() returned false), but now we step up two steps using two step_up() calls. QED
The second (tail) recursion above can be turned into an iteration, as follows:
func step_up()
{
while not step() {
step_up();
}
}
| #PARI.2FGP | PARI/GP | step_up()=while(!step(),step_up()) |
http://rosettacode.org/wiki/Stair-climbing_puzzle | Stair-climbing puzzle | From Chung-Chieh Shan (LtU):
Your stair-climbing robot has a very simple low-level API: the "step" function takes no argument and attempts to climb one step as a side effect. Unfortunately, sometimes the attempt fails and the robot clumsily falls one step instead. The "step" function detects what happens and returns a boolean flag: true on success, false on failure.
Write a function "step_up" that climbs one step up [from the initial position] (by repeating "step" attempts if necessary). Assume that the robot is not already at the top of the stairs, and neither does it ever reach the bottom of the stairs. How small can you make "step_up"? Can you avoid using variables (even immutable ones) and numbers?
Here's a pseudo-code of a simple recursive solution without using variables:
func step_up()
{
if not step() {
step_up();
step_up();
}
}
Inductive proof that step_up() steps up one step, if it terminates:
Base case (if the step() call returns true): it stepped up one step. QED
Inductive case (if the step() call returns false): Assume that recursive calls to step_up() step up one step. It stepped down one step (because step() returned false), but now we step up two steps using two step_up() calls. QED
The second (tail) recursion above can be turned into an iteration, as follows:
func step_up()
{
while not step() {
step_up();
}
}
| #Pascal | Pascal | procedure stepUp;
begin
while not step do
stepUp;
end; |
http://rosettacode.org/wiki/Stack | Stack |
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.
A stack is a container of elements with last in, first out access policy. Sometimes it also called LIFO.
The stack is accessed through its top.
The basic stack operations are:
push stores a new element onto the stack top;
pop returns the last pushed stack element, while removing it from the stack;
empty tests if the stack contains no elements.
Sometimes the last pushed stack element is made accessible for immutable access (for read) or mutable access (for write):
top (sometimes called peek to keep with the p theme) returns the topmost element without modifying the stack.
Stacks allow a very simple hardware implementation.
They are common in almost all processors.
In programming, stacks are also very popular for their way (LIFO) of resource management, usually memory.
Nested scopes of language objects are naturally implemented by a stack (sometimes by multiple stacks).
This is a classical way to implement local variables of a re-entrant or recursive subprogram. Stacks are also used to describe a formal computational framework.
See stack machine.
Many algorithms in pattern matching, compiler construction (e.g. recursive descent parsers), and machine learning (e.g. based on tree traversal) have a natural representation in terms of stacks.
Task
Create a stack supporting the basic operations: push, pop, 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
| #68000_Assembly | 68000 Assembly | LEA userStack,A0 ;initialize the user stack, points to a memory address in user RAM. Only do this once!
MOVEM.L D0-D3,-(A0) ;moves the full 32 bits of registers D0,D1,D2,D3 into the address pointed by A0, with pre-decrement |
http://rosettacode.org/wiki/Square_but_not_cube | Square but not cube | Task
Show the first 30 positive integers which are squares but not cubes of such integers.
Optionally, show also the first 3 positive integers which are both squares and cubes, and mark them as such.
| #ALGOL-M | ALGOL-M | begin
integer function square(x);
integer x;
square := x * x;
integer function cube(x);
integer x;
cube := x * x * x;
integer c, s, seen;
seen := 0;
while seen < 30 do
begin
while cube(c) < square(s) do
c := c + 1;
if square(s) <> cube(c) then
begin
if (seen/5 <> (seen-1)/5) then write("");
writeon(square(s));
seen := seen + 1;
end;
s := s + 1;
end;
end |
http://rosettacode.org/wiki/Square_but_not_cube | Square but not cube | Task
Show the first 30 positive integers which are squares but not cubes of such integers.
Optionally, show also the first 3 positive integers which are both squares and cubes, and mark them as such.
| #APL | APL | (×⍨∘⍳ ~ (⊢×⊢×⊢)∘⍳) 33 |
http://rosettacode.org/wiki/Statistics/Basic | Statistics/Basic | Statistics is all about large groups of numbers.
When talking about a set of sampled data, most frequently used is their mean value and standard deviation (stddev).
If you have set of data
x
i
{\displaystyle x_{i}}
where
i
=
1
,
2
,
…
,
n
{\displaystyle i=1,2,\ldots ,n\,\!}
, the mean is
x
¯
≡
1
n
∑
i
x
i
{\displaystyle {\bar {x}}\equiv {1 \over n}\sum _{i}x_{i}}
, while the stddev is
σ
≡
1
n
∑
i
(
x
i
−
x
¯
)
2
{\displaystyle \sigma \equiv {\sqrt {{1 \over n}\sum _{i}\left(x_{i}-{\bar {x}}\right)^{2}}}}
.
When examining a large quantity of data, one often uses a histogram, which shows the counts of data samples falling into a prechosen set of intervals (or bins).
When plotted, often as bar graphs, it visually indicates how often each data value occurs.
Task Using your language's random number routine, generate real numbers in the range of [0, 1]. It doesn't matter if you chose to use open or closed range.
Create 100 of such numbers (i.e. sample size 100) and calculate their mean and stddev.
Do so for sample size of 1,000 and 10,000, maybe even higher if you feel like.
Show a histogram of any of these sets.
Do you notice some patterns about the standard deviation?
Extra Sometimes so much data need to be processed that it's impossible to keep all of them at once. Can you calculate the mean, stddev and histogram of a trillion numbers? (You don't really need to do a trillion numbers, just show how it can be done.)
Hint
For a finite population with equal probabilities at all points, one can derive:
(
x
−
x
¯
)
2
¯
=
x
2
¯
−
x
¯
2
{\displaystyle {\overline {(x-{\overline {x}})^{2}}}={\overline {x^{2}}}-{\overline {x}}^{2}}
Or, more verbosely:
1
N
∑
i
=
1
N
(
x
i
−
x
¯
)
2
=
1
N
(
∑
i
=
1
N
x
i
2
)
−
x
¯
2
.
{\displaystyle {\frac {1}{N}}\sum _{i=1}^{N}(x_{i}-{\overline {x}})^{2}={\frac {1}{N}}\left(\sum _{i=1}^{N}x_{i}^{2}\right)-{\overline {x}}^{2}.}
See also
Statistics/Normal distribution
Tasks for calculating statistical measures
in one go
moving (sliding window)
moving (cumulative)
Mean
Arithmetic
Statistics/Basic
Averages/Arithmetic mean
Averages/Pythagorean means
Averages/Simple moving average
Geometric
Averages/Pythagorean means
Harmonic
Averages/Pythagorean means
Quadratic
Averages/Root mean square
Circular
Averages/Mean angle
Averages/Mean time of day
Median
Averages/Median
Mode
Averages/Mode
Standard deviation
Statistics/Basic
Cumulative standard deviation
| #D | D | import std.stdio, std.algorithm, std.array, std.typecons,
std.range, std.exception;
auto meanStdDev(R)(R numbers) /*nothrow*/ @safe /*@nogc*/ {
if (numbers.empty)
return tuple(0.0L, 0.0L);
real sx = 0.0, sxx = 0.0;
ulong n;
foreach (x; numbers) {
sx += x;
sxx += x ^^ 2;
n++;
}
return tuple(sx / n, (n * sxx - sx ^^ 2) ^^ 0.5L / n);
}
void showHistogram01(R)(R numbers) /*@safe*/ {
enum maxWidth = 50; // N. characters.
ulong[10] bins;
foreach (immutable x; numbers) {
immutable index = cast(size_t)(x * bins.length);
enforce(index >= 0 && index < bins.length);
bins[index]++;
}
immutable real maxFreq = bins.reduce!max;
foreach (immutable n, immutable i; bins)
writefln(" %3.1f: %s", n / real(bins.length),
replicate("*", cast(int)(i / maxFreq * maxWidth)));
writeln;
}
version (statistics_basic_main) {
void main() @safe {
import std.random;
foreach (immutable p; 1 .. 7) {
auto n = iota(10L ^^ p).map!(_ => uniform(0.0L, 1.0L));
writeln(10L ^^ p, " numbers:");
writefln(" Mean: %8.6f, SD: %8.6f", n.meanStdDev.tupleof);
n.showHistogram01;
}
}
} |
http://rosettacode.org/wiki/Square-free_integers | Square-free integers | Task
Write a function to test if a number is square-free.
A square-free is an integer which is divisible by no perfect square other
than 1 (unity).
For this task, only positive square-free numbers will be used.
Show here (on this page) all square-free integers (in a horizontal format) that are between:
1 ───► 145 (inclusive)
1 trillion ───► 1 trillion + 145 (inclusive)
(One trillion = 1,000,000,000,000)
Show here (on this page) the count of square-free integers from:
1 ───► one hundred (inclusive)
1 ───► one thousand (inclusive)
1 ───► ten thousand (inclusive)
1 ───► one hundred thousand (inclusive)
1 ───► one million (inclusive)
See also
the Wikipedia entry: square-free integer
| #J | J | isSqrFree=: (#@~. = #)@q: NB. are there no duplicates in the prime factors of a number?
filter=: adverb def ' #~ u' NB. filter right arg using verb to left
countSqrFree=: +/@:isSqrFree
thru=: <. + i.@(+ *)@-~ NB. helper verb |
http://rosettacode.org/wiki/Square-free_integers | Square-free integers | Task
Write a function to test if a number is square-free.
A square-free is an integer which is divisible by no perfect square other
than 1 (unity).
For this task, only positive square-free numbers will be used.
Show here (on this page) all square-free integers (in a horizontal format) that are between:
1 ───► 145 (inclusive)
1 trillion ───► 1 trillion + 145 (inclusive)
(One trillion = 1,000,000,000,000)
Show here (on this page) the count of square-free integers from:
1 ───► one hundred (inclusive)
1 ───► one thousand (inclusive)
1 ───► ten thousand (inclusive)
1 ───► one hundred thousand (inclusive)
1 ───► one million (inclusive)
See also
the Wikipedia entry: square-free integer
| #Java | Java | import java.util.ArrayList;
import java.util.List;
public class SquareFree
{
private static List<Long> sieve(long limit) {
List<Long> primes = new ArrayList<Long>();
primes.add(2L);
boolean[] c = new boolean[(int)limit + 1]; // composite = true
// no need to process even numbers > 2
long p = 3;
for (;;) {
long p2 = p * p;
if (p2 > limit) break;
for (long i = p2; i <= limit; i += 2 * p) c[(int)i] = true;
for (;;) {
p += 2;
if (!c[(int)p]) break;
}
}
for (long i = 3; i <= limit; i += 2) {
if (!c[(int)i]) primes.add(i);
}
return primes;
}
private static List<Long> squareFree(long from, long to) {
long limit = (long)Math.sqrt((double)to);
List<Long> primes = sieve(limit);
List<Long> results = new ArrayList<Long>();
outer: for (long i = from; i <= to; i++) {
for (long p : primes) {
long p2 = p * p;
if (p2 > i) break;
if (i % p2 == 0) continue outer;
}
results.add(i);
}
return results;
}
private final static long TRILLION = 1000000000000L;
public static void main(String[] args) {
System.out.println("Square-free integers from 1 to 145:");
List<Long> sf = squareFree(1, 145);
for (int i = 0; i < sf.size(); i++) {
if (i > 0 && i % 20 == 0) {
System.out.println();
}
System.out.printf("%4d", sf.get(i));
}
System.out.print("\n\nSquare-free integers");
System.out.printf(" from %d to %d:\n", TRILLION, TRILLION + 145);
sf = squareFree(TRILLION, TRILLION + 145);
for (int i = 0; i < sf.size(); i++) {
if (i > 0 && i % 5 == 0) System.out.println();
System.out.printf("%14d", sf.get(i));
}
System.out.println("\n\nNumber of square-free integers:\n");
long[] tos = {100, 1000, 10000, 100000, 1000000};
for (long to : tos) {
System.out.printf(" from %d to %d = %d\n", 1, to, squareFree(1, to).size());
}
}
} |
http://rosettacode.org/wiki/State_name_puzzle | State name puzzle | Background
This task is inspired by Mark Nelson's DDJ Column "Wordplay" and one of the weekly puzzle challenges from Will Shortz on NPR Weekend Edition [1] and originally attributed to David Edelheit.
The challenge was to take the names of two U.S. States, mix them all together, then rearrange the letters to form the names of two different U.S. States (so that all four state names differ from one another).
What states are these?
The problem was reissued on the Unicon Discussion Web which includes several solutions with analysis. Several techniques may be helpful and you may wish to refer to Gödel numbering, equivalence relations, and equivalence classes. The basic merits of these were discussed in the Unicon Discussion Web.
A second challenge in the form of a set of fictitious new states was also presented.
Task
Write a program to solve the challenge using both the original list of states and the fictitious list.
Caveats
case and spacing aren't significant - just letters (harmonize case)
don't expect the names to be in any order - such as being sorted
don't rely on names to be unique (eliminate duplicates - meaning if Iowa appears twice you can only use it once)
Comma separated list of state names used in the original puzzle:
"Alabama", "Alaska", "Arizona", "Arkansas",
"California", "Colorado", "Connecticut", "Delaware",
"Florida", "Georgia", "Hawaii", "Idaho", "Illinois",
"Indiana", "Iowa", "Kansas", "Kentucky", "Louisiana",
"Maine", "Maryland", "Massachusetts", "Michigan",
"Minnesota", "Mississippi", "Missouri", "Montana",
"Nebraska", "Nevada", "New Hampshire", "New Jersey",
"New Mexico", "New York", "North Carolina", "North Dakota",
"Ohio", "Oklahoma", "Oregon", "Pennsylvania", "Rhode Island",
"South Carolina", "South Dakota", "Tennessee", "Texas",
"Utah", "Vermont", "Virginia",
"Washington", "West Virginia", "Wisconsin", "Wyoming"
Comma separated list of additional fictitious state names to be added to the original (Includes a duplicate):
"New Kory", "Wen Kory", "York New", "Kory New", "New Kory"
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
| #Tcl | Tcl | package require Tcl 8.5
# Gödel number generator
proc goedel s {
set primes {
2 3 5 7 11 13 17 19 23 29 31 37 41
43 47 53 59 61 67 71 73 79 83 89 97 101
}
set n 1
foreach c [split [string toupper $s] ""] {
if {![string is alpha $c]} continue
set n [expr {$n * [lindex $primes [expr {[scan $c %c] - 65}]]}]
}
return $n
}
# Calculates the pairs of states
proc groupStates {stateList} {
set stateList [lsort -unique $stateList]
foreach state1 $stateList {
foreach state2 $stateList {
if {$state1 >= $state2} continue
dict lappend group [goedel $state1$state2] [list $state1 $state2]
}
}
foreach g [dict values $group] {
if {[llength $g] > 1} {
foreach p1 $g {
foreach p2 $g {
if {$p1 < $p2 && [unshared $p1 $p2]} {
lappend result [list $p1 $p2]
}
}
}
}
}
return $result
}
proc unshared args {
foreach p $args {
foreach a $p {incr s($a)}
}
expr {[array size s] == [llength $args]*2}
}
# Pretty printer for state name pair lists
proc printPairs {title groups} {
foreach group $groups {
puts "$title Group #[incr count]"
foreach statePair $group {
puts "\t[join $statePair {, }]"
}
}
}
set realStates {
"Alabama" "Alaska" "Arizona" "Arkansas" "California" "Colorado"
"Connecticut" "Delaware" "Florida" "Georgia" "Hawaii" "Idaho" "Illinois"
"Indiana" "Iowa" "Kansas" "Kentucky" "Louisiana" "Maine" "Maryland"
"Massachusetts" "Michigan" "Minnesota" "Mississippi" "Missouri" "Montana"
"Nebraska" "Nevada" "New Hampshire" "New Jersey" "New Mexico" "New York"
"North Carolina" "North Dakota" "Ohio" "Oklahoma" "Oregon" "Pennsylvania"
"Rhode Island" "South Carolina" "South Dakota" "Tennessee" "Texas" "Utah"
"Vermont" "Virginia" "Washington" "West Virginia" "Wisconsin" "Wyoming"
}
printPairs "Real States" [groupStates $realStates]
set falseStates {
"New Kory" "Wen Kory" "York New" "Kory New" "New Kory"
}
printPairs "Real and False States" [groupStates [concat $realStates $falseStates]] |
http://rosettacode.org/wiki/String_append | String append |
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
Concatenation |
Interpolation |
Comparison |
Matching
Memory Operations
Pointers & references |
Addresses
Most languages provide a way to concatenate two string values, but some languages also provide a convenient way to append in-place to an existing string variable without referring to the variable twice.
Task
Create a string variable equal to any text value.
Append the string variable with another string literal in the most idiomatic way, without double reference if your language supports it.
Show the contents of the variable after the append operation.
| #Transd | Transd | #lang transd
MainModule: {
_start: (λ
(with s1 "aaa" s2 "bbb" s3 "ccc"
(+= s1 s2 s3)
(textout s1))
)
} |
http://rosettacode.org/wiki/String_append | String append |
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
Concatenation |
Interpolation |
Comparison |
Matching
Memory Operations
Pointers & references |
Addresses
Most languages provide a way to concatenate two string values, but some languages also provide a convenient way to append in-place to an existing string variable without referring to the variable twice.
Task
Create a string variable equal to any text value.
Append the string variable with another string literal in the most idiomatic way, without double reference if your language supports it.
Show the contents of the variable after the append operation.
| #Ursa | Ursa | decl string str
set str "hello "
# append "world" to str
set str (+ str "world")
# outputs "hello world"
out str endl console |
http://rosettacode.org/wiki/Statistics/Normal_distribution | Statistics/Normal distribution | The Normal (or Gaussian) distribution is a frequently used distribution in statistics. While most programming languages provide a uniformly distributed random number generator, one can derive normally distributed random numbers from a uniform generator.
The task
Take a uniform random number generator and create a large (you decide how large) set of numbers that follow a normal (Gaussian) distribution. Calculate the dataset's mean and standard deviation, and show a histogram of the data.
Mention any native language support for the generation of normally distributed random numbers.
Reference
You may refer to code in Statistics/Basic if available.
| #Sidef | Sidef | define τ = Num.tau
func normdist (m, σ) {
var r = sqrt(-2 * 1.rand.log)
var Θ = (τ * 1.rand)
r * Θ.cos * σ + m
}
var size = 100_000
var mean = 50
var stddev = 4
var dataset = size.of { normdist(mean, stddev) }
var m = (dataset.sum / size)
say ("m: #{m}")
var σ = sqrt(dataset »**» 2 -> sum / size - m**2)
say ("s: #{σ}")
var hash = Hash()
dataset.each { |n| hash{ n.round } := 0 ++ }
var scale = (180 * stddev / size)
const subbar = < ⎸ ▏ ▎ ▍ ▌ ▋ ▊ ▉ █ >
for i in (hash.keys.map{.to_i}.sort) {
var x = (hash{i} * scale)
var full = x.int
var part = (8 * (x - full))
say (i, "\t", '█' * full, subbar[part])
} |
http://rosettacode.org/wiki/Stem-and-leaf_plot | Stem-and-leaf plot | Create a well-formatted stem-and-leaf plot from the following data set, where the leaves are the last digits:
12 127 28 42 39 113 42 18 44 118 44 37 113 124 37 48 127 36 29 31 125 139 131 115 105 132 104 123 35 113 122 42 117 119 58 109 23 105 63 27 44 105 99 41 128 121 116 125 32 61 37 127 29 113 121 58 114 126 53 114 96 25 109 7 31 141 46 13 27 43 117 116 27 7 68 40 31 115 124 42 128 52 71 118 117 38 27 106 33 117 116 111 40 119 47 105 57 122 109 124 115 43 120 43 27 27 18 28 48 125 107 114 34 133 45 120 30 127 31 116 146
The primary intent of this task is the presentation of information. It is acceptable to hardcode the data set or characteristics of it (such as what the stems are) in the example, insofar as it is impractical to make the example generic to any data set. For example, in a computation-less language like HTML the data set may be entirely prearranged within the example; the interesting characteristics are how the proper visual formatting is arranged.
If possible, the output should not be a bitmap image. Monospaced plain text is acceptable, but do better if you can. It may be a window, i.e. not a file.
Note: If you wish to try multiple data sets, you might try this generator.
| #Lua | Lua | data = { 12,127,28,42,39,113, 42,18,44,118,44,37,113,124,37,48,127,36,29,31,
125,139,131,115,105,132,104,123,35,113,122,42,117,119,58,109,23,105,
63,27,44,105,99,41,128,121,116,125,32,61,37,127,29,113,121,58,114,126,
53,114,96,25,109,7,31,141,46,13,27,43,117,116,27,7,68,40,31,115,124,42,
128,52,71,118,117,38,27,106,33,117,116,111,40,119,47,105,57,122,109,
124,115,43,120,43,27,27,18,28,48,125,107,114,34,133,45,120, 30,127,
31,116,146
}
table.sort( data )
min, max = data[1], data[#data]
p = 1
for stem = math.floor(min/10), math.floor(max/10) do
io.write( string.format( "%2d | ", stem ) )
while data[p] ~= nil and math.floor( data[p]/10 ) == stem do
io.write( string.format( "%2d ", data[p] % 10 ) )
p = p + 1
end
print ""
end |
http://rosettacode.org/wiki/Stern-Brocot_sequence | Stern-Brocot sequence | For this task, the Stern-Brocot sequence is to be generated by an algorithm similar to that employed in generating the Fibonacci sequence.
The first and second members of the sequence are both 1:
1, 1
Start by considering the second member of the sequence
Sum the considered member of the sequence and its precedent, (1 + 1) = 2, and append it to the end of the sequence:
1, 1, 2
Append the considered member of the sequence to the end of the sequence:
1, 1, 2, 1
Consider the next member of the series, (the third member i.e. 2)
GOTO 3
─── Expanding another loop we get: ───
Sum the considered member of the sequence and its precedent, (2 + 1) = 3, and append it to the end of the sequence:
1, 1, 2, 1, 3
Append the considered member of the sequence to the end of the sequence:
1, 1, 2, 1, 3, 2
Consider the next member of the series, (the fourth member i.e. 1)
The task is to
Create a function/method/subroutine/procedure/... to generate the Stern-Brocot sequence of integers using the method outlined above.
Show the first fifteen members of the sequence. (This should be: 1, 1, 2, 1, 3, 2, 3, 1, 4, 3, 5, 2, 5, 3, 4)
Show the (1-based) index of where the numbers 1-to-10 first appears in the sequence.
Show the (1-based) index of where the number 100 first appears in the sequence.
Check that the greatest common divisor of all the two consecutive members of the series up to the 1000th member, is always one.
Show your output on this page.
Related tasks
Fusc sequence.
Continued fraction/Arithmetic
Ref
Infinite Fractions - Numberphile (Video).
Trees, Teeth, and Time: The mathematics of clock making.
A002487 The On-Line Encyclopedia of Integer Sequences.
| #Java | Java | import java.math.BigInteger;
import java.util.LinkedList;
public class SternBrocot {
static LinkedList<Integer> sequence = new LinkedList<Integer>(){{
add(1); add(1);
}};
private static void genSeq(int n){
for(int conIdx = 1; sequence.size() < n; conIdx++){
int consider = sequence.get(conIdx);
int pre = sequence.get(conIdx - 1);
sequence.add(consider + pre);
sequence.add(consider);
}
}
public static void main(String[] args){
genSeq(1200);
System.out.println("The first 15 elements are: " + sequence.subList(0, 15));
for(int i = 1; i <= 10; i++){
System.out.println("First occurrence of " + i + " is at " + (sequence.indexOf(i) + 1));
}
System.out.println("First occurrence of 100 is at " + (sequence.indexOf(100) + 1));
boolean failure = false;
for(int i = 0; i < 999; i++){
failure |= !BigInteger.valueOf(sequence.get(i)).gcd(BigInteger.valueOf(sequence.get(i + 1))).equals(BigInteger.ONE);
}
System.out.println("All GCDs are" + (failure ? " not" : "") + " 1");
}
} |
http://rosettacode.org/wiki/Stack_traces | Stack traces | Many programming languages allow for introspection of the current call stack environment. This can be for a variety of purposes such as enforcing security checks, debugging, or for getting access to the stack frame of callers.
Task
Print out (in a manner considered suitable for the platform) the current call stack.
The amount of information printed for each frame on the call stack is not constrained, but should include at least the name of the function or method at that level of the stack frame.
You may explicitly add a call to produce the stack trace to the (example) code being instrumented for examination.
The task should allow the program to continue after generating the stack trace.
The task report here must include the trace from a sample program.
| #Racket | Racket |
#lang racket
;; To see these calls we do two things: mutate the binding to prevent
;; Racket from inlining the value; use a (void) call at the end so the
;; calls are not tail calls (which will otherwise not show on the
;; stack).
(define foo #f)
(set! foo (λ() (bar) (void)))
(define bar #f)
(set! bar (λ() (show-stacktrace) (void)))
(define (show-stacktrace)
(for ([s (continuation-mark-set->context (current-continuation-marks))]
[i (in-naturals)])
;; show just the names, not the full source information
(when (car s) (printf "~s: ~s\n" i (car s)))))
(foo)
|
http://rosettacode.org/wiki/Stack_traces | Stack traces | Many programming languages allow for introspection of the current call stack environment. This can be for a variety of purposes such as enforcing security checks, debugging, or for getting access to the stack frame of callers.
Task
Print out (in a manner considered suitable for the platform) the current call stack.
The amount of information printed for each frame on the call stack is not constrained, but should include at least the name of the function or method at that level of the stack frame.
You may explicitly add a call to produce the stack trace to the (example) code being instrumented for examination.
The task should allow the program to continue after generating the stack trace.
The task report here must include the trace from a sample program.
| #Raku | Raku | sub g { say Backtrace.new.concise }
sub f { g }
sub MAIN { f } |
http://rosettacode.org/wiki/Stack_traces | Stack traces | Many programming languages allow for introspection of the current call stack environment. This can be for a variety of purposes such as enforcing security checks, debugging, or for getting access to the stack frame of callers.
Task
Print out (in a manner considered suitable for the platform) the current call stack.
The amount of information printed for each frame on the call stack is not constrained, but should include at least the name of the function or method at that level of the stack frame.
You may explicitly add a call to produce the stack trace to the (example) code being instrumented for examination.
The task should allow the program to continue after generating the stack trace.
The task report here must include the trace from a sample program.
| #Raven | Raven | [1 2 3 4] 42 { 'a' 1 'b' 2 'c' 3 } 34.1234 ( -1 -2 -3 ) "The quick brown fox" FILE dump |
http://rosettacode.org/wiki/Stair-climbing_puzzle | Stair-climbing puzzle | From Chung-Chieh Shan (LtU):
Your stair-climbing robot has a very simple low-level API: the "step" function takes no argument and attempts to climb one step as a side effect. Unfortunately, sometimes the attempt fails and the robot clumsily falls one step instead. The "step" function detects what happens and returns a boolean flag: true on success, false on failure.
Write a function "step_up" that climbs one step up [from the initial position] (by repeating "step" attempts if necessary). Assume that the robot is not already at the top of the stairs, and neither does it ever reach the bottom of the stairs. How small can you make "step_up"? Can you avoid using variables (even immutable ones) and numbers?
Here's a pseudo-code of a simple recursive solution without using variables:
func step_up()
{
if not step() {
step_up();
step_up();
}
}
Inductive proof that step_up() steps up one step, if it terminates:
Base case (if the step() call returns true): it stepped up one step. QED
Inductive case (if the step() call returns false): Assume that recursive calls to step_up() step up one step. It stepped down one step (because step() returned false), but now we step up two steps using two step_up() calls. QED
The second (tail) recursion above can be turned into an iteration, as follows:
func step_up()
{
while not step() {
step_up();
}
}
| #Perl | Perl | sub step_up { step_up until step; } |
http://rosettacode.org/wiki/Stair-climbing_puzzle | Stair-climbing puzzle | From Chung-Chieh Shan (LtU):
Your stair-climbing robot has a very simple low-level API: the "step" function takes no argument and attempts to climb one step as a side effect. Unfortunately, sometimes the attempt fails and the robot clumsily falls one step instead. The "step" function detects what happens and returns a boolean flag: true on success, false on failure.
Write a function "step_up" that climbs one step up [from the initial position] (by repeating "step" attempts if necessary). Assume that the robot is not already at the top of the stairs, and neither does it ever reach the bottom of the stairs. How small can you make "step_up"? Can you avoid using variables (even immutable ones) and numbers?
Here's a pseudo-code of a simple recursive solution without using variables:
func step_up()
{
if not step() {
step_up();
step_up();
}
}
Inductive proof that step_up() steps up one step, if it terminates:
Base case (if the step() call returns true): it stepped up one step. QED
Inductive case (if the step() call returns false): Assume that recursive calls to step_up() step up one step. It stepped down one step (because step() returned false), but now we step up two steps using two step_up() calls. QED
The second (tail) recursion above can be turned into an iteration, as follows:
func step_up()
{
while not step() {
step_up();
}
}
| #Phix | Phix | procedure step_up()
while not step() do step_up() end while
end procedure
|
http://rosettacode.org/wiki/Stair-climbing_puzzle | Stair-climbing puzzle | From Chung-Chieh Shan (LtU):
Your stair-climbing robot has a very simple low-level API: the "step" function takes no argument and attempts to climb one step as a side effect. Unfortunately, sometimes the attempt fails and the robot clumsily falls one step instead. The "step" function detects what happens and returns a boolean flag: true on success, false on failure.
Write a function "step_up" that climbs one step up [from the initial position] (by repeating "step" attempts if necessary). Assume that the robot is not already at the top of the stairs, and neither does it ever reach the bottom of the stairs. How small can you make "step_up"? Can you avoid using variables (even immutable ones) and numbers?
Here's a pseudo-code of a simple recursive solution without using variables:
func step_up()
{
if not step() {
step_up();
step_up();
}
}
Inductive proof that step_up() steps up one step, if it terminates:
Base case (if the step() call returns true): it stepped up one step. QED
Inductive case (if the step() call returns false): Assume that recursive calls to step_up() step up one step. It stepped down one step (because step() returned false), but now we step up two steps using two step_up() calls. QED
The second (tail) recursion above can be turned into an iteration, as follows:
func step_up()
{
while not step() {
step_up();
}
}
| #PicoLisp | PicoLisp | (de stepUp ()
(until (step1) # ('step1', because 'step' is a system function)
(stepUp) ) ) |
http://rosettacode.org/wiki/Stack | Stack |
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.
A stack is a container of elements with last in, first out access policy. Sometimes it also called LIFO.
The stack is accessed through its top.
The basic stack operations are:
push stores a new element onto the stack top;
pop returns the last pushed stack element, while removing it from the stack;
empty tests if the stack contains no elements.
Sometimes the last pushed stack element is made accessible for immutable access (for read) or mutable access (for write):
top (sometimes called peek to keep with the p theme) returns the topmost element without modifying the stack.
Stacks allow a very simple hardware implementation.
They are common in almost all processors.
In programming, stacks are also very popular for their way (LIFO) of resource management, usually memory.
Nested scopes of language objects are naturally implemented by a stack (sometimes by multiple stacks).
This is a classical way to implement local variables of a re-entrant or recursive subprogram. Stacks are also used to describe a formal computational framework.
See stack machine.
Many algorithms in pattern matching, compiler construction (e.g. recursive descent parsers), and machine learning (e.g. based on tree traversal) have a natural representation in terms of stacks.
Task
Create a stack supporting the basic operations: push, pop, 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
| #8086_Assembly | 8086 Assembly | push ax ;push ax onto the stack
pop ax ; pop the top two bytes of the stack into ax |
http://rosettacode.org/wiki/SQL-based_authentication | SQL-based authentication | This task has three parts:
Connect to a MySQL database (connect_db)
Create user/password records in the following table (create_user)
Authenticate login requests against the table (authenticate_user)
This is the table definition:
CREATE TABLE users (
userid INT PRIMARY KEY AUTO_INCREMENT,
username VARCHAR(32) UNIQUE KEY NOT NULL,
pass_salt tinyblob NOT NULL,
-- a string of 16 random bytes
pass_md5 tinyblob NOT NULL
-- binary MD5 hash of pass_salt concatenated with the password
);
(pass_salt and pass_md5 would be binary(16) values, but MySQL versions before 5.0.15 strip trailing spaces when selecting them.)
| #C | C | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
#include <time.h>
#include <mysql.h>
#include <openssl/md5.h>
void end_with_db(void);
MYSQL *mysql = NULL; // global...
bool connect_db(const char *host, const char *user, const char *pwd,
const char *db, unsigned int port)
{
if ( mysql == NULL )
{
if (mysql_library_init(0, NULL, NULL)) return false;
mysql = mysql_init(NULL); if ( mysql == NULL ) return false;
MYSQL *myp = mysql_real_connect(mysql, host, user, pwd, db, port, NULL, 0);
if (myp == NULL) {
fprintf(stderr, "connection error: %s\n", mysql_error(mysql));
end_with_db();
return false;
}
}
return true; // already connected... ?
}
#define USERNAMELIMIT 32
// no part of the spec, but it is reasonable!!
#define PASSWORDLIMIT 32
#define SALTBYTE 16
bool create_user(const char *username, const char *password)
{
int i;
char binarysalt[SALTBYTE];
char salt[SALTBYTE*2+1];
char md5hash[MD5_DIGEST_LENGTH];
char saltpass[SALTBYTE+PASSWORDLIMIT+1];
char pass_md5[MD5_DIGEST_LENGTH*2 + 1];
char user[USERNAMELIMIT*2 + 1];
char *q = NULL;
static const char query[] =
"INSERT INTO users "
"(username,pass_salt,pass_md5) "
"VALUES ('%s', X'%s', X'%s')";
static const size_t qlen = sizeof query;
for(i=0; username[i] != '\0' && i < USERNAMELIMIT; i++) ;
if ( username[i] != '\0' ) return false;
for(i=0; password[i] != '\0' && i < PASSWORDLIMIT; i++) ;
if ( password[i] != '\0' ) return false;
srand(time(NULL));
for(i=0; i < SALTBYTE; i++)
{
// this skews the distribution but it is lazyness-compliant;)
binarysalt[i] = rand()%256;
}
(void)mysql_hex_string(salt, binarysalt, SALTBYTE);
for(i=0; i < SALTBYTE; i++) saltpass[i] = binarysalt[i];
strcpy(saltpass+SALTBYTE, password);
(void)MD5(saltpass, SALTBYTE + strlen(password), md5hash);
(void)mysql_hex_string(pass_md5, md5hash, MD5_DIGEST_LENGTH);
(void)mysql_real_escape_string(mysql, user, username, strlen(username));
// salt, pass_md5, user are db-query-ready
q = malloc(qlen + USERNAMELIMIT*2 + MD5_DIGEST_LENGTH*2 + SALTBYTE*2 + 1);
if ( q == NULL ) return false;
sprintf(q, query, user, salt, pass_md5);
#if defined(DEBUG)
fprintf(stderr, "QUERY:\n%s\n\n", q);
#endif
int res = mysql_query(mysql, q);
free(q);
if ( res != 0 )
{
fprintf(stderr, "create_user query error: %s\n", mysql_error(mysql));
return false;
}
return true;
}
bool authenticate_user(const char *username, const char *password)
{
char user[USERNAMELIMIT*2 + 1];
char md5hash[MD5_DIGEST_LENGTH];
char saltpass[SALTBYTE+PASSWORDLIMIT+1];
bool authok = false;
char *q = NULL;
int i;
static const char query[] =
"SELECT * FROM users WHERE username='%s'";
static const size_t qlen = sizeof query;
// can't be authenticated with invalid username or password
for(i=0; username[i] != '\0' && i < USERNAMELIMIT; i++) ;
if ( username[i] != '\0' ) return false;
for(i=0; password[i] != '\0' && i < PASSWORDLIMIT; i++) ;
if ( password[i] != '\0' ) return false;
(void)mysql_real_escape_string(mysql, user, username, strlen(username));
q = malloc(qlen + strlen(user) + 1);
if (q == NULL) return false;
sprintf(q, query, username);
int res = mysql_query(mysql, q);
free(q);
if ( res != 0 )
{
fprintf(stderr, "authenticate_user query error: %s\n", mysql_error(mysql));
return false;
}
MYSQL_RES *qr = mysql_store_result(mysql);
if ( qr == NULL ) return false;
// should be only a result, or none
if ( mysql_num_rows(qr) != 1 ) {
mysql_free_result(qr);
return false;
}
MYSQL_ROW row = mysql_fetch_row(qr); // 1 row must exist
unsigned long *len = mysql_fetch_lengths(qr); // and should have 4 cols...
memcpy(saltpass, row[2], len[2]); // len[2] should be SALTBYTE
memcpy(saltpass + len[2], password, strlen(password));
(void)MD5(saltpass, SALTBYTE + strlen(password), md5hash);
authok = memcmp(md5hash, row[3], len[3]) == 0;
mysql_free_result(qr);
return authok;
}
void end_with_db(void)
{
mysql_close(mysql); mysql = NULL;
mysql_library_end();
}
int main(int argc, char **argv)
{
if ( argc < 4 ) return EXIT_FAILURE;
if ( connect_db("localhost", "devel", "", "test", 0 ) )
{
if ( strcmp(argv[1], "add") == 0 )
{
if (create_user(argv[2], argv[3]))
printf("created\n");
} else if ( strcmp(argv[1], "auth") == 0 ) {
if (authenticate_user(argv[2], argv[3]))
printf("authorized\n");
else
printf("access denied\n");
} else {
printf("unknown command\n");
}
end_with_db();
}
return EXIT_SUCCESS;
} |
http://rosettacode.org/wiki/Square_but_not_cube | Square but not cube | Task
Show the first 30 positive integers which are squares but not cubes of such integers.
Optionally, show also the first 3 positive integers which are both squares and cubes, and mark them as such.
| #AppleScript | AppleScript | on run
script listing
on |λ|(x)
set sqr to x * x
set strSquare to sqr as text
if isCube(sqr) then
strSquare & " (also cube)"
else
strSquare
end if
end |λ|
end script
unlines(map(listing, ¬
enumFromTo(1, 33)))
end run
-- isCube :: Int -> Bool
on isCube(x)
x = (round (x ^ (1 / 3))) ^ 3
end isCube
-- GENERIC FUNCTIONS -------------------------------------------------
-- enumFromTo :: Int -> Int -> [Int]
on enumFromTo(m, n)
if m ≤ n then
set lst to {}
repeat with i from m to n
set end of lst to i
end repeat
return lst
else
return {}
end if
end enumFromTo
-- map :: (a -> b) -> [a] -> [b]
on map(f, xs)
tell mReturn(f)
set lng to length of xs
set lst to {}
repeat with i from 1 to lng
set end of lst to |λ|(item i of xs, i, xs)
end repeat
return lst
end tell
end map
-- Lift 2nd class handler function into 1st class script wrapper
-- mReturn :: First-class m => (a -> b) -> m (a -> b)
on mReturn(f)
if class of f is script then
f
else
script
property |λ| : f
end script
end if
end mReturn
-- unlines :: [String] -> String
on unlines(xs)
set {dlm, my text item delimiters} to ¬
{my text item delimiters, linefeed}
set str to xs as text
set my text item delimiters to dlm
str
end unlines |
http://rosettacode.org/wiki/Statistics/Basic | Statistics/Basic | Statistics is all about large groups of numbers.
When talking about a set of sampled data, most frequently used is their mean value and standard deviation (stddev).
If you have set of data
x
i
{\displaystyle x_{i}}
where
i
=
1
,
2
,
…
,
n
{\displaystyle i=1,2,\ldots ,n\,\!}
, the mean is
x
¯
≡
1
n
∑
i
x
i
{\displaystyle {\bar {x}}\equiv {1 \over n}\sum _{i}x_{i}}
, while the stddev is
σ
≡
1
n
∑
i
(
x
i
−
x
¯
)
2
{\displaystyle \sigma \equiv {\sqrt {{1 \over n}\sum _{i}\left(x_{i}-{\bar {x}}\right)^{2}}}}
.
When examining a large quantity of data, one often uses a histogram, which shows the counts of data samples falling into a prechosen set of intervals (or bins).
When plotted, often as bar graphs, it visually indicates how often each data value occurs.
Task Using your language's random number routine, generate real numbers in the range of [0, 1]. It doesn't matter if you chose to use open or closed range.
Create 100 of such numbers (i.e. sample size 100) and calculate their mean and stddev.
Do so for sample size of 1,000 and 10,000, maybe even higher if you feel like.
Show a histogram of any of these sets.
Do you notice some patterns about the standard deviation?
Extra Sometimes so much data need to be processed that it's impossible to keep all of them at once. Can you calculate the mean, stddev and histogram of a trillion numbers? (You don't really need to do a trillion numbers, just show how it can be done.)
Hint
For a finite population with equal probabilities at all points, one can derive:
(
x
−
x
¯
)
2
¯
=
x
2
¯
−
x
¯
2
{\displaystyle {\overline {(x-{\overline {x}})^{2}}}={\overline {x^{2}}}-{\overline {x}}^{2}}
Or, more verbosely:
1
N
∑
i
=
1
N
(
x
i
−
x
¯
)
2
=
1
N
(
∑
i
=
1
N
x
i
2
)
−
x
¯
2
.
{\displaystyle {\frac {1}{N}}\sum _{i=1}^{N}(x_{i}-{\overline {x}})^{2}={\frac {1}{N}}\left(\sum _{i=1}^{N}x_{i}^{2}\right)-{\overline {x}}^{2}.}
See also
Statistics/Normal distribution
Tasks for calculating statistical measures
in one go
moving (sliding window)
moving (cumulative)
Mean
Arithmetic
Statistics/Basic
Averages/Arithmetic mean
Averages/Pythagorean means
Averages/Simple moving average
Geometric
Averages/Pythagorean means
Harmonic
Averages/Pythagorean means
Quadratic
Averages/Root mean square
Circular
Averages/Mean angle
Averages/Mean time of day
Median
Averages/Median
Mode
Averages/Mode
Standard deviation
Statistics/Basic
Cumulative standard deviation
| #Dart | Dart | /* Import math library to get:
* 1) Square root function : Math.sqrt(x)
* 2) Power function : Math.pow(base, exponent)
* 3) Random number generator : Math.Random()
*/
import 'dart:math' as Math show sqrt, pow, Random;
// Returns average/mean of a list of numbers
num mean(List<num> l) => l.reduce((num value,num element)=>value+element)/l.length;
// Returns standard deviation of a list of numbers
num stdev(List<num> l) => Math.sqrt((1/l.length)*l.map((num x)=>x*x).reduce((num value,num element) => value+element) - Math.pow(mean(l),2));
/* CODE TO PRINT THE HISTOGRAM STARTS HERE
*
* Histogram has ten fields, one for every tenth between 0 and 1
* To do this, we save the histogram as a global variable
* that will hold the number of occurences of each tenth in the sample
*/
List<num> histogram = new List.filled(10,0);
/*
* METHOD TO CREATE A RANDOM SAMPLE OF n NUMBERS (Returns a list)
*
* While creating each value, this method also increments the
* appropriate index of the histogram
*/
List<num> randomsample(num n){
List<num> l = new List<num>(n);
histogram = new List.filled(10,0);
num random = new Math.Random();
for (int i = 0; i < n; i++){
l[i] = random.nextDouble();
histogram[conv(l[i])] += 1;
}
return l;
}
/*
* METHOD TO RETURN A STRING OF n ASTERIXES (yay ASCII art)
*/
String stars(num n){
String s = '';
for (int i = 0; i < n; i++){
s = s + '*';
}
return s;
}
/*
* METHOD TO DRAW THE HISTOGRAM
* 1) Get to total for all the values in the histogram
* 2) For every field in the histogram:
* a) Compute the frequency for every field in the histogram
* b) Print the frequency as asterixes
*/
void drawhistogram(){
int total = histogram.reduce((num element,num value)=>element+value);
double freq;
for (int i = 0; i < 10; i++){
freq = histogram[i]/total;
print('${i/10} - ${(i+1)/10} : ' + stars(conv(30*freq)));
}
}
/* HELPER METHOD:
* converts values between 0-1 to integers between 0-9 inclusive
* useful to figure out which random value generated
* corresponds to which field in the histogram
*/
int conv(num i) => (10*i).floor();
/* MAIN FUNCTION
*
* Create 5 histograms and print the mean and standard deviation for each:
* 1) Sample Size = 100
* 2) Sample Size = 1000
* 3) Sample Size = 10000
* 4) Sample Size = 100000
* 5) Sample Size = 1000000
*
*/
void main(){
List<num> l;
num m;
num s;
List<int> sampleSizes = [100,1000,10000,100000,1000000];
for (int samplesize in sampleSizes){
print('--------------- Sample size $samplesize ----------------');
l = randomsample(samplesize);
m = mean(l);
s = stdev(l);
drawhistogram();
print('');
print('mean: ${m.toStringAsPrecision(8)} standard deviation: ${s.toStringAsPrecision(8)}');
print('');
}
} |
http://rosettacode.org/wiki/Square-free_integers | Square-free integers | Task
Write a function to test if a number is square-free.
A square-free is an integer which is divisible by no perfect square other
than 1 (unity).
For this task, only positive square-free numbers will be used.
Show here (on this page) all square-free integers (in a horizontal format) that are between:
1 ───► 145 (inclusive)
1 trillion ───► 1 trillion + 145 (inclusive)
(One trillion = 1,000,000,000,000)
Show here (on this page) the count of square-free integers from:
1 ───► one hundred (inclusive)
1 ───► one thousand (inclusive)
1 ───► ten thousand (inclusive)
1 ───► one hundred thousand (inclusive)
1 ───► one million (inclusive)
See also
the Wikipedia entry: square-free integer
| #jq | jq | def is_square_free: . as $n | all( squares; divides($n) | not);
|
http://rosettacode.org/wiki/State_name_puzzle | State name puzzle | Background
This task is inspired by Mark Nelson's DDJ Column "Wordplay" and one of the weekly puzzle challenges from Will Shortz on NPR Weekend Edition [1] and originally attributed to David Edelheit.
The challenge was to take the names of two U.S. States, mix them all together, then rearrange the letters to form the names of two different U.S. States (so that all four state names differ from one another).
What states are these?
The problem was reissued on the Unicon Discussion Web which includes several solutions with analysis. Several techniques may be helpful and you may wish to refer to Gödel numbering, equivalence relations, and equivalence classes. The basic merits of these were discussed in the Unicon Discussion Web.
A second challenge in the form of a set of fictitious new states was also presented.
Task
Write a program to solve the challenge using both the original list of states and the fictitious list.
Caveats
case and spacing aren't significant - just letters (harmonize case)
don't expect the names to be in any order - such as being sorted
don't rely on names to be unique (eliminate duplicates - meaning if Iowa appears twice you can only use it once)
Comma separated list of state names used in the original puzzle:
"Alabama", "Alaska", "Arizona", "Arkansas",
"California", "Colorado", "Connecticut", "Delaware",
"Florida", "Georgia", "Hawaii", "Idaho", "Illinois",
"Indiana", "Iowa", "Kansas", "Kentucky", "Louisiana",
"Maine", "Maryland", "Massachusetts", "Michigan",
"Minnesota", "Mississippi", "Missouri", "Montana",
"Nebraska", "Nevada", "New Hampshire", "New Jersey",
"New Mexico", "New York", "North Carolina", "North Dakota",
"Ohio", "Oklahoma", "Oregon", "Pennsylvania", "Rhode Island",
"South Carolina", "South Dakota", "Tennessee", "Texas",
"Utah", "Vermont", "Virginia",
"Washington", "West Virginia", "Wisconsin", "Wyoming"
Comma separated list of additional fictitious state names to be added to the original (Includes a duplicate):
"New Kory", "Wen Kory", "York New", "Kory New", "New Kory"
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
| #Wren | Wren | import "/str" for Str
import "/sort" for Sort
import "/fmt" for Fmt
var solve = Fn.new { |states|
var dict = {}
for (state in states) {
var key = Str.lower(state).replace(" ", "")
if (!dict[key]) dict[key] = state
}
var keys = dict.keys.toList
Sort.quick(keys)
var solutions = []
var duplicates = []
for (i in 0...keys.count) {
for (j in i+1...keys.count) {
var len = keys[i].count + keys[j].count
var chars = (keys[i] + keys[j]).toList
Sort.quick(chars)
var combined = chars.join()
for (k in 0...keys.count) {
for (l in k+1...keys.count) {
if (k != i && k != j && l != i && l != j) {
var len2 = keys[k].count + keys[l].count
if (len2 == len) {
var chars2 = (keys[k] + keys[l]).toList
Sort.quick(chars2)
var combined2 = chars2.join()
if (combined == combined2) {
var f1 = "%(dict[keys[i]]) + %(dict[keys[j]])"
var f2 = "%(dict[keys[k]]) + %(dict[keys[l]])"
var f3 = "%(f1) = %(f2)"
if (!duplicates.contains(f3)) {
solutions.add(f3)
var f4 = "%(f2) = %(f1)"
duplicates.add(f4)
}
}
}
}
}
}
}
}
Sort.quick(solutions)
var i = 0
for (sol in solutions) {
Fmt.print("$2d $s", i + 1, sol)
i = i + 1
}
}
var states = [
"Alabama", "Alaska", "Arizona", "Arkansas",
"California", "Colorado", "Connecticut",
"Delaware",
"Florida", "Georgia", "Hawaii",
"Idaho", "Illinois", "Indiana", "Iowa",
"Kansas", "Kentucky", "Louisiana",
"Maine", "Maryland", "Massachusetts", "Michigan",
"Minnesota", "Mississippi", "Missouri", "Montana",
"Nebraska", "Nevada", "New Hampshire", "New Jersey",
"New Mexico", "New York", "North Carolina", "North Dakota",
"Ohio", "Oklahoma", "Oregon",
"Pennsylvania", "Rhode Island",
"South Carolina", "South Dakota", "Tennessee", "Texas",
"Utah", "Vermont", "Virginia",
"Washington", "West Virginia", "Wisconsin", "Wyoming"
]
System.print("Real states only:")
solve.call(states)
System.print()
var fictitious = [ "New Kory", "Wen Kory", "York New", "Kory New", "New Kory" ]
System.print("Real and fictitious states:")
solve.call(states + fictitious) |
http://rosettacode.org/wiki/String_append | String append |
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
Concatenation |
Interpolation |
Comparison |
Matching
Memory Operations
Pointers & references |
Addresses
Most languages provide a way to concatenate two string values, but some languages also provide a convenient way to append in-place to an existing string variable without referring to the variable twice.
Task
Create a string variable equal to any text value.
Append the string variable with another string literal in the most idiomatic way, without double reference if your language supports it.
Show the contents of the variable after the append operation.
| #Vala | Vala | void main() {
string x = "foo";
x += "bar\n";
print(x);
} |
http://rosettacode.org/wiki/String_append | String append |
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
Concatenation |
Interpolation |
Comparison |
Matching
Memory Operations
Pointers & references |
Addresses
Most languages provide a way to concatenate two string values, but some languages also provide a convenient way to append in-place to an existing string variable without referring to the variable twice.
Task
Create a string variable equal to any text value.
Append the string variable with another string literal in the most idiomatic way, without double reference if your language supports it.
Show the contents of the variable after the append operation.
| #VBA | VBA | Function StringAppend()
Dim s As String
s = "foo"
s = s & "bar"
Debug.Print s
End Function |
http://rosettacode.org/wiki/String_append | String append |
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
Concatenation |
Interpolation |
Comparison |
Matching
Memory Operations
Pointers & references |
Addresses
Most languages provide a way to concatenate two string values, but some languages also provide a convenient way to append in-place to an existing string variable without referring to the variable twice.
Task
Create a string variable equal to any text value.
Append the string variable with another string literal in the most idiomatic way, without double reference if your language supports it.
Show the contents of the variable after the append operation.
| #VBScript | VBScript | s = "Rosetta"
s = s & " Code"
WScript.StdOut.Write s |
http://rosettacode.org/wiki/Statistics/Normal_distribution | Statistics/Normal distribution | The Normal (or Gaussian) distribution is a frequently used distribution in statistics. While most programming languages provide a uniformly distributed random number generator, one can derive normally distributed random numbers from a uniform generator.
The task
Take a uniform random number generator and create a large (you decide how large) set of numbers that follow a normal (Gaussian) distribution. Calculate the dataset's mean and standard deviation, and show a histogram of the data.
Mention any native language support for the generation of normally distributed random numbers.
Reference
You may refer to code in Statistics/Basic if available.
| #Stata | Stata | clear all
set obs 100000
gen u=runiform()
gen v=runiform()
gen r=sqrt(-2*log(u))
gen x=r*cos(2*_pi*v)
gen y=r*sin(2*_pi*v)
gen z=rnormal()
sum x y z
Variable | Obs Mean Std. Dev. Min Max
-------------+---------------------------------------------------------
x | 100,000 .0025861 1.002346 -4.508192 4.164336
y | 100,000 .0017389 1.001586 -4.631144 4.460274
z | 100,000 .005054 .9998861 -5.134265 4.449522
hist x, normal
hist y, normal
hist z, normal
qqplot x z, msize(tiny) |
http://rosettacode.org/wiki/Statistics/Normal_distribution | Statistics/Normal distribution | The Normal (or Gaussian) distribution is a frequently used distribution in statistics. While most programming languages provide a uniformly distributed random number generator, one can derive normally distributed random numbers from a uniform generator.
The task
Take a uniform random number generator and create a large (you decide how large) set of numbers that follow a normal (Gaussian) distribution. Calculate the dataset's mean and standard deviation, and show a histogram of the data.
Mention any native language support for the generation of normally distributed random numbers.
Reference
You may refer to code in Statistics/Basic if available.
| #Tcl | Tcl | package require Tcl 8.5
# Uses the Box-Muller transform to compute a pair of normal random numbers
proc tcl::mathfunc::nrand {mean stddev} {
variable savednormalrandom
if {[info exists savednormalrandom]} {
return [expr {$savednormalrandom*$stddev + $mean}][unset savednormalrandom]
}
set r [expr {sqrt(-2*log(rand()))}]
set theta [expr {2*3.1415927*rand()}]
set savednormalrandom [expr {$r*sin($theta)}]
expr {$r*cos($theta)*$stddev + $mean}
}
proc stats {size {slotfactor 10}} {
set sum 0.0
set sum2 0.0
for {set i 0} {$i < $size} {incr i} {
set r [expr { nrand(0.5, 0.2) }]
incr histo([expr {int(floor($r*$slotfactor))}])
set sum [expr {$sum + $r}]
set sum2 [expr {$sum2 + $r**2}]
}
set mean [expr {$sum / $size}]
set stddev [expr {sqrt($sum2/$size - $mean**2)}]
puts "$size numbers"
puts "Mean: $mean"
puts "StdDev: $stddev"
foreach i [lsort -integer [array names histo]] {
puts [string repeat "*" [expr {$histo($i)*350/int($size)}]]
}
}
stats 100
puts ""
stats 1000
puts ""
stats 10000
puts ""
stats 100000 20 |
http://rosettacode.org/wiki/Stem-and-leaf_plot | Stem-and-leaf plot | Create a well-formatted stem-and-leaf plot from the following data set, where the leaves are the last digits:
12 127 28 42 39 113 42 18 44 118 44 37 113 124 37 48 127 36 29 31 125 139 131 115 105 132 104 123 35 113 122 42 117 119 58 109 23 105 63 27 44 105 99 41 128 121 116 125 32 61 37 127 29 113 121 58 114 126 53 114 96 25 109 7 31 141 46 13 27 43 117 116 27 7 68 40 31 115 124 42 128 52 71 118 117 38 27 106 33 117 116 111 40 119 47 105 57 122 109 124 115 43 120 43 27 27 18 28 48 125 107 114 34 133 45 120 30 127 31 116 146
The primary intent of this task is the presentation of information. It is acceptable to hardcode the data set or characteristics of it (such as what the stems are) in the example, insofar as it is impractical to make the example generic to any data set. For example, in a computation-less language like HTML the data set may be entirely prearranged within the example; the interesting characteristics are how the proper visual formatting is arranged.
If possible, the output should not be a bitmap image. Monospaced plain text is acceptable, but do better if you can. It may be a window, i.e. not a file.
Note: If you wish to try multiple data sets, you might try this generator.
| #Maple | Maple | StemPlot := proc( datatable::{rtable,list,algebraic} )
local i, j, k, tf, LeafStemTable, LeafStemIndices;
k:=0;
LeafStemTable := ListTools:-Categorize( (x,y) -> iquo(x, 10) = iquo(y, 10), sort(datatable));
if LeafStemTable = NULL then
error "Empty List";
elif nops( [ LeafStemTable ] ) = 1 or not( type( LeafStemTable[2], list) ) then
LeafStemTable := [ LeafStemTable ];
end if;
LeafStemIndices := { seq( iquo( LeafStemTable[i][1], 10 ), i = 1..nops( [ LeafStemTable ] ) ) };
for i from min( LeafStemIndices ) to max( LeafStemIndices ) do
if i in LeafStemIndices then
k := k + 1;
if i = 0 then
if min( datatable ) >=0 then
printf( "%-4a%s%-s\n", i, " | ", StringTools:-Remove( "[],", convert( [seq( abs( irem( LeafStemTable[k][j], 10 ) ), j = 1..nops( LeafStemTable[k] ) )], string ) ) );
else
tf := ListTools:-Occurrences( true, (x->type(x,negative))~(LeafStemTable[k]));
printf( "%s%-4a%s%-s\n", "-", i, " | ", StringTools:-Remove( "[],", convert( [seq( abs( irem( LeafStemTable[k][j], 10 ) ), j = 1 .. tf )], string ) ) );
printf( "%-4a%s%-s\n", i, " | ", StringTools:-Remove( "[],", convert( [seq( abs( irem( LeafStemTable[k][j], 10 ) ), j = tf + 1 .. nops( LeafStemTable[k] ) )], string ) ) );
end if;
else
printf( "%-4a%s%-s\n", i, " | ", StringTools:-Remove( "[],", convert( [seq( abs( irem( LeafStemTable[k][j], 10 ) ), j = 1..nops( LeafStemTable[k] ) )], string ) ) );
end if;
else
printf( "%-4a%s\n", i, " | " );
end if;
end do;
return NULL;
end proc:
Y := [ 12, 127, 28, 42, 39, 113, 42, 18, 44, 118, 44, 37, 113, 124, 37, 48, 127, 36, 29, 31, 125, 139, 131, 115, 105, 132, 104, 123, 35, 113, 122, 42, 117, 119, 58, 109, 23, 105, 63, 27, 44, 105, 99, 41, 128, 121, 116, 125, 32, 61, 37, 127, 29, 113, 121, 58, 114, 126, 53, 114, 96, 25, 109, 7, 31, 141, 46, 13, 27, 43, 117, 116, 27, 7, 68, 40, 31, 115, 124, 42, 128, 52, 71, 118, 117, 38, 27, 106, 33, 117, 116, 111, 40, 119, 47, 105, 57, 122, 109, 124, 115, 43, 120, 43, 27, 27, 18, 28, 48, 125, 107, 114, 34, 133, 45, 120, 30, 127, 31, 116, 146];
StemPlot(Y); |
http://rosettacode.org/wiki/Stern-Brocot_sequence | Stern-Brocot sequence | For this task, the Stern-Brocot sequence is to be generated by an algorithm similar to that employed in generating the Fibonacci sequence.
The first and second members of the sequence are both 1:
1, 1
Start by considering the second member of the sequence
Sum the considered member of the sequence and its precedent, (1 + 1) = 2, and append it to the end of the sequence:
1, 1, 2
Append the considered member of the sequence to the end of the sequence:
1, 1, 2, 1
Consider the next member of the series, (the third member i.e. 2)
GOTO 3
─── Expanding another loop we get: ───
Sum the considered member of the sequence and its precedent, (2 + 1) = 3, and append it to the end of the sequence:
1, 1, 2, 1, 3
Append the considered member of the sequence to the end of the sequence:
1, 1, 2, 1, 3, 2
Consider the next member of the series, (the fourth member i.e. 1)
The task is to
Create a function/method/subroutine/procedure/... to generate the Stern-Brocot sequence of integers using the method outlined above.
Show the first fifteen members of the sequence. (This should be: 1, 1, 2, 1, 3, 2, 3, 1, 4, 3, 5, 2, 5, 3, 4)
Show the (1-based) index of where the numbers 1-to-10 first appears in the sequence.
Show the (1-based) index of where the number 100 first appears in the sequence.
Check that the greatest common divisor of all the two consecutive members of the series up to the 1000th member, is always one.
Show your output on this page.
Related tasks
Fusc sequence.
Continued fraction/Arithmetic
Ref
Infinite Fractions - Numberphile (Video).
Trees, Teeth, and Time: The mathematics of clock making.
A002487 The On-Line Encyclopedia of Integer Sequences.
| #JavaScript | JavaScript | (() => {
'use strict';
const main = () => {
// sternBrocot :: Generator [Int]
const sternBrocot = () => {
const go = xs => {
const x = snd(xs);
return tail(append(xs, [fst(xs) + x, x]));
};
return fmapGen(head, iterate(go, [1, 1]));
};
// TESTS ------------------------------------------
const
sbs = take(1200, sternBrocot()),
ixSB = zip(sbs, enumFrom(1));
return unlines(map(
JSON.stringify,
[
take(15, sbs),
take(10,
map(listFromTuple,
nubBy(
on(eq, fst),
sortBy(
comparing(fst),
takeWhile(x => 12 !== fst(x), ixSB)
)
)
)
),
listFromTuple(
take(1, dropWhile(x => 100 !== fst(x), ixSB))[0]
),
all(tpl => 1 === gcd(fst(tpl), snd(tpl)),
take(1000, zip(sbs, tail(sbs)))
)
]
));
};
// GENERIC ABSTRACTIONS -------------------------------
// Just :: a -> Maybe a
const Just = x => ({
type: 'Maybe',
Nothing: false,
Just: x
});
// Nothing :: Maybe a
const Nothing = () => ({
type: 'Maybe',
Nothing: true,
});
// Tuple (,) :: a -> b -> (a, b)
const Tuple = (a, b) => ({
type: 'Tuple',
'0': a,
'1': b,
length: 2
});
// | Absolute value.
// abs :: Num -> Num
const abs = Math.abs;
// Determines whether all elements of the structure
// satisfy the predicate.
// all :: (a -> Bool) -> [a] -> Bool
const all = (p, xs) => xs.every(p);
// append (++) :: [a] -> [a] -> [a]
// append (++) :: String -> String -> String
const append = (xs, ys) => xs.concat(ys);
// chr :: Int -> Char
const chr = String.fromCodePoint;
// comparing :: (a -> b) -> (a -> a -> Ordering)
const comparing = f =>
(x, y) => {
const
a = f(x),
b = f(y);
return a < b ? -1 : (a > b ? 1 : 0);
};
// dropWhile :: (a -> Bool) -> [a] -> [a]
// dropWhile :: (Char -> Bool) -> String -> String
const dropWhile = (p, xs) => {
const lng = xs.length;
return 0 < lng ? xs.slice(
until(
i => i === lng || !p(xs[i]),
i => 1 + i,
0
)
) : [];
};
// enumFrom :: a -> [a]
function* enumFrom(x) {
let v = x;
while (true) {
yield v;
v = succ(v);
}
}
// eq (==) :: Eq a => a -> a -> Bool
const eq = (a, b) => {
const t = typeof a;
return t !== typeof b ? (
false
) : 'object' !== t ? (
'function' !== t ? (
a === b
) : a.toString() === b.toString()
) : (() => {
const aks = Object.keys(a);
return aks.length !== Object.keys(b).length ? (
false
) : aks.every(k => eq(a[k], b[k]));
})();
};
// fmapGen <$> :: (a -> b) -> Gen [a] -> Gen [b]
function* fmapGen(f, gen) {
const g = gen;
let v = take(1, g)[0];
while (0 < v.length) {
yield(f(v))
v = take(1, g)[0]
}
}
// fst :: (a, b) -> a
const fst = tpl => tpl[0];
// gcd :: Int -> Int -> Int
const gcd = (x, y) => {
const
_gcd = (a, b) => (0 === b ? a : _gcd(b, a % b)),
abs = Math.abs;
return _gcd(abs(x), abs(y));
};
// head :: [a] -> a
const head = xs => xs.length ? xs[0] : undefined;
// isChar :: a -> Bool
const isChar = x =>
('string' === typeof x) && (1 === x.length);
// iterate :: (a -> a) -> a -> Gen [a]
function* iterate(f, x) {
let v = x;
while (true) {
yield(v);
v = f(v);
}
}
// Returns Infinity over objects without finite length
// this enables zip and zipWith to choose the shorter
// argument when one is non-finite, like cycle, repeat etc
// length :: [a] -> Int
const length = xs => xs.length || Infinity;
// listFromTuple :: (a, a ...) -> [a]
const listFromTuple = tpl =>
Array.from(tpl);
// map :: (a -> b) -> [a] -> [b]
const map = (f, xs) => xs.map(f);
// nubBy :: (a -> a -> Bool) -> [a] -> [a]
const nubBy = (p, xs) => {
const go = xs => 0 < xs.length ? (() => {
const x = xs[0];
return [x].concat(
go(xs.slice(1)
.filter(y => !p(x, y))
)
)
})() : [];
return go(xs);
};
// e.g. sortBy(on(compare,length), xs)
// on :: (b -> b -> c) -> (a -> b) -> a -> a -> c
const on = (f, g) => (a, b) => f(g(a), g(b));
// ord :: Char -> Int
const ord = c => c.codePointAt(0);
// snd :: (a, b) -> b
const snd = tpl => tpl[1];
// sortBy :: (a -> a -> Ordering) -> [a] -> [a]
const sortBy = (f, xs) =>
xs.slice()
.sort(f);
// succ :: Enum a => a -> a
const succ = x =>
isChar(x) ? (
chr(1 + ord(x))
) : isNaN(x) ? (
undefined
) : 1 + x;
// tail :: [a] -> [a]
const tail = xs => 0 < xs.length ? xs.slice(1) : [];
// take :: Int -> [a] -> [a]
// take :: Int -> String -> String
const take = (n, xs) =>
xs.constructor.constructor.name !== 'GeneratorFunction' ? (
xs.slice(0, n)
) : [].concat.apply([], Array.from({
length: n
}, () => {
const x = xs.next();
return x.done ? [] : [x.value];
}));
// takeWhile :: (a -> Bool) -> [a] -> [a]
// takeWhile :: (Char -> Bool) -> String -> String
const takeWhile = (p, xs) =>
xs.constructor.constructor.name !==
'GeneratorFunction' ? (() => {
const lng = xs.length;
return 0 < lng ? xs.slice(
0,
until(
i => lng === i || !p(xs[i]),
i => 1 + i,
0
)
) : [];
})() : takeWhileGen(p, xs);
// takeWhileGen :: (a -> Bool) -> Gen [a] -> [a]
const takeWhileGen = (p, xs) => {
const ys = [];
let
nxt = xs.next(),
v = nxt.value;
while (!nxt.done && p(v)) {
ys.push(v);
nxt = xs.next();
v = nxt.value
}
return ys;
};
// uncons :: [a] -> Maybe (a, [a])
const uncons = xs => {
const lng = length(xs);
return (0 < lng) ? (
lng < Infinity ? (
Just(Tuple(xs[0], xs.slice(1))) // Finite list
) : (() => {
const nxt = take(1, xs);
return 0 < nxt.length ? (
Just(Tuple(nxt[0], xs))
) : Nothing();
})() // Lazy generator
) : Nothing();
};
// unlines :: [String] -> String
const unlines = xs => xs.join('\n');
// until :: (a -> Bool) -> (a -> a) -> a -> a
const until = (p, f, x) => {
let v = x;
while (!p(v)) v = f(v);
return v;
};
// Use of `take` and `length` here allows for zipping with non-finite
// lists - i.e. generators like cycle, repeat, iterate.
// zip :: [a] -> [b] -> [(a, b)]
const zip = (xs, ys) => {
const lng = Math.min(length(xs), length(ys));
return Infinity !== lng ? (() => {
const bs = take(lng, ys);
return take(lng, xs).map((x, i) => Tuple(x, bs[i]));
})() : zipGen(xs, ys);
};
// zipGen :: Gen [a] -> Gen [b] -> Gen [(a, b)]
const zipGen = (ga, gb) => {
function* go(ma, mb) {
let
a = ma,
b = mb;
while (!a.Nothing && !b.Nothing) {
let
ta = a.Just,
tb = b.Just
yield(Tuple(fst(ta), fst(tb)));
a = uncons(snd(ta));
b = uncons(snd(tb));
}
}
return go(uncons(ga), uncons(gb));
};
// MAIN ---
return main();
})(); |
http://rosettacode.org/wiki/Stack_traces | Stack traces | Many programming languages allow for introspection of the current call stack environment. This can be for a variety of purposes such as enforcing security checks, debugging, or for getting access to the stack frame of callers.
Task
Print out (in a manner considered suitable for the platform) the current call stack.
The amount of information printed for each frame on the call stack is not constrained, but should include at least the name of the function or method at that level of the stack frame.
You may explicitly add a call to produce the stack trace to the (example) code being instrumented for examination.
The task should allow the program to continue after generating the stack trace.
The task report here must include the trace from a sample program.
| #REXX | REXX | /* call stack */
say 'Call A'
call A '123'
say result
exit 0
A:
say 'Call B'
call B '456'
say result
return ARG(1)
B:
say 'Call C'
call C '789'
say result
return ARG(1)
C:
call callstack
return ARG(1)
callstack: procedure
getcallstack(cs.)
say 'Dump call stack with' cs.0 'items'
do i = 1 to cs.0
parse var cs.i line func
say format(line, 3) ':' left(func, 9) ': source "' || sourceline(line) || '"'
end
return cs.0 |
http://rosettacode.org/wiki/Stack_traces | Stack traces | Many programming languages allow for introspection of the current call stack environment. This can be for a variety of purposes such as enforcing security checks, debugging, or for getting access to the stack frame of callers.
Task
Print out (in a manner considered suitable for the platform) the current call stack.
The amount of information printed for each frame on the call stack is not constrained, but should include at least the name of the function or method at that level of the stack frame.
You may explicitly add a call to produce the stack trace to the (example) code being instrumented for examination.
The task should allow the program to continue after generating the stack trace.
The task report here must include the trace from a sample program.
| #Ruby | Ruby | def outer(a,b,c)
middle a+b, b+c
end
def middle(d,e)
inner d+e
end
def inner(f)
puts caller(0)
puts "continuing... my arg is #{f}"
end
outer 2,3,5 |
http://rosettacode.org/wiki/Stair-climbing_puzzle | Stair-climbing puzzle | From Chung-Chieh Shan (LtU):
Your stair-climbing robot has a very simple low-level API: the "step" function takes no argument and attempts to climb one step as a side effect. Unfortunately, sometimes the attempt fails and the robot clumsily falls one step instead. The "step" function detects what happens and returns a boolean flag: true on success, false on failure.
Write a function "step_up" that climbs one step up [from the initial position] (by repeating "step" attempts if necessary). Assume that the robot is not already at the top of the stairs, and neither does it ever reach the bottom of the stairs. How small can you make "step_up"? Can you avoid using variables (even immutable ones) and numbers?
Here's a pseudo-code of a simple recursive solution without using variables:
func step_up()
{
if not step() {
step_up();
step_up();
}
}
Inductive proof that step_up() steps up one step, if it terminates:
Base case (if the step() call returns true): it stepped up one step. QED
Inductive case (if the step() call returns false): Assume that recursive calls to step_up() step up one step. It stepped down one step (because step() returned false), but now we step up two steps using two step_up() calls. QED
The second (tail) recursion above can be turned into an iteration, as follows:
func step_up()
{
while not step() {
step_up();
}
}
| #PowerShell | PowerShell | function StepUp
{
If ( -not ( Step ) )
{
StepUp
StepUp
}
}
# Step simulator for testing
function Step
{
If ( Get-Random 0,1 )
{
$Success = $True
Write-Verbose "Up one step"
}
Else
{
$Success = $False
Write-Verbose "Fell one step"
}
return $Success
}
# Test
$VerbosePreference = 'Continue'
StepUp |
http://rosettacode.org/wiki/Stair-climbing_puzzle | Stair-climbing puzzle | From Chung-Chieh Shan (LtU):
Your stair-climbing robot has a very simple low-level API: the "step" function takes no argument and attempts to climb one step as a side effect. Unfortunately, sometimes the attempt fails and the robot clumsily falls one step instead. The "step" function detects what happens and returns a boolean flag: true on success, false on failure.
Write a function "step_up" that climbs one step up [from the initial position] (by repeating "step" attempts if necessary). Assume that the robot is not already at the top of the stairs, and neither does it ever reach the bottom of the stairs. How small can you make "step_up"? Can you avoid using variables (even immutable ones) and numbers?
Here's a pseudo-code of a simple recursive solution without using variables:
func step_up()
{
if not step() {
step_up();
step_up();
}
}
Inductive proof that step_up() steps up one step, if it terminates:
Base case (if the step() call returns true): it stepped up one step. QED
Inductive case (if the step() call returns false): Assume that recursive calls to step_up() step up one step. It stepped down one step (because step() returned false), but now we step up two steps using two step_up() calls. QED
The second (tail) recursion above can be turned into an iteration, as follows:
func step_up()
{
while not step() {
step_up();
}
}
| #Prolog | Prolog | step_up :- \+ step, step_up, step_up. |
http://rosettacode.org/wiki/Stair-climbing_puzzle | Stair-climbing puzzle | From Chung-Chieh Shan (LtU):
Your stair-climbing robot has a very simple low-level API: the "step" function takes no argument and attempts to climb one step as a side effect. Unfortunately, sometimes the attempt fails and the robot clumsily falls one step instead. The "step" function detects what happens and returns a boolean flag: true on success, false on failure.
Write a function "step_up" that climbs one step up [from the initial position] (by repeating "step" attempts if necessary). Assume that the robot is not already at the top of the stairs, and neither does it ever reach the bottom of the stairs. How small can you make "step_up"? Can you avoid using variables (even immutable ones) and numbers?
Here's a pseudo-code of a simple recursive solution without using variables:
func step_up()
{
if not step() {
step_up();
step_up();
}
}
Inductive proof that step_up() steps up one step, if it terminates:
Base case (if the step() call returns true): it stepped up one step. QED
Inductive case (if the step() call returns false): Assume that recursive calls to step_up() step up one step. It stepped down one step (because step() returned false), but now we step up two steps using two step_up() calls. QED
The second (tail) recursion above can be turned into an iteration, as follows:
func step_up()
{
while not step() {
step_up();
}
}
| #PureBasic | PureBasic | Procedure step_up()
Protected i
Repeat: If _step(): i + 1: Else: i - 1: EndIf: Until i = 1
EndProcedure |
http://rosettacode.org/wiki/Stack | Stack |
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.
A stack is a container of elements with last in, first out access policy. Sometimes it also called LIFO.
The stack is accessed through its top.
The basic stack operations are:
push stores a new element onto the stack top;
pop returns the last pushed stack element, while removing it from the stack;
empty tests if the stack contains no elements.
Sometimes the last pushed stack element is made accessible for immutable access (for read) or mutable access (for write):
top (sometimes called peek to keep with the p theme) returns the topmost element without modifying the stack.
Stacks allow a very simple hardware implementation.
They are common in almost all processors.
In programming, stacks are also very popular for their way (LIFO) of resource management, usually memory.
Nested scopes of language objects are naturally implemented by a stack (sometimes by multiple stacks).
This is a classical way to implement local variables of a re-entrant or recursive subprogram. Stacks are also used to describe a formal computational framework.
See stack machine.
Many algorithms in pattern matching, compiler construction (e.g. recursive descent parsers), and machine learning (e.g. based on tree traversal) have a natural representation in terms of stacks.
Task
Create a stack supporting the basic operations: push, pop, 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
| #ABAP | ABAP |
report z_stack.
interface stack.
methods:
push
importing
new_element type any
returning
value(new_stack) type ref to stack,
pop
exporting
top_element type any
returning
value(new_stack) type ref to stack,
empty
returning
value(is_empty) type abap_bool,
peek
exporting
top_element type any,
get_size
returning
value(size) type int4,
stringify
returning
value(stringified_stack) type string.
endinterface.
class character_stack definition.
public section.
interfaces:
stack.
methods:
constructor
importing
characters type string optional.
private section.
data:
characters type string.
endclass.
class character_stack implementation.
method stack~push.
characters = |{ new_element }{ characters }|.
new_stack = me.
endmethod.
method stack~pop.
if not me->stack~empty( ).
top_element = me->characters(1).
me->characters = me->characters+1.
endif.
new_stack = me.
endmethod.
method stack~empty.
is_empty = xsdbool( strlen( me->characters ) eq 0 ).
endmethod.
method stack~peek.
check not me->stack~empty( ).
top_element = me->characters(1).
endmethod.
method stack~get_size.
size = strlen( me->characters ).
endmethod.
method stack~stringify.
stringified_stack = cond string(
when me->stack~empty( )
then `empty`
else me->characters ).
endmethod.
method constructor.
check characters is not initial.
me->characters = characters.
endmethod.
endclass.
class integer_stack definition.
public section.
interfaces:
stack.
methods:
constructor
importing
integers type int4_table optional.
private section.
data:
integers type int4_table.
endclass.
class integer_stack implementation.
method stack~push.
append new_element to me->integers.
new_stack = me.
endmethod.
method stack~pop.
if not me->stack~empty( ).
top_element = me->integers[ me->stack~get_size( ) ].
delete me->integers index me->stack~get_size( ).
endif.
new_stack = me.
endmethod.
method stack~empty.
is_empty = xsdbool( lines( me->integers ) eq 0 ).
endmethod.
method stack~peek.
check not me->stack~empty( ).
top_element = me->integers[ lines( me->integers ) ].
endmethod.
method stack~get_size.
size = lines( me->integers ).
endmethod.
method stack~stringify.
stringified_stack = cond string(
when me->stack~empty( )
then `empty`
else reduce string(
init stack = ``
for integer in me->integers
next stack = |{ integer }{ stack }| ) ).
endmethod.
method constructor.
check integers is not initial.
me->integers = integers.
endmethod.
endclass.
start-of-selection.
data:
stack1 type ref to stack,
stack2 type ref to stack,
stack3 type ref to stack,
top_character type char1,
top_integer type int4.
stack1 = new character_stack( ).
stack2 = new integer_stack( ).
stack3 = new integer_stack( ).
write: |Stack1 = { stack1->stringify( ) }|, /.
stack1->push( 'a' )->push( 'b' )->push( 'c' )->push( 'd' ).
write: |push a, push b, push c, push d -> Stack1 = { stack1->stringify( ) }|, /.
stack1->pop( )->pop( importing top_element = top_character ).
write: |pop, pop and return element -> { top_character }, Stack1 = { stack1->stringify( ) }|, /, /.
write: |Stack2 = { stack2->stringify( ) }|, /.
stack2->push( 1 )->push( 2 )->push( 3 )->push( 4 ).
write: |push 1, push 2, push 3, push 4 -> Stack2 = { stack2->stringify( ) }|, /.
stack2->pop( )->pop( importing top_element = top_integer ).
write: |pop, pop and return element -> { top_integer }, Stack2 = { stack2->stringify( ) }|, /, /.
write: |Stack3 = { stack3->stringify( ) }|, /.
stack3->pop( ).
write: |pop -> Stack3 = { stack3->stringify( ) }|, /, /.
|
http://rosettacode.org/wiki/SQL-based_authentication | SQL-based authentication | This task has three parts:
Connect to a MySQL database (connect_db)
Create user/password records in the following table (create_user)
Authenticate login requests against the table (authenticate_user)
This is the table definition:
CREATE TABLE users (
userid INT PRIMARY KEY AUTO_INCREMENT,
username VARCHAR(32) UNIQUE KEY NOT NULL,
pass_salt tinyblob NOT NULL,
-- a string of 16 random bytes
pass_md5 tinyblob NOT NULL
-- binary MD5 hash of pass_salt concatenated with the password
);
(pass_salt and pass_md5 would be binary(16) values, but MySQL versions before 5.0.15 strip trailing spaces when selecting them.)
| #C.23 | C# | using System.Security.Cryptography;
using System.Text;
namespace rosettaMySQL
{
class Hasher
{
private static string _BytesToHex(byte[] input)
{
var strBuilder = new StringBuilder();
foreach (byte _byte in input)
{
strBuilder.Append(_byte.ToString("x2"));
}
return strBuilder.ToString();
}
public static string Hash(string salt, string input)
{
using (MD5 md5 = new MD5CryptoServiceProvider())
{
var bytes = Encoding.Default.GetBytes(salt + input);
var data = md5.ComputeHash(bytes);
return _BytesToHex(data);
}
}
public static string GenSalt()
{
using (RandomNumberGenerator rng = new RNGCryptoServiceProvider())
{
var salt = new byte[16];
rng.GetBytes(salt);
return _BytesToHex(salt);
}
}
}
} |
http://rosettacode.org/wiki/SQL-based_authentication | SQL-based authentication | This task has three parts:
Connect to a MySQL database (connect_db)
Create user/password records in the following table (create_user)
Authenticate login requests against the table (authenticate_user)
This is the table definition:
CREATE TABLE users (
userid INT PRIMARY KEY AUTO_INCREMENT,
username VARCHAR(32) UNIQUE KEY NOT NULL,
pass_salt tinyblob NOT NULL,
-- a string of 16 random bytes
pass_md5 tinyblob NOT NULL
-- binary MD5 hash of pass_salt concatenated with the password
);
(pass_salt and pass_md5 would be binary(16) values, but MySQL versions before 5.0.15 strip trailing spaces when selecting them.)
| #Go | Go | package main
import (
"bytes"
"crypto/md5"
"crypto/rand"
"database/sql"
"fmt"
_ "github.com/go-sql-driver/mysql"
)
func connectDB() (*sql.DB, error) {
return sql.Open("mysql", "rosetta:code@/rc")
}
func createUser(db *sql.DB, user, pwd string) error {
salt := make([]byte, 16)
rand.Reader.Read(salt)
_, err := db.Exec(`insert into users (username, pass_salt, pass_md5)
values (?, ?, ?)`, user, salt, saltHash(salt, pwd))
if err != nil {
return fmt.Errorf("User %s already exits", user)
}
return nil
}
func authenticateUser(db *sql.DB, user, pwd string) error {
var salt, hash []byte
row := db.QueryRow(`select pass_salt, pass_md5 from users
where username=?`, user)
if err := row.Scan(&salt, &hash); err != nil {
return fmt.Errorf("User %s unknown", user)
}
if !bytes.Equal(saltHash(salt, pwd), hash) {
return fmt.Errorf("User %s invalid password", user)
}
return nil
}
func saltHash(salt []byte, pwd string) []byte {
h := md5.New()
h.Write(salt)
h.Write([]byte(pwd))
return h.Sum(nil)
}
func main() {
// demonstrate
db, err := connectDB()
defer db.Close()
createUser(db, "sam", "123")
err = authenticateUser(db, "sam", "123")
if err == nil {
fmt.Println("User sam authenticated")
}
// extra
fmt.Println()
// show contents of database
rows, _ := db.Query(`select username, pass_salt, pass_md5 from users`)
var user string
var salt, hash []byte
for rows.Next() {
rows.Scan(&user, &salt, &hash)
fmt.Printf("%s %x %x\n", user, salt, hash)
}
// try creating same user again
err = createUser(db, "sam", "123")
fmt.Println(err)
// try authenticating unknown user
err = authenticateUser(db, "pam", "123")
fmt.Println(err)
// try wrong password
err = authenticateUser(db, "sam", "1234")
fmt.Println(err)
// clear table to run program again
db.Exec(`truncate table users`)
} |
http://rosettacode.org/wiki/Square_but_not_cube | Square but not cube | Task
Show the first 30 positive integers which are squares but not cubes of such integers.
Optionally, show also the first 3 positive integers which are both squares and cubes, and mark them as such.
| #Arturo | Arturo | squares: map 1..100 => [&^2]
cubes: map 1..100 => [&^3]
print "Square but not cube:"
print first.n:30 select squares => [not? in? & cubes]
print "Square and cube:"
print first.n:3 select squares => [in? & cubes] |
http://rosettacode.org/wiki/Square_but_not_cube | Square but not cube | Task
Show the first 30 positive integers which are squares but not cubes of such integers.
Optionally, show also the first 3 positive integers which are both squares and cubes, and mark them as such.
| #AutoHotkey | AutoHotkey | cube := [], counter:=0
while counter<30 {
cube[(n := A_Index)**3] := true
if !cube[n**2]
counter++, res .= n**2 " "
else
res .= "[" n**2 "] "
}
MsgBox % Trim(res, " ") |
http://rosettacode.org/wiki/Statistics/Basic | Statistics/Basic | Statistics is all about large groups of numbers.
When talking about a set of sampled data, most frequently used is their mean value and standard deviation (stddev).
If you have set of data
x
i
{\displaystyle x_{i}}
where
i
=
1
,
2
,
…
,
n
{\displaystyle i=1,2,\ldots ,n\,\!}
, the mean is
x
¯
≡
1
n
∑
i
x
i
{\displaystyle {\bar {x}}\equiv {1 \over n}\sum _{i}x_{i}}
, while the stddev is
σ
≡
1
n
∑
i
(
x
i
−
x
¯
)
2
{\displaystyle \sigma \equiv {\sqrt {{1 \over n}\sum _{i}\left(x_{i}-{\bar {x}}\right)^{2}}}}
.
When examining a large quantity of data, one often uses a histogram, which shows the counts of data samples falling into a prechosen set of intervals (or bins).
When plotted, often as bar graphs, it visually indicates how often each data value occurs.
Task Using your language's random number routine, generate real numbers in the range of [0, 1]. It doesn't matter if you chose to use open or closed range.
Create 100 of such numbers (i.e. sample size 100) and calculate their mean and stddev.
Do so for sample size of 1,000 and 10,000, maybe even higher if you feel like.
Show a histogram of any of these sets.
Do you notice some patterns about the standard deviation?
Extra Sometimes so much data need to be processed that it's impossible to keep all of them at once. Can you calculate the mean, stddev and histogram of a trillion numbers? (You don't really need to do a trillion numbers, just show how it can be done.)
Hint
For a finite population with equal probabilities at all points, one can derive:
(
x
−
x
¯
)
2
¯
=
x
2
¯
−
x
¯
2
{\displaystyle {\overline {(x-{\overline {x}})^{2}}}={\overline {x^{2}}}-{\overline {x}}^{2}}
Or, more verbosely:
1
N
∑
i
=
1
N
(
x
i
−
x
¯
)
2
=
1
N
(
∑
i
=
1
N
x
i
2
)
−
x
¯
2
.
{\displaystyle {\frac {1}{N}}\sum _{i=1}^{N}(x_{i}-{\overline {x}})^{2}={\frac {1}{N}}\left(\sum _{i=1}^{N}x_{i}^{2}\right)-{\overline {x}}^{2}.}
See also
Statistics/Normal distribution
Tasks for calculating statistical measures
in one go
moving (sliding window)
moving (cumulative)
Mean
Arithmetic
Statistics/Basic
Averages/Arithmetic mean
Averages/Pythagorean means
Averages/Simple moving average
Geometric
Averages/Pythagorean means
Harmonic
Averages/Pythagorean means
Quadratic
Averages/Root mean square
Circular
Averages/Mean angle
Averages/Mean time of day
Median
Averages/Median
Mode
Averages/Mode
Standard deviation
Statistics/Basic
Cumulative standard deviation
| #Elixir | Elixir | defmodule Statistics do
def basic(n) do
{sum, sum2, hist} = generate(n)
mean = sum / n
stddev = :math.sqrt(sum2 / n - mean*mean)
IO.puts "size: #{n}"
IO.puts "mean: #{mean}"
IO.puts "stddev: #{stddev}"
Enum.each(0..9, fn i ->
:io.fwrite "~.1f:~s~n", [0.1*i, String.duplicate("=", trunc(500 * hist[i] / n))]
end)
IO.puts ""
end
defp generate(n) do
hist = for i <- 0..9, into: %{}, do: {i,0}
Enum.reduce(1..n, {0, 0, hist}, fn _,{sum, sum2, h} ->
r = :rand.uniform
{sum+r, sum2+r*r, Map.update!(h, trunc(10*r), &(&1+1))}
end)
end
end
Enum.each([100,1000,10000], fn n ->
Statistics.basic(n)
end) |
http://rosettacode.org/wiki/Statistics/Basic | Statistics/Basic | Statistics is all about large groups of numbers.
When talking about a set of sampled data, most frequently used is their mean value and standard deviation (stddev).
If you have set of data
x
i
{\displaystyle x_{i}}
where
i
=
1
,
2
,
…
,
n
{\displaystyle i=1,2,\ldots ,n\,\!}
, the mean is
x
¯
≡
1
n
∑
i
x
i
{\displaystyle {\bar {x}}\equiv {1 \over n}\sum _{i}x_{i}}
, while the stddev is
σ
≡
1
n
∑
i
(
x
i
−
x
¯
)
2
{\displaystyle \sigma \equiv {\sqrt {{1 \over n}\sum _{i}\left(x_{i}-{\bar {x}}\right)^{2}}}}
.
When examining a large quantity of data, one often uses a histogram, which shows the counts of data samples falling into a prechosen set of intervals (or bins).
When plotted, often as bar graphs, it visually indicates how often each data value occurs.
Task Using your language's random number routine, generate real numbers in the range of [0, 1]. It doesn't matter if you chose to use open or closed range.
Create 100 of such numbers (i.e. sample size 100) and calculate their mean and stddev.
Do so for sample size of 1,000 and 10,000, maybe even higher if you feel like.
Show a histogram of any of these sets.
Do you notice some patterns about the standard deviation?
Extra Sometimes so much data need to be processed that it's impossible to keep all of them at once. Can you calculate the mean, stddev and histogram of a trillion numbers? (You don't really need to do a trillion numbers, just show how it can be done.)
Hint
For a finite population with equal probabilities at all points, one can derive:
(
x
−
x
¯
)
2
¯
=
x
2
¯
−
x
¯
2
{\displaystyle {\overline {(x-{\overline {x}})^{2}}}={\overline {x^{2}}}-{\overline {x}}^{2}}
Or, more verbosely:
1
N
∑
i
=
1
N
(
x
i
−
x
¯
)
2
=
1
N
(
∑
i
=
1
N
x
i
2
)
−
x
¯
2
.
{\displaystyle {\frac {1}{N}}\sum _{i=1}^{N}(x_{i}-{\overline {x}})^{2}={\frac {1}{N}}\left(\sum _{i=1}^{N}x_{i}^{2}\right)-{\overline {x}}^{2}.}
See also
Statistics/Normal distribution
Tasks for calculating statistical measures
in one go
moving (sliding window)
moving (cumulative)
Mean
Arithmetic
Statistics/Basic
Averages/Arithmetic mean
Averages/Pythagorean means
Averages/Simple moving average
Geometric
Averages/Pythagorean means
Harmonic
Averages/Pythagorean means
Quadratic
Averages/Root mean square
Circular
Averages/Mean angle
Averages/Mean time of day
Median
Averages/Median
Mode
Averages/Mode
Standard deviation
Statistics/Basic
Cumulative standard deviation
| #Factor | Factor | USING: assocs formatting grouping io kernel literals math
math.functions math.order math.statistics prettyprint random
sequences sequences.deep sequences.repeating ;
IN: rosetta-code.statistics-basic
CONSTANT: granularity
$[ 11 iota [ 10 /f ] map 2 clump ]
: mean/std ( seq -- a b )
[ mean ] [ population-std ] bi ;
: .mean/std ( seq -- )
mean/std [ "Mean: " write . ] [ "STD: " write . ] bi* ;
: count-between ( seq a b -- n )
[ between? ] 2curry count ;
: histo ( seq -- seq )
granularity [ first2 count-between ] with map ;
: bar ( n -- str )
[ dup 50 < ] [ 10 / ] until 2 * >integer "*" swap repeat ;
: (.histo) ( seq -- seq' )
[ bar ] map granularity swap zip flatten 3 group ;
: .histo ( seq -- )
(.histo) [ "%.1f - %.1f %s\n" vprintf ] each ;
: stats ( n -- )
dup "Statistics %d:\n" printf
random-units [ histo .histo ] [ .mean/std nl ] bi ;
: main ( -- )
{ 100 1,000 10,000 } [ stats ] each ;
MAIN: main |
http://rosettacode.org/wiki/Square-free_integers | Square-free integers | Task
Write a function to test if a number is square-free.
A square-free is an integer which is divisible by no perfect square other
than 1 (unity).
For this task, only positive square-free numbers will be used.
Show here (on this page) all square-free integers (in a horizontal format) that are between:
1 ───► 145 (inclusive)
1 trillion ───► 1 trillion + 145 (inclusive)
(One trillion = 1,000,000,000,000)
Show here (on this page) the count of square-free integers from:
1 ───► one hundred (inclusive)
1 ───► one thousand (inclusive)
1 ───► ten thousand (inclusive)
1 ───► one hundred thousand (inclusive)
1 ───► one million (inclusive)
See also
the Wikipedia entry: square-free integer
| #Julia | Julia | using Primes
const maxrootprime = Int64(floor(sqrt(1000000000145)))
const sqprimes = map(x -> x * x, primes(2, maxrootprime))
possdivisorsfor(n) = vcat(filter(x -> x <= n / 2, sqprimes), n in sqprimes ? n : [])
issquarefree(n) = all(x -> floor(n / x) != n / x, possdivisorsfor(n))
function squarefreebetween(mn, mx)
count = 1
padsize = length(string(mx)) + 2
println("The squarefree numbers between $mn and $mx are:")
for n in mn:mx
if issquarefree(n)
print(lpad(string(n), padsize))
count += 1
end
if count * padsize > 80
println()
count = 1
end
end
println()
end
function squarefreecount(intervals, maxnum)
count = 0
for n in 1:maxnum
for i in 1:length(intervals)
if intervals[i] < n
println("There are $count square free numbers between 1 and $(intervals[i]).")
intervals[i] = maxnum + 1
end
end
if issquarefree(n)
count += 1
end
end
println("There are $count square free numbers between 1 and $maxnum.")
end
squarefreebetween(1, 145)
squarefreebetween(1000000000000, 1000000000145)
squarefreecount([100, 1000, 10000, 100000], 1000000)
|
http://rosettacode.org/wiki/Square-free_integers | Square-free integers | Task
Write a function to test if a number is square-free.
A square-free is an integer which is divisible by no perfect square other
than 1 (unity).
For this task, only positive square-free numbers will be used.
Show here (on this page) all square-free integers (in a horizontal format) that are between:
1 ───► 145 (inclusive)
1 trillion ───► 1 trillion + 145 (inclusive)
(One trillion = 1,000,000,000,000)
Show here (on this page) the count of square-free integers from:
1 ───► one hundred (inclusive)
1 ───► one thousand (inclusive)
1 ───► ten thousand (inclusive)
1 ───► one hundred thousand (inclusive)
1 ───► one million (inclusive)
See also
the Wikipedia entry: square-free integer
| #Kotlin | Kotlin | // Version 1.2.50
import kotlin.math.sqrt
fun sieve(limit: Long): List<Long> {
val primes = mutableListOf(2L)
val c = BooleanArray(limit.toInt() + 1) // composite = true
// no need to process even numbers > 2
var p = 3
while (true) {
val p2 = p * p
if (p2 > limit) break
for (i in p2..limit step 2L * p) c[i.toInt()] = true
do { p += 2 } while (c[p])
}
for (i in 3..limit step 2)
if (!c[i.toInt()])
primes.add(i)
return primes
}
fun squareFree(r: LongProgression): List<Long> {
val primes = sieve(sqrt(r.last.toDouble()).toLong())
val results = mutableListOf<Long>()
outer@ for (i in r) {
for (p in primes) {
val p2 = p * p
if (p2 > i) break
if (i % p2 == 0L) continue@outer
}
results.add(i)
}
return results
}
fun printResults(r: LongProgression, c: Int, f: Int) {
println("Square-free integers from ${r.first} to ${r.last}:")
squareFree(r).chunked(c).forEach {
println()
it.forEach { print("%${f}d".format(it)) }
}
println('\n')
}
const val TRILLION = 1000000_000000L
fun main(args: Array<String>) {
printResults(1..145L, 20, 4)
printResults(TRILLION..TRILLION + 145L, 5, 14)
println("Number of square-free integers:\n")
longArrayOf(100, 1000, 10000, 100000, 1000000).forEach {
j -> println(" from 1 to $j = ${squareFree(1..j).size}")
}
} |
http://rosettacode.org/wiki/State_name_puzzle | State name puzzle | Background
This task is inspired by Mark Nelson's DDJ Column "Wordplay" and one of the weekly puzzle challenges from Will Shortz on NPR Weekend Edition [1] and originally attributed to David Edelheit.
The challenge was to take the names of two U.S. States, mix them all together, then rearrange the letters to form the names of two different U.S. States (so that all four state names differ from one another).
What states are these?
The problem was reissued on the Unicon Discussion Web which includes several solutions with analysis. Several techniques may be helpful and you may wish to refer to Gödel numbering, equivalence relations, and equivalence classes. The basic merits of these were discussed in the Unicon Discussion Web.
A second challenge in the form of a set of fictitious new states was also presented.
Task
Write a program to solve the challenge using both the original list of states and the fictitious list.
Caveats
case and spacing aren't significant - just letters (harmonize case)
don't expect the names to be in any order - such as being sorted
don't rely on names to be unique (eliminate duplicates - meaning if Iowa appears twice you can only use it once)
Comma separated list of state names used in the original puzzle:
"Alabama", "Alaska", "Arizona", "Arkansas",
"California", "Colorado", "Connecticut", "Delaware",
"Florida", "Georgia", "Hawaii", "Idaho", "Illinois",
"Indiana", "Iowa", "Kansas", "Kentucky", "Louisiana",
"Maine", "Maryland", "Massachusetts", "Michigan",
"Minnesota", "Mississippi", "Missouri", "Montana",
"Nebraska", "Nevada", "New Hampshire", "New Jersey",
"New Mexico", "New York", "North Carolina", "North Dakota",
"Ohio", "Oklahoma", "Oregon", "Pennsylvania", "Rhode Island",
"South Carolina", "South Dakota", "Tennessee", "Texas",
"Utah", "Vermont", "Virginia",
"Washington", "West Virginia", "Wisconsin", "Wyoming"
Comma separated list of additional fictitious state names to be added to the original (Includes a duplicate):
"New Kory", "Wen Kory", "York New", "Kory New", "New Kory"
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
| #zkl | zkl | #<<< // here doc
states:=("Alabama, Alaska, Arizona, Arkansas,
California, Colorado, Connecticut, Delaware, Florida,
Georgia, Hawaii, Idaho, Illinois, Indiana, Iowa, Kansas,
Kentucky, Louisiana, Maine, Maryland, Massachusetts,
Michigan, Minnesota, Mississippi, Missouri, Montana,
Nebraska, Nevada, New Hampshire, New Jersey, New Mexico,
New York, North Carolina, North Dakota, Ohio, Oklahoma,
Oregon, Pennsylvania, Rhode Island, South Carolina,
South Dakota, Tennessee, Texas, Utah, Vermont, Virginia,
Washington, West Virginia, Wisconsin, Wyoming"
/* Uncomment the next line for the fake states. */
# ",New Kory, Wen Kory, York New, Kory New, New Kory"
#<<<
).split(",").apply("strip");
smap:=Dictionary();
Utils.Helpers.pickNFrom(2,states).apply2('wrap(ss){ // 1225 combinations
key:=(ss.concat()).toLower().sort()-" ";
smap[key]=smap.find(key,List()).append(ss.concat(" + "));
});
foreach pairs in (smap.values){ // 1224 keys
// pairs=Utils.Helpers.listUnique(pairs); // eliminate dups
if(pairs.len()>1)
println(pairs.concat(" = ")) } |
http://rosettacode.org/wiki/String_append | String append |
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
Concatenation |
Interpolation |
Comparison |
Matching
Memory Operations
Pointers & references |
Addresses
Most languages provide a way to concatenate two string values, but some languages also provide a convenient way to append in-place to an existing string variable without referring to the variable twice.
Task
Create a string variable equal to any text value.
Append the string variable with another string literal in the most idiomatic way, without double reference if your language supports it.
Show the contents of the variable after the append operation.
| #Vlang | Vlang | mut s:= 'foo'
s += 'bar'
println(s)
foo := 'foo'
bar := 'bar'
foobar := '$foo$bar'
println(foobar) |
http://rosettacode.org/wiki/String_append | String append |
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
Concatenation |
Interpolation |
Comparison |
Matching
Memory Operations
Pointers & references |
Addresses
Most languages provide a way to concatenate two string values, but some languages also provide a convenient way to append in-place to an existing string variable without referring to the variable twice.
Task
Create a string variable equal to any text value.
Append the string variable with another string literal in the most idiomatic way, without double reference if your language supports it.
Show the contents of the variable after the append operation.
| #Wart | Wart | s <- "12345678"
s <- (s + "9!") |
http://rosettacode.org/wiki/String_append | String append |
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
Concatenation |
Interpolation |
Comparison |
Matching
Memory Operations
Pointers & references |
Addresses
Most languages provide a way to concatenate two string values, but some languages also provide a convenient way to append in-place to an existing string variable without referring to the variable twice.
Task
Create a string variable equal to any text value.
Append the string variable with another string literal in the most idiomatic way, without double reference if your language supports it.
Show the contents of the variable after the append operation.
| #Wren | Wren | var s = "Hello, "
s = s + "world!"
System.print(s) |
http://rosettacode.org/wiki/String_append | String append |
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
Concatenation |
Interpolation |
Comparison |
Matching
Memory Operations
Pointers & references |
Addresses
Most languages provide a way to concatenate two string values, but some languages also provide a convenient way to append in-place to an existing string variable without referring to the variable twice.
Task
Create a string variable equal to any text value.
Append the string variable with another string literal in the most idiomatic way, without double reference if your language supports it.
Show the contents of the variable after the append operation.
| #XPL0 | XPL0 | include xpllib;
char A, B, C(80);
[A:= "Hello, ";
B:= "world!";
StrCopy(C, A);
StrCat(C, B);
Text(0, C);
] |
http://rosettacode.org/wiki/Statistics/Normal_distribution | Statistics/Normal distribution | The Normal (or Gaussian) distribution is a frequently used distribution in statistics. While most programming languages provide a uniformly distributed random number generator, one can derive normally distributed random numbers from a uniform generator.
The task
Take a uniform random number generator and create a large (you decide how large) set of numbers that follow a normal (Gaussian) distribution. Calculate the dataset's mean and standard deviation, and show a histogram of the data.
Mention any native language support for the generation of normally distributed random numbers.
Reference
You may refer to code in Statistics/Basic if available.
| #VBA | VBA | Public Sub standard_normal()
Dim s() As Variant, bins(71) As Single
ReDim s(20000)
For i = 1 To 20000
s(i) = WorksheetFunction.Norm_S_Inv(Rnd())
Next i
For i = -35 To 35
bins(i + 36) = i / 10
Next i
Debug.Print "sample size"; UBound(s), "mean"; mean(s), "standard deviation"; standard_deviation(s)
t = WorksheetFunction.Frequency(s, bins)
For i = -35 To 35
Debug.Print Format((i - 1) / 10, "0.00");
Debug.Print "-"; Format(i / 10, "0.00"),
Debug.Print String$(t(i + 36, 1) / 10, "X");
Debug.Print
Next i
End Sub |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.