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/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
| #R | R |
#Generate the sets
a = runif(10,min=0,max=1)
b = runif(100,min=0,max=1)
c = runif(1000,min=0,max=1)
d = runif(10000,min=0,max=1)
#Print out the set of 10 values
cat("a = ",a)
#Print out the Mean and Standard Deviations of each of the sets
cat("Mean of a : ",mean(a))
cat("Standard Deviation of a : ", sd(a))
cat("Mean of b : ",mean(b))
cat("Standard Deviation of b : ", sd(b))
cat("Mean of c : ",mean(c))
cat("Standard Deviation of c : ", sd(c))
cat("Mean of d : ",mean(d))
cat("Standard Deviation of d : ", sd(d))
#Plotting the histogram of d
hist(d)
#Following lines error out due to insufficient memory
cat("Mean of a trillion random values in the range [0,1] : ",mean(runif(10^12,min=0,max=1)))
cat("Standard Deviation of a trillion random values in the range [0,1] : ", sd(runif(10^12,min=0,max=1)))
|
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
| #Racket | Racket |
#lang racket
(require math (only-in srfi/27 random-real))
(define (histogram n xs Δx)
(define (r x) (~r x #:precision 1 #:min-width 3))
(define (len count) (exact-floor (/ (* count 200) n)))
(for ([b (bin-samples (range 0 1 Δx) <= xs)])
(displayln (~a (r (sample-bin-min b)) "-" (r (sample-bin-max b)) ": "
(make-string (len (length (sample-bin-values b))) #\*)))))
(define (task n)
(define xs (for/list ([_ n]) (random-real)))
(displayln (~a "Number of samples: " n))
(displayln (~a "Mean: " (mean xs)))
(displayln (~a "Standard deviance: " (stddev xs)))
(histogram n xs 0.1)
(newline))
(task 100)
(task 1000)
(task 10000)
|
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.
| #TUSCRIPT | TUSCRIPT |
$$ MODE TUSCRIPT
digits=*
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
DATA 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
DATA 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
DATA 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
digits=SPLIT (digits,": :"), digitssort=DIGIT_SORT (digits)
SECTION format
formatstem=CENTER (currentstem,5," ")
PRINT formatstem, leaves
ENDSECTION
leaves="",currentstem=0
LOOP d=digitssort
leaf=mod(d,10),stem=d/10
IF (stem!=currentstem) THEN
DO format
IF (stem!=nextstem) THEN
currentstem=nextstem=nextstem+1,leaves=""
DO format
ENDIF
leaves=leaf, currentstem=stem
ELSE
leaves=APPEND (leaves,leaf), nextstem=stem+1
ENDIF
ENDLOOP
DO format
|
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.
| #uBasic.2F4tH | uBasic/4tH | Push 12, 127, 28, 42, 39, 113, 42, 18, 44, 118, 44, 37, 113, 124
Push 0, 13 : Gosub _Read ' read 1st line of data
Push 37, 48, 127, 36, 29, 31, 125, 139, 131, 115, 105, 132, 104, 123
Push 14, 27 : Gosub _Read ' read 2nd line of data
Push 35, 113, 122, 42, 117, 119, 58, 109, 23, 105, 63, 27, 44, 105
Push 28, 41 : Gosub _Read ' read 3rd line of data
Push 99, 41, 128, 121, 116, 125, 32, 61, 37, 127, 29, 113, 121, 58
Push 42, 55 : Gosub _Read ' read 4tH line of data
Push 114, 126, 53, 114, 96, 25, 109, 7, 31, 141, 46, 13, 27, 43
Push 56, 69 : Gosub _Read ' read 5th line of data
Push 117, 116, 27, 7, 68, 40, 31, 115, 124, 42, 128, 52, 71, 118
Push 70, 83 : Gosub _Read ' read 6th line of data
Push 117, 38, 27, 106, 33, 117, 116, 111, 40, 119, 47, 105, 57, 122
Push 84, 97 : Gosub _Read ' read 7th line of data
Push 109, 124, 115, 43, 120, 43, 27, 27, 18, 28, 48, 125, 107, 114
Push 98, 111 : Gosub _Read ' read 8th line of data
Push 34, 133, 45, 120, 30, 127, 31, 116, 146
Push 112, 120 : Gosub _Read ' read last line of data
Push 121 : Gosub _SimpleSort ' now sort 121 elements
i = @(0) / 10 - 1
For j = 0 To Pop() - 1 ' note array size was still on stack
d = @(j) / 10
Do While d > i
If j Print
i = i + 1
If i < 10 Print " "; ' align stem number
Print i;" |"; ' print stem number
Loop
Print @(j) % 10;" "; ' print leaf number
Next
Print ' print final LF
End
' simplest sorting algorithm
_SimpleSort ' ( n -- n)
For x = 0 To Tos() - 1
For y = x+1 To Tos() - 1
If @(x) > @ (y) Then ' if larger, switch elements
Push @(y)
@(y) = @(x)
@(x) = Pop()
Endif
Next
Next
Return
' read a line of data backwards
_Read ' (.. n1 n2 -- ..)
For x = Pop() To Pop() Step -1 ' loop from n2 to n1
@(x) = Pop() ' get element from stack
Next
Return |
http://rosettacode.org/wiki/Split_a_character_string_based_on_change_of_character | Split a character string based on change of character |
Task
Split a (character) string into comma (plus a blank) delimited
strings based on a change of character (left to right).
Show the output here (use the 1st example below).
Blanks should be treated as any other character (except
they are problematic to display clearly). The same applies
to commas.
For instance, the string:
gHHH5YY++///\
should be split and show:
g, HHH, 5, YY, ++, ///, \
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
| #FreeBASIC | FreeBASIC | function split( instring as string ) as string
if len(instring) < 2 then return instring
dim as string ret = left(instring,1)
for i as uinteger = 2 to len(instring)
if mid(instring,i,1)<>mid(instring, i - 1, 1) then ret + = ", "
ret += mid(instring, i, 1)
next i
return ret
end function |
http://rosettacode.org/wiki/Split_a_character_string_based_on_change_of_character | Split a character string based on change of character |
Task
Split a (character) string into comma (plus a blank) delimited
strings based on a change of character (left to right).
Show the output here (use the 1st example below).
Blanks should be treated as any other character (except
they are problematic to display clearly). The same applies
to commas.
For instance, the string:
gHHH5YY++///\
should be split and show:
g, HHH, 5, YY, ++, ///, \
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
| #FutureBasic | FutureBasic |
local fn SplitString( inputStr as Str255 ) as Str255
Str255 resultStr
NSUInteger i
if len$( inputStr ) < 2 then resultStr = inputStr : exit fn
resultStr = left$( inputStr, 1 )
for i = 2 to len$( inputStr )
if mid$( inputStr, i, 1 ) <> mid$( inputStr, i - 1, 1 ) then resultStr = resultStr + ", "
resultStr = resultStr + mid$(inputStr, i, 1)
next
end fn = resultStr
window 1
print fn SplitString( "gHHH5YY++///\" )
HandleEvents
|
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.
| #Racket | Racket | #lang racket
;; OEIS Definition
;; A002487
;; Stern's diatomic series
;; (or Stern-Brocot sequence):
;; a(0) = 0, a(1) = 1;
;; for n > 0:
;; a(2*n) = a(n),
;; a(2*n+1) = a(n) + a(n+1).
(define A002487
(let ((memo (make-hash '((0 . 0) (1 . 1)))))
(lambda (n)
(hash-ref! memo n
(lambda ()
(define n/2 (quotient n 2))
(+ (A002487 n/2) (if (even? n) 0 (A002487 (add1 n/2)))))))))
(define Stern-Brocot A002487)
(displayln "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)")
(for/list ((i (in-range 1 (add1 15)))) (Stern-Brocot i))
(displayln "Show the (1-based) index of where the numbers 1-to-10 first appears in the sequence.")
(for ((n (in-range 1 (add1 10))))
(for/first ((i (in-naturals 1))
#:when (= n (Stern-Brocot i)))
(printf "~a first found at a(~a)~%" n i)))
(displayln "Show the (1-based) index of where the number 100 first appears in the sequence.")
(for/first ((i (in-naturals 1)) #:when (= 100 (Stern-Brocot i))) i)
(displayln "Check that the greatest common divisor of all the two consecutive members of the
series up to the 1000th member, is always one.")
(unless
(for/first ((i (in-range 1 1000))
#:unless (= 1 (gcd (Stern-Brocot i) (Stern-Brocot (add1 i))))) #t)
(display "\tdidn't find gcd > (or otherwise ≠) 1")) |
http://rosettacode.org/wiki/Spinning_rod_animation/Text | Spinning rod animation/Text | Task
An animation with the following frames in the following order (if certain characters aren't available or can't be used correctly in the programming language, alternate characters can replace any of these frames) must animate with a delay of 0.25 seconds between each frame, with the previous frame being cleared before the next frame appears:
|
/
- or ─
\
A stand-alone version that loops and/or a version that doesn't loop can be made. These examples can also be converted into a system used in game development which is called on a HUD or GUI element requiring it to be called each frame to output the text, and advance the frame when the frame delay has passed. You can also use alternate text such as the . animation ( . | .. | ... | .. | repeat from . ) or the logic can be updated to include a ping/pong style where the frames advance forward, reach the end and then play backwards and when they reach the beginning they start over ( technically, you'd stop one frame prior to prevent the first frame playing twice, or write it another way ).
There are many different ways you can incorporate text animations. Here are a few text ideas - each frame is in quotes. If you can think of any, add them to this page! There are 2 examples for several of these; the first is the base animation with only unique sets of characters. The second consists of the primary set from a - n and doubled, minus the first and last element ie: We only want the center. This way an animation can play forwards, and then in reverse ( ping ponging ) without having to code that feature. For the animations with 3 elements, we only add 1, the center. with 4, it becomes 6. with 10, it becomes 18.
We don't need the second option for some of the animations if they connect smoothly, when animated, back to the first element. ... doesn't connect with . cleanly - there is a large leap. The rotating pipe meets the first perfectly so it isn't necessary, etc..
Dots - Option A requires ping / pong enabled script. Option B just adds the elements in the center.
'.', '..', '...'
'.', '..', '...', '..'
Pipe - This has the uniform sideways pipe instead of a hyphen to prevent non-uniform sizing.
'|', '/', '─', '\'
Stars - Option A requires ping / pong enabled script. Option B just adds the elements from the center.
'⁎', '⁑', '⁂'
'⁎', '⁑', '⁂', '⁑'
Clock - These need to be ordered. I haven't done this yet as the application I was testing the system in doesn't support these wingdings / icons. But this would look quite nice and you could set it up to go forward, or backward during an undo process, etc..
'🕛', '🕧', '🕐', '🕜', '🕑', '🕝', '🕒', '🕞', '🕓', '🕟', '🕔', '🕠', '🕕', '🕖', '🕗', '🕘', '🕙', '🕚', '🕡', '🕢', '🕣', '🕤', '🕥', '🕦'
Arrows:
'⬍', '⬈', '➞', '⬊', '⬍', '⬋', '⬅', '⬉'
Bird - This looks decent but may be missing something.
'︷', '︵', '︹', '︺', '︶', '︸'
'︷', '︵', '︹', '︺', '︶', '︸', '︶', '︺', '︹', '︵'
Plants - This isn't quite complete
'☘', '❀', '❁'
'☘', '❀', '❁', '❀'
Eclipse - From Raku Throbber post author
'🌑', '🌒', '🌓', '🌔', '🌕', '🌖', '🌗', '🌘'
| #M2000_Interpreter | M2000 Interpreter |
Module Checkit {
n$=lambda$ n=1, a$="|/-\" -> {
=mid$(a$, n, 1)
n++
if n>4 then n=1
}
\\ 1000 is 1 second
Every 250 {
\\ Print Over: erase line before print. No new line append.
Print Over n$()
}
}
CheckIt
|
http://rosettacode.org/wiki/Spinning_rod_animation/Text | Spinning rod animation/Text | Task
An animation with the following frames in the following order (if certain characters aren't available or can't be used correctly in the programming language, alternate characters can replace any of these frames) must animate with a delay of 0.25 seconds between each frame, with the previous frame being cleared before the next frame appears:
|
/
- or ─
\
A stand-alone version that loops and/or a version that doesn't loop can be made. These examples can also be converted into a system used in game development which is called on a HUD or GUI element requiring it to be called each frame to output the text, and advance the frame when the frame delay has passed. You can also use alternate text such as the . animation ( . | .. | ... | .. | repeat from . ) or the logic can be updated to include a ping/pong style where the frames advance forward, reach the end and then play backwards and when they reach the beginning they start over ( technically, you'd stop one frame prior to prevent the first frame playing twice, or write it another way ).
There are many different ways you can incorporate text animations. Here are a few text ideas - each frame is in quotes. If you can think of any, add them to this page! There are 2 examples for several of these; the first is the base animation with only unique sets of characters. The second consists of the primary set from a - n and doubled, minus the first and last element ie: We only want the center. This way an animation can play forwards, and then in reverse ( ping ponging ) without having to code that feature. For the animations with 3 elements, we only add 1, the center. with 4, it becomes 6. with 10, it becomes 18.
We don't need the second option for some of the animations if they connect smoothly, when animated, back to the first element. ... doesn't connect with . cleanly - there is a large leap. The rotating pipe meets the first perfectly so it isn't necessary, etc..
Dots - Option A requires ping / pong enabled script. Option B just adds the elements in the center.
'.', '..', '...'
'.', '..', '...', '..'
Pipe - This has the uniform sideways pipe instead of a hyphen to prevent non-uniform sizing.
'|', '/', '─', '\'
Stars - Option A requires ping / pong enabled script. Option B just adds the elements from the center.
'⁎', '⁑', '⁂'
'⁎', '⁑', '⁂', '⁑'
Clock - These need to be ordered. I haven't done this yet as the application I was testing the system in doesn't support these wingdings / icons. But this would look quite nice and you could set it up to go forward, or backward during an undo process, etc..
'🕛', '🕧', '🕐', '🕜', '🕑', '🕝', '🕒', '🕞', '🕓', '🕟', '🕔', '🕠', '🕕', '🕖', '🕗', '🕘', '🕙', '🕚', '🕡', '🕢', '🕣', '🕤', '🕥', '🕦'
Arrows:
'⬍', '⬈', '➞', '⬊', '⬍', '⬋', '⬅', '⬉'
Bird - This looks decent but may be missing something.
'︷', '︵', '︹', '︺', '︶', '︸'
'︷', '︵', '︹', '︺', '︶', '︸', '︶', '︺', '︹', '︵'
Plants - This isn't quite complete
'☘', '❀', '❁'
'☘', '❀', '❁', '❀'
Eclipse - From Raku Throbber post author
'🌑', '🌒', '🌓', '🌔', '🌕', '🌖', '🌗', '🌘'
| #Mathematica_.2F_Wolfram_Language | Mathematica / Wolfram Language | chars = "|/\[Dash]\\";
pos = 1;
Dynamic[c]
While[True,
pos = Mod[pos + 1, StringLength[chars], 1];
c = StringTake[chars, {pos}];
Pause[0.25];
] |
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
| #C.2B.2B | C++ | #include <stack> |
http://rosettacode.org/wiki/Special_variables | Special variables | Special variables have a predefined meaning within a computer programming language.
Task
List the special variables used within the language.
| #6502_Assembly | 6502 Assembly | ;DEFINING INTERRUPT VECTORS ON THE NES
org $FFFA
dw #### ;address of your NMI handler goes here (you can use labels for each of these for your convenience)
dw #### ;address of your Reset handler goes here
dw #### ;address of your IRQ handler goes here. |
http://rosettacode.org/wiki/Special_variables | Special variables | Special variables have a predefined meaning within a computer programming language.
Task
List the special variables used within the language.
| #Ada | Ada | #!/usr/local/bin/a68g --script #
FORMAT f = $g": ["g"]"l$;
printf((f,
"pi", pi,
"random", random, # actually a procedure #
"flip", flip,
"flop", flop,
"TRUE", TRUE,
"FALSE", FALSE,
"error char", error char,
"null character", null character,
CO "NIL", NIL, NIL is not printable END CO
# "lengths" details how many distinctive precisions are permitted. #
# e.g. int length = 3 suggests 3 distincts types: #
# INT, LONG INT, and LONG LONG INT #
"bits shorths", bits shorths,
"bits lengths", bits lengths,
"bytes shorths", bytes shorths,
"bytes lengths", bytes lengths,
"int shorths", int shorths,
"int lengths", int lengths,
"real shorths", real shorths,
"real lengths", real lengths,
"max abs char", max abs char,
# short/long int/real also possible #
"max int", max int,
"small real", small real,
"max real", max real,
# "width" indicates how many characters are require to prepresent the value #
# short/long bits/bytes/int/real also possible #
"bits width", bits width,
"bytes width", bytes width,
"int width", int width,
"real width", real width,
"exp width", exp width
));
# ALL the following are actually procedures #
print((
"space: [", space, "]", new line,
"new line: [", new line, "]", new line,
"new page: [", new page, "]", new line
CO the following are standard, but not implemented in algol68g
"char number: [", char number, "]", new line,
"line number: [", line number, "]", new line,
"page number: [", page number, "]", new line
END CO
));
SKIP |
http://rosettacode.org/wiki/Stable_marriage_problem | Stable marriage problem | Solve the Stable marriage problem using the Gale/Shapley algorithm.
Problem description
Given an equal number of men and women to be paired for marriage, each man ranks all the women in order of his preference and each woman ranks all the men in order of her preference.
A stable set of engagements for marriage is one where no man prefers a woman over the one he is engaged to, where that other woman also prefers that man over the one she is engaged to. I.e. with consulting marriages, there would be no reason for the engagements between the people to change.
Gale and Shapley proved that there is a stable set of engagements for any set of preferences and the first link above gives their algorithm for finding a set of stable engagements.
Task Specifics
Given ten males:
abe, bob, col, dan, ed, fred, gav, hal, ian, jon
And ten females:
abi, bea, cath, dee, eve, fay, gay, hope, ivy, jan
And a complete list of ranked preferences, where the most liked is to the left:
abe: abi, eve, cath, ivy, jan, dee, fay, bea, hope, gay
bob: cath, hope, abi, dee, eve, fay, bea, jan, ivy, gay
col: hope, eve, abi, dee, bea, fay, ivy, gay, cath, jan
dan: ivy, fay, dee, gay, hope, eve, jan, bea, cath, abi
ed: jan, dee, bea, cath, fay, eve, abi, ivy, hope, gay
fred: bea, abi, dee, gay, eve, ivy, cath, jan, hope, fay
gav: gay, eve, ivy, bea, cath, abi, dee, hope, jan, fay
hal: abi, eve, hope, fay, ivy, cath, jan, bea, gay, dee
ian: hope, cath, dee, gay, bea, abi, fay, ivy, jan, eve
jon: abi, fay, jan, gay, eve, bea, dee, cath, ivy, hope
abi: bob, fred, jon, gav, ian, abe, dan, ed, col, hal
bea: bob, abe, col, fred, gav, dan, ian, ed, jon, hal
cath: fred, bob, ed, gav, hal, col, ian, abe, dan, jon
dee: fred, jon, col, abe, ian, hal, gav, dan, bob, ed
eve: jon, hal, fred, dan, abe, gav, col, ed, ian, bob
fay: bob, abe, ed, ian, jon, dan, fred, gav, col, hal
gay: jon, gav, hal, fred, bob, abe, col, ed, dan, ian
hope: gav, jon, bob, abe, ian, dan, hal, ed, col, fred
ivy: ian, col, hal, gav, fred, bob, abe, ed, jon, dan
jan: ed, hal, gav, abe, bob, jon, col, ian, fred, dan
Use the Gale Shapley algorithm to find a stable set of engagements
Perturb this set of engagements to form an unstable set of engagements then check this new set for stability.
References
The Stable Marriage Problem. (Eloquent description and background information).
Gale-Shapley Algorithm Demonstration.
Another Gale-Shapley Algorithm Demonstration.
Stable Marriage Problem - Numberphile (Video).
Stable Marriage Problem (the math bit) (Video).
The Stable Marriage Problem and School Choice. (Excellent exposition)
| #11l | 11l | V guyprefers = [‘abe’ = [‘abi’, ‘eve’, ‘cath’, ‘ivy’, ‘jan’, ‘dee’, ‘fay’, ‘bea’, ‘hope’, ‘gay’],
‘bob’ = [‘cath’, ‘hope’, ‘abi’, ‘dee’, ‘eve’, ‘fay’, ‘bea’, ‘jan’, ‘ivy’, ‘gay’],
‘col’ = [‘hope’, ‘eve’, ‘abi’, ‘dee’, ‘bea’, ‘fay’, ‘ivy’, ‘gay’, ‘cath’, ‘jan’],
‘dan’ = [‘ivy’, ‘fay’, ‘dee’, ‘gay’, ‘hope’, ‘eve’, ‘jan’, ‘bea’, ‘cath’, ‘abi’],
‘ed’ = [‘jan’, ‘dee’, ‘bea’, ‘cath’, ‘fay’, ‘eve’, ‘abi’, ‘ivy’, ‘hope’, ‘gay’],
‘fred’= [‘bea’, ‘abi’, ‘dee’, ‘gay’, ‘eve’, ‘ivy’, ‘cath’, ‘jan’, ‘hope’, ‘fay’],
‘gav’ = [‘gay’, ‘eve’, ‘ivy’, ‘bea’, ‘cath’, ‘abi’, ‘dee’, ‘hope’, ‘jan’, ‘fay’],
‘hal’ = [‘abi’, ‘eve’, ‘hope’, ‘fay’, ‘ivy’, ‘cath’, ‘jan’, ‘bea’, ‘gay’, ‘dee’],
‘ian’ = [‘hope’, ‘cath’, ‘dee’, ‘gay’, ‘bea’, ‘abi’, ‘fay’, ‘ivy’, ‘jan’, ‘eve’],
‘jon’ = [‘abi’, ‘fay’, ‘jan’, ‘gay’, ‘eve’, ‘bea’, ‘dee’, ‘cath’, ‘ivy’, ‘hope’]]
V galprefers = [‘abi’ = [‘bob’, ‘fred’, ‘jon’, ‘gav’, ‘ian’, ‘abe’, ‘dan’, ‘ed’, ‘col’, ‘hal’],
‘bea’ = [‘bob’, ‘abe’, ‘col’, ‘fred’, ‘gav’, ‘dan’, ‘ian’, ‘ed’, ‘jon’, ‘hal’],
‘cath’= [‘fred’, ‘bob’, ‘ed’, ‘gav’, ‘hal’, ‘col’, ‘ian’, ‘abe’, ‘dan’, ‘jon’],
‘dee’ = [‘fred’, ‘jon’, ‘col’, ‘abe’, ‘ian’, ‘hal’, ‘gav’, ‘dan’, ‘bob’, ‘ed’],
‘eve’ = [‘jon’, ‘hal’, ‘fred’, ‘dan’, ‘abe’, ‘gav’, ‘col’, ‘ed’, ‘ian’, ‘bob’],
‘fay’ = [‘bob’, ‘abe’, ‘ed’, ‘ian’, ‘jon’, ‘dan’, ‘fred’, ‘gav’, ‘col’, ‘hal’],
‘gay’ = [‘jon’, ‘gav’, ‘hal’, ‘fred’, ‘bob’, ‘abe’, ‘col’, ‘ed’, ‘dan’, ‘ian’],
‘hope’= [‘gav’, ‘jon’, ‘bob’, ‘abe’, ‘ian’, ‘dan’, ‘hal’, ‘ed’, ‘col’, ‘fred’],
‘ivy’ = [‘ian’, ‘col’, ‘hal’, ‘gav’, ‘fred’, ‘bob’, ‘abe’, ‘ed’, ‘jon’, ‘dan’],
‘jan’ = [‘ed’, ‘hal’, ‘gav’, ‘abe’, ‘bob’, ‘jon’, ‘col’, ‘ian’, ‘fred’, ‘dan’]]
V guys = sorted(guyprefers.keys())
V gals = sorted(galprefers.keys())
F check(engaged)
V inverseengaged = Dict(engaged.map((k, v) -> (v, k)))
L(she, he) engaged
V shelikes = :galprefers[she]
V shelikesbetter = shelikes[0 .< shelikes.index(he)]
V helikes = :guyprefers[he]
V helikesbetter = helikes[0 .< helikes.index(she)]
L(guy) shelikesbetter
V guysgirl = inverseengaged[guy]
V guylikes = :guyprefers[guy]
I guylikes.index(guysgirl) > guylikes.index(she)
print(‘#. and #. like each other better than their present partners: #. and #., respectively’.format(she, guy, he, guysgirl))
R 0B
L(gal) helikesbetter
V girlsguy = engaged[gal]
V gallikes = :galprefers[gal]
I gallikes.index(girlsguy) > gallikes.index(he)
print(‘#. and #. like each other better than their present partners: #. and #., respectively’.format(he, gal, she, girlsguy))
R 0B
R 1B
F matchmaker()
V guysfree = copy(:guys)
[String = String] engaged
V guyprefers2 = copy(:guyprefers)
V galprefers2 = copy(:galprefers)
L !guysfree.empty
V guy = guysfree.pop(0)
V& guyslist = guyprefers2[guy]
V gal = guyslist.pop(0)
V fiance = engaged.get(gal, ‘’)
I fiance == ‘’
engaged[gal] = guy
print(‘ #. and #.’.format(guy, gal))
E
V galslist = galprefers2[gal]
I galslist.index(fiance) > galslist.index(guy)
engaged[gal] = guy
print(‘ #. dumped #. for #.’.format(gal, fiance, guy))
I !guyprefers2[fiance].empty
guysfree.append(fiance)
E
I !guyslist.empty
guysfree.append(guy)
R engaged
print("\nEngagements:")
V engaged = matchmaker()
print("\nCouples:")
print(‘ ’sorted(engaged.items()).map((couple_key, couple_val) -> ‘#. is engaged to #.’.format(couple_key, couple_val)).join(",\n "))
print()
print(I check(engaged) {‘Engagement stability check PASSED’} E ‘Engagement stability check FAILED’)
print("\n\nSwapping two fiances to introduce an error")
swap(&engaged[gals[0]], &engaged[gals[1]])
L(gal) gals[0.<2]
print(‘ #. is now engaged to #.’.format(gal, engaged[gal]))
print()
print(I check(engaged) {‘Engagement stability check PASSED’} E ‘Engagement stability check FAILED’) |
http://rosettacode.org/wiki/Spelling_of_ordinal_numbers | Spelling of ordinal numbers | Ordinal numbers (as used in this Rosetta Code task), are numbers that describe the position of something in a list.
It is this context that ordinal numbers will be used, using an English-spelled name of an ordinal number.
The ordinal numbers are (at least, one form of them):
1st 2nd 3rd 4th 5th 6th 7th ··· 99th 100th ··· 1000000000th ··· etc
sometimes expressed as:
1st 2nd 3rd 4th 5th 6th 7th ··· 99th 100th ··· 1000000000th ···
For this task, the following (English-spelled form) will be used:
first second third fourth fifth sixth seventh ninety-nineth one hundredth one billionth
Furthermore, the American version of numbers will be used here (as opposed to the British).
2,000,000,000 is two billion, not two milliard.
Task
Write a driver and a function (subroutine/routine ···) that returns the English-spelled ordinal version of a specified number (a positive integer).
Optionally, try to support as many forms of an integer that can be expressed: 123 00123.0 1.23e2 all are forms of the same integer.
Show all output here.
Test cases
Use (at least) the test cases of:
1 2 3 4 5 11 65 100 101 272 23456 8007006005004003
Related tasks
Number names
N'th
| #Clojure | Clojure | (def test-cases [1 2 3 4 5 11 65 100 101 272 23456 8007006005004003])
(pprint
(sort (zipmap test-cases (map #(clojure.pprint/cl-format nil "~:R" %) test-cases))))
|
http://rosettacode.org/wiki/Spelling_of_ordinal_numbers | Spelling of ordinal numbers | Ordinal numbers (as used in this Rosetta Code task), are numbers that describe the position of something in a list.
It is this context that ordinal numbers will be used, using an English-spelled name of an ordinal number.
The ordinal numbers are (at least, one form of them):
1st 2nd 3rd 4th 5th 6th 7th ··· 99th 100th ··· 1000000000th ··· etc
sometimes expressed as:
1st 2nd 3rd 4th 5th 6th 7th ··· 99th 100th ··· 1000000000th ···
For this task, the following (English-spelled form) will be used:
first second third fourth fifth sixth seventh ninety-nineth one hundredth one billionth
Furthermore, the American version of numbers will be used here (as opposed to the British).
2,000,000,000 is two billion, not two milliard.
Task
Write a driver and a function (subroutine/routine ···) that returns the English-spelled ordinal version of a specified number (a positive integer).
Optionally, try to support as many forms of an integer that can be expressed: 123 00123.0 1.23e2 all are forms of the same integer.
Show all output here.
Test cases
Use (at least) the test cases of:
1 2 3 4 5 11 65 100 101 272 23456 8007006005004003
Related tasks
Number names
N'th
| #Common_Lisp | Common Lisp | (defun ordinal-number (n)
(format nil "~:R" n))
#|
CL-USER> (loop for i in '(1 2 3 4 5 11 65 100 101 272 23456 8007006005004003)
do (format t "~a: ~a~%" i (ordinal-number i)))
1: first
2: second
3: third
4: fourth
5: fifth
11: eleventh
65: sixty-fifth
100: one hundredth
101: one hundred first
272: two hundred seventy-second
23456: twenty-three thousand four hundred fifty-sixth
8007006005004003: eight quadrillion seven trillion six billion five million four thousand third
NIL
|#
|
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.
| #jq | jq |
# Emit an unbounded stream
def squares_not_cubes:
def icbrt: pow(10; log10/3) | round;
range(1; infinite)
| (.*.)
| icbrt as $c
| select( ($c*$c*$c) != .);
limit(30; squares_not_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.
| #Julia | Julia |
iscube(n) = n == round(Int, cbrt(n))^3
println(collect(Iterators.take((n^2 for n in 1:10^6 if !iscube(n^2)), 30)))
|
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
| #Raku | Raku | for 100, 1_000, 10_000 -> $N {
say "size: $N";
my @data = rand xx $N;
printf "mean: %f\n", my $mean = $N R/ [+] @data;
printf "stddev: %f\n", sqrt
$mean**2 R- $N R/ [+] @data »**» 2;
printf "%.1f %s\n", .key, '=' x (500 * .value.elems / $N)
for sort @data.classify: (10 * *).Int / 10;
say '';
} |
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
| #REXX | REXX | /*REXX program generates some random numbers, shows bin histogram, finds mean & stdDev. */
numeric digits 20 /*use twenty decimal digits precision, */
showDigs=digits()%2 /* ··· but only show ten decimal digits*/
parse arg size seed . /*allow specification: size, and seed.*/
if size=='' | size=="," then size=100 /*Not specified? Then use the default.*/
if datatype(seed,'W') then call random ,,seed /*allow a seed for the RANDOM BIF. */
#.=0 /*count of the numbers in each bin. */
do j=1 for size /*generate some random numbers. */
@.j=random(, 99999) / 100000 /*express random number as a fraction. */
_=substr(@.j'00', 3, 1) /*determine which bin the number is in,*/
#._=#._ + 1 /* ··· and bump its count. */
end /*j*/
do k=0 for 10; kp=k + 1 /*show a histogram of the bins. */
lr='0.'k ; if k==0 then lr= "0 " /*adjust for the low range. */
hr='0.'kp ; if k==9 then hr= "1 " /* " " " high range. */
barPC=right( strip( left( format( 100*#.k / size, , 2), 5)), 5) /*compute the %. */
say lr"──►"hr' ' barPC copies("─", barPC * 2 % 1 ) /*show histogram.*/
end /*k*/
say
say 'sample size = ' size; say
avg= mean(size) ; say ' mean = ' format(avg, , showDigs)
std=stdDev(size) ; say ' stdDev = ' format(std, , showDigs)
exit /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
mean: arg N; $=0; do m=1 for N; $=$ + @.m; end; return $/N
stdDev: arg N; $=0; do s=1 for N; $=$ + (@.s-avg)**2; end; return sqrt($/N) /1
/*──────────────────────────────────────────────────────────────────────────────────────*/
sqrt: procedure; parse arg x; if x=0 then return 0; d=digits(); m.=9; numeric form; h=d+6
numeric digits; parse value format(x,2,1,,0) 'E0' with g 'E' _ .; g=g*.5'e'_ % 2
do j=0 while h>9; m.j=h; h=h%2+1; end /*j*/
do k=j+5 to 0 by -1; numeric digits m.k; g=(g+x/g)*.5; end /*k*/; return g |
http://rosettacode.org/wiki/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.
| #Ursala | Ursala | #import std
#import nat
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>
stemleaf_plot =
^|T(~&,' | '--)*+ -+
^p(pad` @hS; * ==` ~-rlT,mat` *tS)@hSS+ (%nP*)^|*H/~& ^lrNCT/iota ~&,
^(*+ ^C/~&+ -:0!,~&zl)+ ^|(~&,nleq-<)*+ nleq-<&l@lK2hlPrSXS+ * division\10+-
#show+
main = stemleaf_plot data |
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.
| #Wren | Wren | import "/fmt" for Fmt
var leafPlot = Fn.new { |x|
x.sort()
var i = (x[0]/10).floor - 1
for (j in 0...x.count) {
var d = (x[j] / 10).floor
while (d > i) {
i = i + 1
Fmt.write("$0s$3d |", (j != 0) ? "\n" : "", i)
}
System.write(" %(x[j] % 10)")
}
System.print()
}
var 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
]
leafPlot.call(data) |
http://rosettacode.org/wiki/Split_a_character_string_based_on_change_of_character | Split a character string based on change of character |
Task
Split a (character) string into comma (plus a blank) delimited
strings based on a change of character (left to right).
Show the output here (use the 1st example below).
Blanks should be treated as any other character (except
they are problematic to display clearly). The same applies
to commas.
For instance, the string:
gHHH5YY++///\
should be split and show:
g, HHH, 5, YY, ++, ///, \
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
| #Go | Go | package main
import (
"fmt"
"strings"
)
func main() {
fmt.Println(scc(`gHHH5YY++///\`))
}
func scc(s string) string {
if len(s) < 2 {
return s
}
var b strings.Builder
p := s[0]
b.WriteByte(p)
for _, c := range []byte(s[1:]) {
if c != p {
b.WriteString(", ")
}
b.WriteByte(c)
p = c
}
return b.String()
} |
http://rosettacode.org/wiki/Split_a_character_string_based_on_change_of_character | Split a character string based on change of character |
Task
Split a (character) string into comma (plus a blank) delimited
strings based on a change of character (left to right).
Show the output here (use the 1st example below).
Blanks should be treated as any other character (except
they are problematic to display clearly). The same applies
to commas.
For instance, the string:
gHHH5YY++///\
should be split and show:
g, HHH, 5, YY, ++, ///, \
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
| #Haskell | Haskell | import Data.List (group, intercalate)
main :: IO ()
main = putStrLn $ intercalate ", " (group "gHHH5YY++///\\") |
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.
| #Raku | Raku | constant @Stern-Brocot = 1, 1, { |(@_[$_ - 1] + @_[$_], @_[$_]) given ++$ } ... *;
put @Stern-Brocot[^15];
for flat 1..10, 100 -> $ix {
say "First occurrence of {$ix.fmt('%3d')} is at index: {([email protected]($ix, :k)).fmt('%4d')}";
}
say so 1 == all map ^1000: { [gcd] @Stern-Brocot[$_, $_ + 1] } |
http://rosettacode.org/wiki/Spinning_rod_animation/Text | Spinning rod animation/Text | Task
An animation with the following frames in the following order (if certain characters aren't available or can't be used correctly in the programming language, alternate characters can replace any of these frames) must animate with a delay of 0.25 seconds between each frame, with the previous frame being cleared before the next frame appears:
|
/
- or ─
\
A stand-alone version that loops and/or a version that doesn't loop can be made. These examples can also be converted into a system used in game development which is called on a HUD or GUI element requiring it to be called each frame to output the text, and advance the frame when the frame delay has passed. You can also use alternate text such as the . animation ( . | .. | ... | .. | repeat from . ) or the logic can be updated to include a ping/pong style where the frames advance forward, reach the end and then play backwards and when they reach the beginning they start over ( technically, you'd stop one frame prior to prevent the first frame playing twice, or write it another way ).
There are many different ways you can incorporate text animations. Here are a few text ideas - each frame is in quotes. If you can think of any, add them to this page! There are 2 examples for several of these; the first is the base animation with only unique sets of characters. The second consists of the primary set from a - n and doubled, minus the first and last element ie: We only want the center. This way an animation can play forwards, and then in reverse ( ping ponging ) without having to code that feature. For the animations with 3 elements, we only add 1, the center. with 4, it becomes 6. with 10, it becomes 18.
We don't need the second option for some of the animations if they connect smoothly, when animated, back to the first element. ... doesn't connect with . cleanly - there is a large leap. The rotating pipe meets the first perfectly so it isn't necessary, etc..
Dots - Option A requires ping / pong enabled script. Option B just adds the elements in the center.
'.', '..', '...'
'.', '..', '...', '..'
Pipe - This has the uniform sideways pipe instead of a hyphen to prevent non-uniform sizing.
'|', '/', '─', '\'
Stars - Option A requires ping / pong enabled script. Option B just adds the elements from the center.
'⁎', '⁑', '⁂'
'⁎', '⁑', '⁂', '⁑'
Clock - These need to be ordered. I haven't done this yet as the application I was testing the system in doesn't support these wingdings / icons. But this would look quite nice and you could set it up to go forward, or backward during an undo process, etc..
'🕛', '🕧', '🕐', '🕜', '🕑', '🕝', '🕒', '🕞', '🕓', '🕟', '🕔', '🕠', '🕕', '🕖', '🕗', '🕘', '🕙', '🕚', '🕡', '🕢', '🕣', '🕤', '🕥', '🕦'
Arrows:
'⬍', '⬈', '➞', '⬊', '⬍', '⬋', '⬅', '⬉'
Bird - This looks decent but may be missing something.
'︷', '︵', '︹', '︺', '︶', '︸'
'︷', '︵', '︹', '︺', '︶', '︸', '︶', '︺', '︹', '︵'
Plants - This isn't quite complete
'☘', '❀', '❁'
'☘', '❀', '❁', '❀'
Eclipse - From Raku Throbber post author
'🌑', '🌒', '🌓', '🌔', '🌕', '🌖', '🌗', '🌘'
| #MelonBasic | MelonBasic | Wait:0.25
Delete:1
Say:/
Wait:0.25
Delete:1
Say:-
Wait:0.25
Delete:1
Say:\
Wait:0.25
Delete:1
Goto:1 |
http://rosettacode.org/wiki/Spinning_rod_animation/Text | Spinning rod animation/Text | Task
An animation with the following frames in the following order (if certain characters aren't available or can't be used correctly in the programming language, alternate characters can replace any of these frames) must animate with a delay of 0.25 seconds between each frame, with the previous frame being cleared before the next frame appears:
|
/
- or ─
\
A stand-alone version that loops and/or a version that doesn't loop can be made. These examples can also be converted into a system used in game development which is called on a HUD or GUI element requiring it to be called each frame to output the text, and advance the frame when the frame delay has passed. You can also use alternate text such as the . animation ( . | .. | ... | .. | repeat from . ) or the logic can be updated to include a ping/pong style where the frames advance forward, reach the end and then play backwards and when they reach the beginning they start over ( technically, you'd stop one frame prior to prevent the first frame playing twice, or write it another way ).
There are many different ways you can incorporate text animations. Here are a few text ideas - each frame is in quotes. If you can think of any, add them to this page! There are 2 examples for several of these; the first is the base animation with only unique sets of characters. The second consists of the primary set from a - n and doubled, minus the first and last element ie: We only want the center. This way an animation can play forwards, and then in reverse ( ping ponging ) without having to code that feature. For the animations with 3 elements, we only add 1, the center. with 4, it becomes 6. with 10, it becomes 18.
We don't need the second option for some of the animations if they connect smoothly, when animated, back to the first element. ... doesn't connect with . cleanly - there is a large leap. The rotating pipe meets the first perfectly so it isn't necessary, etc..
Dots - Option A requires ping / pong enabled script. Option B just adds the elements in the center.
'.', '..', '...'
'.', '..', '...', '..'
Pipe - This has the uniform sideways pipe instead of a hyphen to prevent non-uniform sizing.
'|', '/', '─', '\'
Stars - Option A requires ping / pong enabled script. Option B just adds the elements from the center.
'⁎', '⁑', '⁂'
'⁎', '⁑', '⁂', '⁑'
Clock - These need to be ordered. I haven't done this yet as the application I was testing the system in doesn't support these wingdings / icons. But this would look quite nice and you could set it up to go forward, or backward during an undo process, etc..
'🕛', '🕧', '🕐', '🕜', '🕑', '🕝', '🕒', '🕞', '🕓', '🕟', '🕔', '🕠', '🕕', '🕖', '🕗', '🕘', '🕙', '🕚', '🕡', '🕢', '🕣', '🕤', '🕥', '🕦'
Arrows:
'⬍', '⬈', '➞', '⬊', '⬍', '⬋', '⬅', '⬉'
Bird - This looks decent but may be missing something.
'︷', '︵', '︹', '︺', '︶', '︸'
'︷', '︵', '︹', '︺', '︶', '︸', '︶', '︺', '︹', '︵'
Plants - This isn't quite complete
'☘', '❀', '❁'
'☘', '❀', '❁', '❀'
Eclipse - From Raku Throbber post author
'🌑', '🌒', '🌓', '🌔', '🌕', '🌖', '🌗', '🌘'
| #Microsoft_Small_Basic | Microsoft Small Basic | a[1]="|"
a[2]="/"
a[3]="-"
a[4]="\"
b=0
While b=0
For c=1 To 4
TextWindow.Clear()
TextWindow.WriteLine(a[c])
Program.Delay(250)
EndFor
EndWhile |
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
| #Clojure | Clojure | (deftype Stack [elements])
(def stack (Stack (ref ())))
(defn push-stack
"Pushes an item to the top of the stack."
[x] (dosync (alter (:elements stack) conj x)))
(defn pop-stack
"Pops an item from the top of the stack."
[] (let [fst (first (deref (:elements stack)))]
(dosync (alter (:elements stack) rest)) fst))
(defn top-stack
"Shows what's on the top of the stack."
[] (first (deref (:elements stack))))
(defn empty-stack?
"Tests whether or not the stack is empty."
[] (= () (deref (:elements stack)))) |
http://rosettacode.org/wiki/Special_variables | Special variables | Special variables have a predefined meaning within a computer programming language.
Task
List the special variables used within the language.
| #ALGOL_68 | ALGOL 68 | #!/usr/local/bin/a68g --script #
FORMAT f = $g": ["g"]"l$;
printf((f,
"pi", pi,
"random", random, # actually a procedure #
"flip", flip,
"flop", flop,
"TRUE", TRUE,
"FALSE", FALSE,
"error char", error char,
"null character", null character,
CO "NIL", NIL, NIL is not printable END CO
# "lengths" details how many distinctive precisions are permitted. #
# e.g. int length = 3 suggests 3 distincts types: #
# INT, LONG INT, and LONG LONG INT #
"bits shorths", bits shorths,
"bits lengths", bits lengths,
"bytes shorths", bytes shorths,
"bytes lengths", bytes lengths,
"int shorths", int shorths,
"int lengths", int lengths,
"real shorths", real shorths,
"real lengths", real lengths,
"max abs char", max abs char,
# short/long int/real also possible #
"max int", max int,
"small real", small real,
"max real", max real,
# "width" indicates how many characters are require to prepresent the value #
# short/long bits/bytes/int/real also possible #
"bits width", bits width,
"bytes width", bytes width,
"int width", int width,
"real width", real width,
"exp width", exp width
));
# ALL the following are actually procedures #
print((
"space: [", space, "]", new line,
"new line: [", new line, "]", new line,
"new page: [", new page, "]", new line
CO the following are standard, but not implemented in algol68g
"char number: [", char number, "]", new line,
"line number: [", line number, "]", new line,
"page number: [", page number, "]", new line
END CO
));
SKIP |
http://rosettacode.org/wiki/Stable_marriage_problem | Stable marriage problem | Solve the Stable marriage problem using the Gale/Shapley algorithm.
Problem description
Given an equal number of men and women to be paired for marriage, each man ranks all the women in order of his preference and each woman ranks all the men in order of her preference.
A stable set of engagements for marriage is one where no man prefers a woman over the one he is engaged to, where that other woman also prefers that man over the one she is engaged to. I.e. with consulting marriages, there would be no reason for the engagements between the people to change.
Gale and Shapley proved that there is a stable set of engagements for any set of preferences and the first link above gives their algorithm for finding a set of stable engagements.
Task Specifics
Given ten males:
abe, bob, col, dan, ed, fred, gav, hal, ian, jon
And ten females:
abi, bea, cath, dee, eve, fay, gay, hope, ivy, jan
And a complete list of ranked preferences, where the most liked is to the left:
abe: abi, eve, cath, ivy, jan, dee, fay, bea, hope, gay
bob: cath, hope, abi, dee, eve, fay, bea, jan, ivy, gay
col: hope, eve, abi, dee, bea, fay, ivy, gay, cath, jan
dan: ivy, fay, dee, gay, hope, eve, jan, bea, cath, abi
ed: jan, dee, bea, cath, fay, eve, abi, ivy, hope, gay
fred: bea, abi, dee, gay, eve, ivy, cath, jan, hope, fay
gav: gay, eve, ivy, bea, cath, abi, dee, hope, jan, fay
hal: abi, eve, hope, fay, ivy, cath, jan, bea, gay, dee
ian: hope, cath, dee, gay, bea, abi, fay, ivy, jan, eve
jon: abi, fay, jan, gay, eve, bea, dee, cath, ivy, hope
abi: bob, fred, jon, gav, ian, abe, dan, ed, col, hal
bea: bob, abe, col, fred, gav, dan, ian, ed, jon, hal
cath: fred, bob, ed, gav, hal, col, ian, abe, dan, jon
dee: fred, jon, col, abe, ian, hal, gav, dan, bob, ed
eve: jon, hal, fred, dan, abe, gav, col, ed, ian, bob
fay: bob, abe, ed, ian, jon, dan, fred, gav, col, hal
gay: jon, gav, hal, fred, bob, abe, col, ed, dan, ian
hope: gav, jon, bob, abe, ian, dan, hal, ed, col, fred
ivy: ian, col, hal, gav, fred, bob, abe, ed, jon, dan
jan: ed, hal, gav, abe, bob, jon, col, ian, fred, dan
Use the Gale Shapley algorithm to find a stable set of engagements
Perturb this set of engagements to form an unstable set of engagements then check this new set for stability.
References
The Stable Marriage Problem. (Eloquent description and background information).
Gale-Shapley Algorithm Demonstration.
Another Gale-Shapley Algorithm Demonstration.
Stable Marriage Problem - Numberphile (Video).
Stable Marriage Problem (the math bit) (Video).
The Stable Marriage Problem and School Choice. (Excellent exposition)
| #AutoHotkey | AutoHotkey | ; Given a complete list of ranked preferences, where the most liked is to the left:
abe := ["abi", "eve", "cath", "ivy", "jan", "dee", "fay", "bea", "hope", "gay"]
bob := ["cath", "hope", "abi", "dee", "eve", "fay", "bea", "jan", "ivy", "gay"]
col := ["hope", "eve", "abi", "dee", "bea", "fay", "ivy", "gay", "cath", "jan"]
dan := ["ivy", "fay", "dee", "gay", "hope", "eve", "jan", "bea", "cath", "abi"]
ed := ["jan", "dee", "bea", "cath", "fay", "eve", "abi", "ivy", "hope", "gay"]
fred := ["bea", "abi", "dee", "gay", "eve", "ivy", "cath", "jan", "hope", "fay"]
gav := ["gay", "eve", "ivy", "bea", "cath", "abi", "dee", "hope", "jan", "fay"]
hal := ["abi", "eve", "hope", "fay", "ivy", "cath", "jan", "bea", "gay", "dee"]
ian := ["hope", "cath", "dee", "gay", "bea", "abi", "fay", "ivy", "jan", "eve"]
jon := ["abi", "fay", "jan", "gay", "eve", "bea", "dee", "cath", "ivy", "hope"]
abi := ["bob", "fred", "jon", "gav", "ian", "abe", "dan", "ed", "col", "hal"]
bea := ["bob", "abe", "col", "fred", "gav", "dan", "ian", "ed", "jon", "hal"]
cath := ["fred", "bob", "ed", "gav", "hal", "col", "ian", "abe", "dan", "jon"]
dee := ["fred", "jon", "col", "abe", "ian", "hal", "gav", "dan", "bob", "ed"]
eve := ["jon", "hal", "fred", "dan", "abe", "gav", "col", "ed", "ian", "bob"]
fay := ["bob", "abe", "ed", "ian", "jon", "dan", "fred", "gav", "col", "hal"]
gay := ["jon", "gav", "hal", "fred", "bob", "abe", "col", "ed", "dan", "ian"]
hope := ["gav", "jon", "bob", "abe", "ian", "dan", "hal", "ed", "col", "fred"]
ivy := ["ian", "col", "hal", "gav", "fred", "bob", "abe", "ed", "jon", "dan"]
jan := ["ed", "hal", "gav", "abe", "bob", "jon", "col", "ian", "fred", "dan"]
; of ten males:
males := ["abe", "bob", "col", "dan", "ed", "fred", "gav", "hal", "ian", "jon"]
; and ten females:
females := ["abi", "bea", "cath", "dee", "eve", "fay", "gay", "hope", "ivy", "jan"]
; and an empty set of engagements:
engagements := Object()
freemales := males.Clone()
,s := "Engagements:`n"
; use the Gale Shapley algorithm to find a stable set of engagements:
For i, male in freemales ; i=index of male (not needed)
{
j:=1 ; index of female
While (engagements[female:=%male%[j]] != "" and index(%female%, male) > index(%female%, engagements[female]))
j++ ; each male loops through all females in order of his preference until one accepts him
If (engagements[female] != "") ; if she was previously engaged
freemales.insert(engagements[female]) ; her old male goes to the bottom of the list
,s .= female . " dumped " . engagements[female] . "`n"
engagements[female] := male ; the new engagement is registered
,s .= female . " accepted " . male . "`n"
}
; summarize results:
s .= "`nCouples:`n"
For female, male in engagements
s .= female . " is engaged to " . male . "`n"
s .= Stable(engagements, females)
; then perturb this set of engagements to form an unstable set of engagements then check this new set for stability:
s .= "`nWhat if cath and ivy swap?`n"
engagements["cath"]:="abe", engagements["ivy"]:="bob"
; summarize results:
s .= "`nCouples:`n"
For female, male in engagements
s .= female . " is engaged to " . male . "`n"
s .= Stable(engagements, females)
Msgbox % clipboard := s
Return
; Functions:
Index(obj, value) {
For key, val in obj
If (val = value)
Return, key, ErrorLevel := 0
Return, False, Errorlevel := 1
}
Stable(engagements, females) {
For female, male in engagements
{
For j, female2 in females ; j=index of female (not needed)
{
If (index(%male%, female) > index(%male%, female2)
and index(%female2%, male2:=engagements[female2]) > index(%female2%, male))
s .= male . " is engaged to " . female . " but would prefer " . female2
. " and " . female2 . " is engaged to " . male2 . " but would prefer " . male . "`n"
}
}
If s
Return "`nThese couples are not stable.`n" . s
Else
Return "`nThese couples are stable.`n"
} |
http://rosettacode.org/wiki/Spelling_of_ordinal_numbers | Spelling of ordinal numbers | Ordinal numbers (as used in this Rosetta Code task), are numbers that describe the position of something in a list.
It is this context that ordinal numbers will be used, using an English-spelled name of an ordinal number.
The ordinal numbers are (at least, one form of them):
1st 2nd 3rd 4th 5th 6th 7th ··· 99th 100th ··· 1000000000th ··· etc
sometimes expressed as:
1st 2nd 3rd 4th 5th 6th 7th ··· 99th 100th ··· 1000000000th ···
For this task, the following (English-spelled form) will be used:
first second third fourth fifth sixth seventh ninety-nineth one hundredth one billionth
Furthermore, the American version of numbers will be used here (as opposed to the British).
2,000,000,000 is two billion, not two milliard.
Task
Write a driver and a function (subroutine/routine ···) that returns the English-spelled ordinal version of a specified number (a positive integer).
Optionally, try to support as many forms of an integer that can be expressed: 123 00123.0 1.23e2 all are forms of the same integer.
Show all output here.
Test cases
Use (at least) the test cases of:
1 2 3 4 5 11 65 100 101 272 23456 8007006005004003
Related tasks
Number names
N'th
| #Factor | Factor | USING: assocs formatting grouping kernel literals locals math
math.parser math.text.english qw regexp sequences
splitting.extras ;
IN: rosetta-code.spelling-ordinal-numbers
<PRIVATE
! Factor supports the arbitrary use of commas in integer
! literals, as some number systems (e.g. Indian) don't solely
! break numbers up into triplets.
CONSTANT: test-cases qw{
1 2 3 4 5 11 65 100 101 272 23456 8007006005004003 123
00123.0 1.23e2 1,2,3 0b1111011 0o173 0x7B 2706/22
}
CONSTANT: replacements $[
qw{
one first
two second
three third
five fifth
eight eighth
nine ninth
twelve twelfth
} 2 group
]
: regular-ordinal ( n -- str )
[ number>text ] [ ordinal-suffix ] bi append ;
! Since Factor's number>text word contains commas and "and",
! strip them out with a regular expression.
: text>ordinal-text ( str -- str' ) R/ \sand|,/ "" re-replace ;
PRIVATE>
:: number>ordinal-text ( n! -- str )
n >integer n!
n number>text " ,-" split* dup last replacements at
[ [ but-last ] dip suffix "" join ]
[ drop n regular-ordinal ] if* text>ordinal-text ;
<PRIVATE
: print-ordinal-pair ( str x -- )
number>ordinal-text "%16s => %s\n" printf ;
PRIVATE>
: ordinal-text-demo ( -- )
test-cases [ dup string>number print-ordinal-pair ] each
"C{ 123 0 }" C{ 123 0 } print-ordinal-pair ;
MAIN: ordinal-text-demo |
http://rosettacode.org/wiki/Spelling_of_ordinal_numbers | Spelling of ordinal numbers | Ordinal numbers (as used in this Rosetta Code task), are numbers that describe the position of something in a list.
It is this context that ordinal numbers will be used, using an English-spelled name of an ordinal number.
The ordinal numbers are (at least, one form of them):
1st 2nd 3rd 4th 5th 6th 7th ··· 99th 100th ··· 1000000000th ··· etc
sometimes expressed as:
1st 2nd 3rd 4th 5th 6th 7th ··· 99th 100th ··· 1000000000th ···
For this task, the following (English-spelled form) will be used:
first second third fourth fifth sixth seventh ninety-nineth one hundredth one billionth
Furthermore, the American version of numbers will be used here (as opposed to the British).
2,000,000,000 is two billion, not two milliard.
Task
Write a driver and a function (subroutine/routine ···) that returns the English-spelled ordinal version of a specified number (a positive integer).
Optionally, try to support as many forms of an integer that can be expressed: 123 00123.0 1.23e2 all are forms of the same integer.
Show all output here.
Test cases
Use (at least) the test cases of:
1 2 3 4 5 11 65 100 101 272 23456 8007006005004003
Related tasks
Number names
N'th
| #Go | Go | import (
"fmt"
"strings"
)
func main() {
for _, n := range []int64{
1, 2, 3, 4, 5, 11, 65, 100, 101, 272, 23456, 8007006005004003,
} {
fmt.Println(sayOrdinal(n))
}
}
var irregularOrdinals = map[string]string{
"one": "first",
"two": "second",
"three": "third",
"five": "fifth",
"eight": "eighth",
"nine": "ninth",
"twelve": "twelfth",
}
func sayOrdinal(n int64) string {
s := say(n)
i := strings.LastIndexAny(s, " -")
i++
// Now s[:i] is everything upto and including the space or hyphen
// and s[i:] is the last word; we modify s[i:] as required.
// Since LastIndex returns -1 if there was no space/hyphen,
// `i` will be zero and this will still be fine.
if x, ok := irregularOrdinals[s[i:]]; ok {
s = s[:i] + x
} else if s[len(s)-1] == 'y' {
s = s[:i] + s[i:len(s)-1] + "ieth"
} else {
s = s[:i] + s[i:] + "th"
}
return s
}
// Below is a copy of https://rosettacode.org/wiki/Number_names#Go
var small = [...]string{"zero", "one", "two", "three", "four", "five", "six",
"seven", "eight", "nine", "ten", "eleven", "twelve", "thirteen",
"fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen"}
var tens = [...]string{"", "", "twenty", "thirty", "forty",
"fifty", "sixty", "seventy", "eighty", "ninety"}
var illions = [...]string{"", " thousand", " million", " billion",
" trillion", " quadrillion", " quintillion"}
func say(n int64) string {
var t string
if n < 0 {
t = "negative "
// Note, for math.MinInt64 this leaves n negative.
n = -n
}
switch {
case n < 20:
t += small[n]
case n < 100:
t += tens[n/10]
s := n % 10
if s > 0 {
t += "-" + small[s]
}
case n < 1000:
t += small[n/100] + " hundred"
s := n % 100
if s > 0 {
t += " " + say(s)
}
default:
// work right-to-left
sx := ""
for i := 0; n > 0; i++ {
p := n % 1000
n /= 1000
if p > 0 {
ix := say(p) + illions[i]
if sx != "" {
ix += " " + sx
}
sx = ix
}
}
t += sx
}
return t
} |
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.
| #Kotlin | Kotlin | // Version 1.2.60
fun main(args: Array<String>) {
var n = 1
var count = 0
while (count < 30) {
val sq = n * n
val cr = Math.cbrt(sq.toDouble()).toInt()
if (cr * cr * cr != sq) {
count++
println(sq)
}
else {
println("$sq is square and cube")
}
n++
}
} |
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
| #Ring | Ring |
# Project : Statistics/Basic
decimals(9)
sample(100)
sample(1000)
sample(10000)
func sample(n)
samp = list(n)
for i =1 to n
samp[i] =random(9)/10
next
sum = 0
sumSq = 0
for i = 1 to n
sum = sum + samp[i]
sumSq = sumSq +pow(samp[i],2)
next
see n + " Samples used." + nl
mean = sum / n
see "Mean = " + mean + nl
see "Std Dev = " + pow((sumSq /n -pow(mean,2)),0.5) + nl
bins2 = 10
bins = list(bins2)
for i = 1 to n
z = floor(bins2 * samp[i])
if z != 0
bins[z] = bins[z] +1
ok
next
for b = 1 to bins2
see b + " " + nl
for j = 1 to floor(bins2 *bins[b]) /n *70
see "*"
next
see nl
next
see nl
|
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
| #Ruby | Ruby | def generate_statistics(n)
sum = sum2 = 0.0
hist = Array.new(10, 0)
n.times do
r = rand
sum += r
sum2 += r**2
hist[(10*r).to_i] += 1
end
mean = sum / n
stddev = Math::sqrt((sum2 / n) - mean**2)
puts "size: #{n}"
puts "mean: #{mean}"
puts "stddev: #{stddev}"
hist.each_with_index {|x,i| puts "%.1f:%s" % [0.1*i, "=" * (70*x/hist.max)]}
puts
end
[100, 1000, 10000].each {|n| generate_statistics n} |
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.
| #zkl | zkl | fcn leaf_plot(xs){
xs=xs.sort();
i := xs[0] / 10 - 1;
foreach j in (xs.len()){
d := xs[j] / 10;
while (d > i){ print("%s%3d |".fmt(j and "\n" or "", i+=1)); }
print(" %d".fmt(xs[j] % 10));
}
println();
}
data := T(
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 );
leaf_plot(data); |
http://rosettacode.org/wiki/Split_a_character_string_based_on_change_of_character | Split a character string based on change of character |
Task
Split a (character) string into comma (plus a blank) delimited
strings based on a change of character (left to right).
Show the output here (use the 1st example below).
Blanks should be treated as any other character (except
they are problematic to display clearly). The same applies
to commas.
For instance, the string:
gHHH5YY++///\
should be split and show:
g, HHH, 5, YY, ++, ///, \
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
| #IS-BASIC | IS-BASIC | 100 LET S$="gHHH5YY++///\"
110 PRINT S$(1);
120 FOR I=2 TO LEN(S$)
130 IF S$(I)<>S$(I-1) THEN PRINT ", ";
140 PRINT S$(I);
150 NEXT
160 PRINT |
http://rosettacode.org/wiki/Split_a_character_string_based_on_change_of_character | Split a character string based on change of character |
Task
Split a (character) string into comma (plus a blank) delimited
strings based on a change of character (left to right).
Show the output here (use the 1st example below).
Blanks should be treated as any other character (except
they are problematic to display clearly). The same applies
to commas.
For instance, the string:
gHHH5YY++///\
should be split and show:
g, HHH, 5, YY, ++, ///, \
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
| #J | J | splitChars=: (1 ,~ 2 ~:/\ ]) <;.2 ]
delimitChars=: ', ' joinstring splitChars |
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.
| #REXX | REXX | /*REXX program generates & displays a Stern─Brocot sequence; finds 1─based indices; GCDs*/
parse arg N idx fix chk . /*get optional arguments from the C.L. */
if N=='' | N=="," then N= 15 /*Not specified? Then use the default.*/
if idx=='' | idx=="," then idx= 10 /* " " " " " " */
if fix=='' | fix=="," then fix= 100 /* " " " " " " */
if chk=='' | chk=="," then chk= 1000 /* " " " " " " */
if N>0 then say center('the first' N "numbers in the Stern─Brocot sequence", 70, '═')
a= Stern_Brocot(N) /*invoke function to generate sequence.*/
say a /*display the sequence to the terminal.*/
say
say center('the 1─based index for the first' idx "integers", 70, '═')
a= Stern_Brocot(-idx) /*invoke function to generate sequence.*/
w= length(idx); do i=1 for idx
say 'for ' right(i, w)", the index is: " wordpos(i, a)
end /*i*/
say
say center('the 1─based index for' fix, 70, "═")
a= Stern_Brocot(-fix) /*invoke function to generate sequence.*/
say 'for ' fix", the index is: " wordpos(fix, a)
say
if chk<2 then exit 0
say center('checking if all two consecutive members have a GCD=1', 70, '═')
a= Stern_Brocot(chk) /*invoke function to generate sequence.*/
do c=1 for chk-1; if gcd(subword(a, c, 2))==1 then iterate
say 'GCD check failed at index' c; exit 13
end /*c*/
say
say '───── All ' chk " two consecutive members have a GCD of unity."
exit 0 /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
gcd: procedure; $=; do i=1 for arg(); $= $ arg(i) /*get arg list. */
end /*i*/
parse var $ x z .; if x=0 then x= z /*is zero case? */
x=abs(x) /*use absolute x*/
do j=2 to words($); y=abs( word($, j) )
if y=0 then iterate /*ignore zeros. */
do until y==0; parse value x//y y with y x /* ◄──heavy work*/
end /*until*/
end /*j*/
return x /*return the GCD*/
/*──────────────────────────────────────────────────────────────────────────────────────*/
Stern_Brocot: parse arg h 1 f; $= 1 1; if h<0 then h= 1e9
else f= 0
f= abs(f)
do k=2 until words($)>=h | wordpos(f, $)\==0
_= word($, k); $= $ (_ + word($, k-1) ) _
end /*k*/
if f==0 then return subword($, 1, h)
return $ |
http://rosettacode.org/wiki/Spinning_rod_animation/Text | Spinning rod animation/Text | Task
An animation with the following frames in the following order (if certain characters aren't available or can't be used correctly in the programming language, alternate characters can replace any of these frames) must animate with a delay of 0.25 seconds between each frame, with the previous frame being cleared before the next frame appears:
|
/
- or ─
\
A stand-alone version that loops and/or a version that doesn't loop can be made. These examples can also be converted into a system used in game development which is called on a HUD or GUI element requiring it to be called each frame to output the text, and advance the frame when the frame delay has passed. You can also use alternate text such as the . animation ( . | .. | ... | .. | repeat from . ) or the logic can be updated to include a ping/pong style where the frames advance forward, reach the end and then play backwards and when they reach the beginning they start over ( technically, you'd stop one frame prior to prevent the first frame playing twice, or write it another way ).
There are many different ways you can incorporate text animations. Here are a few text ideas - each frame is in quotes. If you can think of any, add them to this page! There are 2 examples for several of these; the first is the base animation with only unique sets of characters. The second consists of the primary set from a - n and doubled, minus the first and last element ie: We only want the center. This way an animation can play forwards, and then in reverse ( ping ponging ) without having to code that feature. For the animations with 3 elements, we only add 1, the center. with 4, it becomes 6. with 10, it becomes 18.
We don't need the second option for some of the animations if they connect smoothly, when animated, back to the first element. ... doesn't connect with . cleanly - there is a large leap. The rotating pipe meets the first perfectly so it isn't necessary, etc..
Dots - Option A requires ping / pong enabled script. Option B just adds the elements in the center.
'.', '..', '...'
'.', '..', '...', '..'
Pipe - This has the uniform sideways pipe instead of a hyphen to prevent non-uniform sizing.
'|', '/', '─', '\'
Stars - Option A requires ping / pong enabled script. Option B just adds the elements from the center.
'⁎', '⁑', '⁂'
'⁎', '⁑', '⁂', '⁑'
Clock - These need to be ordered. I haven't done this yet as the application I was testing the system in doesn't support these wingdings / icons. But this would look quite nice and you could set it up to go forward, or backward during an undo process, etc..
'🕛', '🕧', '🕐', '🕜', '🕑', '🕝', '🕒', '🕞', '🕓', '🕟', '🕔', '🕠', '🕕', '🕖', '🕗', '🕘', '🕙', '🕚', '🕡', '🕢', '🕣', '🕤', '🕥', '🕦'
Arrows:
'⬍', '⬈', '➞', '⬊', '⬍', '⬋', '⬅', '⬉'
Bird - This looks decent but may be missing something.
'︷', '︵', '︹', '︺', '︶', '︸'
'︷', '︵', '︹', '︺', '︶', '︸', '︶', '︺', '︹', '︵'
Plants - This isn't quite complete
'☘', '❀', '❁'
'☘', '❀', '❁', '❀'
Eclipse - From Raku Throbber post author
'🌑', '🌒', '🌓', '🌔', '🌕', '🌖', '🌗', '🌘'
| #MiniScript | MiniScript | print "Press control-C to exit..."
while true
for c in "|/-\"
text.setCell 0, 0, c
wait 0.25
end for
end while |
http://rosettacode.org/wiki/Spinning_rod_animation/Text | Spinning rod animation/Text | Task
An animation with the following frames in the following order (if certain characters aren't available or can't be used correctly in the programming language, alternate characters can replace any of these frames) must animate with a delay of 0.25 seconds between each frame, with the previous frame being cleared before the next frame appears:
|
/
- or ─
\
A stand-alone version that loops and/or a version that doesn't loop can be made. These examples can also be converted into a system used in game development which is called on a HUD or GUI element requiring it to be called each frame to output the text, and advance the frame when the frame delay has passed. You can also use alternate text such as the . animation ( . | .. | ... | .. | repeat from . ) or the logic can be updated to include a ping/pong style where the frames advance forward, reach the end and then play backwards and when they reach the beginning they start over ( technically, you'd stop one frame prior to prevent the first frame playing twice, or write it another way ).
There are many different ways you can incorporate text animations. Here are a few text ideas - each frame is in quotes. If you can think of any, add them to this page! There are 2 examples for several of these; the first is the base animation with only unique sets of characters. The second consists of the primary set from a - n and doubled, minus the first and last element ie: We only want the center. This way an animation can play forwards, and then in reverse ( ping ponging ) without having to code that feature. For the animations with 3 elements, we only add 1, the center. with 4, it becomes 6. with 10, it becomes 18.
We don't need the second option for some of the animations if they connect smoothly, when animated, back to the first element. ... doesn't connect with . cleanly - there is a large leap. The rotating pipe meets the first perfectly so it isn't necessary, etc..
Dots - Option A requires ping / pong enabled script. Option B just adds the elements in the center.
'.', '..', '...'
'.', '..', '...', '..'
Pipe - This has the uniform sideways pipe instead of a hyphen to prevent non-uniform sizing.
'|', '/', '─', '\'
Stars - Option A requires ping / pong enabled script. Option B just adds the elements from the center.
'⁎', '⁑', '⁂'
'⁎', '⁑', '⁂', '⁑'
Clock - These need to be ordered. I haven't done this yet as the application I was testing the system in doesn't support these wingdings / icons. But this would look quite nice and you could set it up to go forward, or backward during an undo process, etc..
'🕛', '🕧', '🕐', '🕜', '🕑', '🕝', '🕒', '🕞', '🕓', '🕟', '🕔', '🕠', '🕕', '🕖', '🕗', '🕘', '🕙', '🕚', '🕡', '🕢', '🕣', '🕤', '🕥', '🕦'
Arrows:
'⬍', '⬈', '➞', '⬊', '⬍', '⬋', '⬅', '⬉'
Bird - This looks decent but may be missing something.
'︷', '︵', '︹', '︺', '︶', '︸'
'︷', '︵', '︹', '︺', '︶', '︸', '︶', '︺', '︹', '︵'
Plants - This isn't quite complete
'☘', '❀', '❁'
'☘', '❀', '❁', '❀'
Eclipse - From Raku Throbber post author
'🌑', '🌒', '🌓', '🌔', '🌕', '🌖', '🌗', '🌘'
| #Nim | Nim | import std/monotimes, times, os
const A = ["|", "/", "—", "\\"]
stdout.write "$\e[?25l" # Hide the cursor.
let start = getMonoTime()
while true:
for s in A:
stdout.write "$\e[2J" # Clear terminal.
stdout.write "$\e[0;0H" # Place cursor at top left corner.
for _ in 1..40:
stdout.write s & ' '
stdout.flushFile
os.sleep(250)
let now = getMonoTime()
if (now - start).inSeconds >= 5:
break
echo "$\e[?25h" # Restore the cursor. |
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
| #CLU | CLU | % Stack
stack = cluster [T: type] is new, push, pop, peek, empty
rep = array[T]
new = proc () returns (cvt)
return (rep$new())
end new
empty = proc (s: cvt) returns (bool)
return (rep$size(s) = 0)
end empty;
push = proc (s: cvt, val: T)
rep$addh(s, val)
end push;
pop = proc (s: cvt) returns (T) signals (empty)
if rep$empty(s)
then signal empty
else return(rep$remh(s))
end
end pop
peek = proc (s: cvt) returns (T) signals (empty)
if rep$empty(s)
then signal empty
else return(s[rep$high(s)])
end
end peek
end stack
start_up = proc ()
po: stream := stream$primary_output()
% Make a stack
s: stack[int] := stack[int]$new()
% Push 1..10 onto the stack
for i: int in int$from_to(1, 10) do
stack[int]$push(s, i)
end
% Pop items off the stack until the stack is empty
while ~stack[int]$empty(s) do
stream$putl(po, int$unparse(stack[int]$pop(s)))
end
% Trying to pop off the stack now should raise 'empty'
begin
i: int := stack[int]$pop(s)
stream$putl(po, "Still here! And I got: " || int$unparse(i))
end except when empty:
stream$putl(po, "The stack is empty.")
end
end start_up |
http://rosettacode.org/wiki/Special_variables | Special variables | Special variables have a predefined meaning within a computer programming language.
Task
List the special variables used within the language.
| #ALGOL_W | ALGOL W | % the Algol W standard environment includes the following standard variables: %
integer I_W % field width for integer output %
integer R_W % field width for real output %
integer R_D % number of decimal places for real output %
string(1) R_FORMAT % format for real output:
S - "scaled" normalised mantissa with exponent
A - "aligned" fixed point format
F - "free" either scaled or aligned as appropriate
for the value and field width
%
integer S_W % separator width - number of spaces following non-string output items %
integer MAXINTEGER % largest integer value %
real EPSILON % largest positive real number such that 1 + epsilon = 1 %
long real LONGEPSILON % largest positive long real number such that 1 + longepsilon = 1 %
long real MAXREAL % largest real number %
long real PI % approximation to pi %
% the following reference(EXCEPTION) variables control how errors are handled:
ENDFILE - end-of-file
OVFL - overflow
UNFL - underflow
DIVZERO - division by zero
INTOVFL - integer overflow
INTDIVZERO - integer division by zero or modulo 0
SQRTERR - invalid SQRT parameter
EXPERR - invalid EXP parameter
LNLOGERR - invalid LN or LOG parameter
SINCOSERR - invalid SIN or COS parameter
The EXCEPTION record is defined as follows:
record EXCEPTION( logical XCPNOTED - true if the exception has occurred
; integer XCPLIMIT - number of times the exception can occur
before the program terminates
, XCPACTION - if the program continues, controls how to
replace the erroneous value
; logical XCPMARK - true if an error message should be printed
even if the program continues
; string(64) XCPMSG - message to describe the exception
)
if the relevant EXCEPTION variable is null, the exception is ignored,
otherwise it is processed according to the settings of XCPLIMIT etc.
% |
http://rosettacode.org/wiki/Special_variables | Special variables | Special variables have a predefined meaning within a computer programming language.
Task
List the special variables used within the language.
| #Arturo | Arturo | %CD% - expands to the current directory string.
%DATE% - expands to current date using same format as DATE command.
%TIME% - expands to current time using same format as TIME command.
%RANDOM% - expands to a random decimal number between 0 and 32767.
%ERRORLEVEL% - expands to the current ERRORLEVEL value
%CMDEXTVERSION% - expands to the current Command Processor Extensions
version number.
%CMDCMDLINE% - expands to the original command line that invoked the
Command Processor.
%HIGHESTNUMANODENUMBER% - expands to the highest NUMA node number
on this machine. |
http://rosettacode.org/wiki/Stable_marriage_problem | Stable marriage problem | Solve the Stable marriage problem using the Gale/Shapley algorithm.
Problem description
Given an equal number of men and women to be paired for marriage, each man ranks all the women in order of his preference and each woman ranks all the men in order of her preference.
A stable set of engagements for marriage is one where no man prefers a woman over the one he is engaged to, where that other woman also prefers that man over the one she is engaged to. I.e. with consulting marriages, there would be no reason for the engagements between the people to change.
Gale and Shapley proved that there is a stable set of engagements for any set of preferences and the first link above gives their algorithm for finding a set of stable engagements.
Task Specifics
Given ten males:
abe, bob, col, dan, ed, fred, gav, hal, ian, jon
And ten females:
abi, bea, cath, dee, eve, fay, gay, hope, ivy, jan
And a complete list of ranked preferences, where the most liked is to the left:
abe: abi, eve, cath, ivy, jan, dee, fay, bea, hope, gay
bob: cath, hope, abi, dee, eve, fay, bea, jan, ivy, gay
col: hope, eve, abi, dee, bea, fay, ivy, gay, cath, jan
dan: ivy, fay, dee, gay, hope, eve, jan, bea, cath, abi
ed: jan, dee, bea, cath, fay, eve, abi, ivy, hope, gay
fred: bea, abi, dee, gay, eve, ivy, cath, jan, hope, fay
gav: gay, eve, ivy, bea, cath, abi, dee, hope, jan, fay
hal: abi, eve, hope, fay, ivy, cath, jan, bea, gay, dee
ian: hope, cath, dee, gay, bea, abi, fay, ivy, jan, eve
jon: abi, fay, jan, gay, eve, bea, dee, cath, ivy, hope
abi: bob, fred, jon, gav, ian, abe, dan, ed, col, hal
bea: bob, abe, col, fred, gav, dan, ian, ed, jon, hal
cath: fred, bob, ed, gav, hal, col, ian, abe, dan, jon
dee: fred, jon, col, abe, ian, hal, gav, dan, bob, ed
eve: jon, hal, fred, dan, abe, gav, col, ed, ian, bob
fay: bob, abe, ed, ian, jon, dan, fred, gav, col, hal
gay: jon, gav, hal, fred, bob, abe, col, ed, dan, ian
hope: gav, jon, bob, abe, ian, dan, hal, ed, col, fred
ivy: ian, col, hal, gav, fred, bob, abe, ed, jon, dan
jan: ed, hal, gav, abe, bob, jon, col, ian, fred, dan
Use the Gale Shapley algorithm to find a stable set of engagements
Perturb this set of engagements to form an unstable set of engagements then check this new set for stability.
References
The Stable Marriage Problem. (Eloquent description and background information).
Gale-Shapley Algorithm Demonstration.
Another Gale-Shapley Algorithm Demonstration.
Stable Marriage Problem - Numberphile (Video).
Stable Marriage Problem (the math bit) (Video).
The Stable Marriage Problem and School Choice. (Excellent exposition)
| #Batch_File | Batch File | :: Stable Marriage Problem in Rosetta Code
:: Batch File Implementation
@echo off
setlocal enabledelayedexpansion
:: Initialization (Index Starts in 0)
set "male=abe bob col dan ed fred gav hal ian jon"
set "femm=abi bea cath dee eve fay gay hope ivy jan"
set "abe[]=abi, eve, cath, ivy, jan, dee, fay, bea, hope, gay"
set "bob[]=cath, hope, abi, dee, eve, fay, bea, jan, ivy, gay"
set "col[]=hope, eve, abi, dee, bea, fay, ivy, gay, cath, jan"
set "dan[]=ivy, fay, dee, gay, hope, eve, jan, bea, cath, abi"
set "ed[]=jan, dee, bea, cath, fay, eve, abi, ivy, hope, gay"
set "fred[]=bea, abi, dee, gay, eve, ivy, cath, jan, hope, fay"
set "gav[]=gay, eve, ivy, bea, cath, abi, dee, hope, jan, fay"
set "hal[]=abi, eve, hope, fay, ivy, cath, jan, bea, gay, dee"
set "ian[]=hope, cath, dee, gay, bea, abi, fay, ivy, jan, eve"
set "jon[]=abi, fay, jan, gay, eve, bea, dee, cath, ivy, hope"
set "abi[]=bob, fred, jon, gav, ian, abe, dan, ed, col, hal"
set "bea[]=bob, abe, col, fred, gav, dan, ian, ed, jon, hal"
set "cath[]=fred, bob, ed, gav, hal, col, ian, abe, dan, jon"
set "dee[]=fred, jon, col, abe, ian, hal, gav, dan, bob, ed"
set "eve[]=jon, hal, fred, dan, abe, gav, col, ed, ian, bob"
set "fay[]=bob, abe, ed, ian, jon, dan, fred, gav, col, hal"
set "gay[]=jon, gav, hal, fred, bob, abe, col, ed, dan, ian"
set "hope[]=gav, jon, bob, abe, ian, dan, hal, ed, col, fred"
set "ivy[]=ian, col, hal, gav, fred, bob, abe, ed, jon, dan"
set "jan[]=ed, hal, gav, abe, bob, jon, col, ian, fred, dan"
rem variable notation:
rem <boy>{<index>} = <girl>
rem <boy>[<girl>] = <index>
for %%M in (%male%) do (
set cnt=0
for %%. in (!%%M[]!) do (
set "%%M{!cnt!}=%%."
set "%%M[%%.]=!cnt!"
set /a cnt+=1
)
)
for %%F in (%femm%) do (
set cnt=0
for %%. in (!%%F[]!) do (
set "%%F[%%.]=!cnt!"
set /a cnt+=1
)
)
:: The Main Thing
echo(HISTORY:
call :stableMatching
echo(
echo(NEWLYWEDS:
call :display
echo(
call :isStable
echo(
echo(What if ed and hal swapped?
call :swapper ed hal
echo(
echo(NEW-NEWLYWEDS:
call :display
echo(
call :isStable
pause>nul
exit /b 0
:: The Algorithm
:stableMatching
set "free_men=%male%"
set "free_fem=%femm%"
for %%M in (%male%) do set "%%M_tried=0"
:match_loop
if "%free_men%"=="" goto :EOF
for /f "tokens=1* delims= " %%m in ("%free_men%") do (
rem get woman not yet proposed to, but if man's tries exceeds the number
rem of women (poor guy), he starts again to his most preferred woman (#0).
for /f %%x in ("!%%m_tried!") do if not defined %%m{%%x} (
set "%%m_tried=0" & set "w=!%%m{0}!"
) else set "w=!%%m{%%x}!"
set "m=%%m"
for /f %%x in ("free_fem:!w!=") do (
if not "!free_fem!"=="!%%x!" (
rem accept because !w! (the woman) is free
set "!m!_=!w!" & set "!w!_=!m!"
set "free_men=%%n" & set "free_fem=!%%x!"
echo( !w! ACCEPTED !m!.
) else (
rem here, !w! already has a pair; get his name and rank.
for /f %%. in ("!w!") do set "cur_man=!%%._!"
for /f %%. in ("!w![!cur_man!]") do set "rank_cur=!%%.!"
rem also, get the rank of current proposing man.
for /f %%. in ("!w![!m!]") do set "rank_new=!%%.!"
if !rank_new! lss !rank_cur! (
rem here, !w! will leave her pair, and choose !m!.
set "free_men=%%n !cur_man!"
echo( !w! LEFT !cur_man!.
rem pair them up now!
set "!m!_=!w!" & set "!w!_=!m!"
echo( !w! ACCEPTED !m!.
)
)
)
set /a "!m!_tried+=1"
)
goto :match_loop
:: Output the Couples
:display
for %%S in (%femm%) do echo. %%S and !%%S_!.
goto :EOF
:: Stability Checking
:isStable
for %%f in (%femm%) do (
for %%g in (%male%) do (
for /f %%. in ("%%f[!%%f_!]") do set "girl_cur=!%%.!"
set "girl_aboy=!%%f[%%g]!"
for /f %%. in ("%%g[!%%g_!]") do set "boy_cur=!%%.!"
set "boy_agirl=!%%g[%%f]!"
if !boy_cur! gtr !boy_agirl! (
if !girl_cur! gtr !girl_aboy! (
echo(STABILITY = FALSE.
echo(%%f and %%g would rather be together than their current partners.
goto :EOF
)
)
)
)
echo(STABILITY = TRUE.
goto :EOF
:: Swapper
:swapper
set %~1.tmp=!%~1_!
set %~2.tmp=!%~2_!
set "%~1_=!%~2.tmp!"
set "%~2_=!%~1.tmp!"
set "!%~1.tmp!_=%~2"
set "!%~2.tmp!_=%~1"
goto :EOF |
http://rosettacode.org/wiki/Spelling_of_ordinal_numbers | Spelling of ordinal numbers | Ordinal numbers (as used in this Rosetta Code task), are numbers that describe the position of something in a list.
It is this context that ordinal numbers will be used, using an English-spelled name of an ordinal number.
The ordinal numbers are (at least, one form of them):
1st 2nd 3rd 4th 5th 6th 7th ··· 99th 100th ··· 1000000000th ··· etc
sometimes expressed as:
1st 2nd 3rd 4th 5th 6th 7th ··· 99th 100th ··· 1000000000th ···
For this task, the following (English-spelled form) will be used:
first second third fourth fifth sixth seventh ninety-nineth one hundredth one billionth
Furthermore, the American version of numbers will be used here (as opposed to the British).
2,000,000,000 is two billion, not two milliard.
Task
Write a driver and a function (subroutine/routine ···) that returns the English-spelled ordinal version of a specified number (a positive integer).
Optionally, try to support as many forms of an integer that can be expressed: 123 00123.0 1.23e2 all are forms of the same integer.
Show all output here.
Test cases
Use (at least) the test cases of:
1 2 3 4 5 11 65 100 101 272 23456 8007006005004003
Related tasks
Number names
N'th
| #Haskell | Haskell | spellOrdinal :: Integer -> String
spellOrdinal n
| n <= 0 = "not ordinal"
| n < 20 = small n
| n < 100 = case divMod n 10 of
(k, 0) -> spellInteger (10*k) ++ "th"
(k, m) -> spellInteger (10*k) ++ "-" ++ spellOrdinal m
| n < 1000 = case divMod n 100 of
(k, 0) -> spellInteger (100*k) ++ "th"
(k, m) -> spellInteger (100*k) ++ " and " ++ spellOrdinal m
| otherwise = case divMod n 1000 of
(k, 0) -> spellInteger (1000*k) ++ "th"
(k, m) -> spellInteger (k*1000) ++ s ++ spellOrdinal m
where s = if m < 100 then " and " else ", "
where
small = ([ undefined, "first", "second", "third", "fourth", "fifth"
, "sixth", "seventh", "eighth", "nineth", "tenth", "eleventh"
, "twelveth", "thirteenth", "fourteenth", "fifteenth", "sixteenth"
, "seventeenth", "eighteenth", "nineteenth"] !!) . fromEnum |
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.
| #Ksh | Ksh |
#!/bin/ksh
# First 30 positive integers which are squares but not cubes
# also, the first 3 positive integers which are both squares and cubes
######
# main #
######
integer n sq cr cnt=0
for (( n=1; cnt<30; n++ )); do
(( sq = n * n ))
(( cr = cbrt(sq) ))
if (( (cr * cr * cr) != sq )); then
(( cnt++ ))
print ${sq}
else
print "${sq} is square and cube"
fi
done |
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.
| #LOLCODE | LOLCODE | HAI 1.2
I HAS A SkwareKyoobs ITZ A BUKKIT
I HAS A NumbarSkwareKyoobs ITZ 0
I HAS A NotKyoobs ITZ 0
I HAS A Index ITZ 1
I HAS A Skware ITZ 1
I HAS A Kyoob ITZ 1
I HAS A Root ITZ 1
VISIBLE "Skwares but not kyoobs::"
IM IN YR Outer UPPIN YR Dummy WILE DIFFRINT NotKyoobs AN 30
Skware R PRODUKT OF Index AN Index
IM IN YR Inner UPPIN YR OtherDummy WILE DIFFRINT Kyoob AN BIGGR OF Skware AN Kyoob
Root R SUM OF Root AN 1
Kyoob R PRODUKT OF PRODUKT OF Root AN Root AN Root
IM OUTTA YR Inner
BOTH SAEM Skware AN Kyoob, O RLY?
YA RLY
SkwareKyoobs HAS A SRS NumbarSkwareKyoobs ITZ Skware
NumbarSkwareKyoobs R SUM OF NumbarSkwareKyoobs AN 1
NO WAI
BOTH SAEM Kyoob AN BIGGR OF Skware AN Kyoob, O RLY?
YA RLY
VISIBLE SMOOSH Skware " " MKAY !
NotKyoobs R SUM OF NotKyoobs AN 1
OIC
OIC
Index R SUM OF Index AN 1
IM OUTTA YR Outer
VISIBLE ""
VISIBLE ""
VISIBLE "Both skwares and kyoobs::"
IM IN YR Output UPPIN YR Index WILE DIFFRINT Index AN NumbarSkwareKyoobs
VISIBLE SMOOSH SkwareKyoobs'Z SRS Index " " MKAY !
IM OUTTA YR Output
VISIBLE ""
KTHXBYE |
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
| #Run_BASIC | Run BASIC | call sample 100
call sample 1000
call sample 10000
end
sub sample n
dim samp(n)
for i =1 to n
samp(i) =rnd(1)
next i
' calculate mean, standard deviation
sum = 0
sumSq = 0
for i = 1 to n
sum = sum + samp(i)
sumSq = sumSq + samp(i)^2
next i
print n; " Samples used."
mean = sum / n
print "Mean = "; mean
print "Std Dev = "; (sumSq /n -mean^2)^0.5
'------- Show histogram
bins = 10
dim bins(bins)
for i = 1 to n
z = int(bins * samp(i))
bins(z) = bins(z) +1
next i
for b = 0 to bins -1
print b;" ";
for j = 1 to int(bins *bins(b)) /n *70
print "*";
next j
print
next b
print
end sub |
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
| #Rust | Rust | #![feature(iter_arith)]
extern crate rand;
use rand::distributions::{IndependentSample, Range};
pub fn mean(data: &[f32]) -> Option<f32> {
if data.is_empty() {
None
} else {
let sum: f32 = data.iter().sum();
Some(sum / data.len() as f32)
}
}
pub fn variance(data: &[f32]) -> Option<f32> {
if data.is_empty() {
None
} else {
let mean = mean(data).unwrap();
let mut sum = 0f32;
for &x in data {
sum += (x - mean).powi(2);
}
Some(sum / data.len() as f32)
}
}
pub fn standard_deviation(data: &[f32]) -> Option<f32> {
if data.is_empty() {
None
} else {
let variance = variance(data).unwrap();
Some(variance.sqrt())
}
}
fn print_histogram(width: u32, data: &[f32]) {
let mut histogram = [0; 10];
let len = histogram.len() as f32;
for &x in data {
histogram[(x * len) as usize] += 1;
}
let max_frequency = *histogram.iter().max().unwrap() as f32;
for (i, &frequency) in histogram.iter().enumerate() {
let bar_width = frequency as f32 * width as f32 / max_frequency;
print!("{:3.1}: ", i as f32 / len);
for _ in 0..bar_width as usize {
print!("*");
}
println!("");
}
}
fn main() {
let range = Range::new(0f32, 1f32);
let mut rng = rand::thread_rng();
for &number_of_samples in [1000, 10_000, 1_000_000].iter() {
let mut data = vec![];
for _ in 0..number_of_samples {
let x = range.ind_sample(&mut rng);
data.push(x);
}
println!(" Statistics for sample size {}", number_of_samples);
println!("Mean: {:?}", mean(&data));
println!("Variance: {:?}", variance(&data));
println!("Standard deviation: {:?}", standard_deviation(&data));
print_histogram(40, &data);
}
} |
http://rosettacode.org/wiki/Split_a_character_string_based_on_change_of_character | Split a character string based on change of character |
Task
Split a (character) string into comma (plus a blank) delimited
strings based on a change of character (left to right).
Show the output here (use the 1st example below).
Blanks should be treated as any other character (except
they are problematic to display clearly). The same applies
to commas.
For instance, the string:
gHHH5YY++///\
should be split and show:
g, HHH, 5, YY, ++, ///, \
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
| #Java | Java | package org.rosettacode;
import java.util.ArrayList;
import java.util.List;
/**
* This class provides a main method that will, for each arg provided,
* transform a String into a list of sub-strings, where each contiguous
* series of characters is made into a String, then the next, and so on,
* and then it will output them all separated by a comma and a space.
*/
public class SplitStringByCharacterChange {
public static void main(String... args){
for (String string : args){
List<String> resultStrings = splitStringByCharacter(string);
String output = formatList(resultStrings);
System.out.println(output);
}
}
/**
* @param string String - String to split
* @return List<\String> - substrings of contiguous characters
*/
public static List<String> splitStringByCharacter(String string){
List<String> resultStrings = new ArrayList<>();
StringBuilder currentString = new StringBuilder();
for (int pointer = 0; pointer < string.length(); pointer++){
currentString.append(string.charAt(pointer));
if (pointer == string.length() - 1
|| currentString.charAt(0) != string.charAt(pointer + 1)) {
resultStrings.add(currentString.toString());
currentString = new StringBuilder();
}
}
return resultStrings;
}
/**
* @param list List<\String> - list of strings to format as a comma+space-delimited string
* @return String
*/
public static String formatList(List<String> list){
StringBuilder output = new StringBuilder();
for (int pointer = 0; pointer < list.size(); pointer++){
output.append(list.get(pointer));
if (pointer != list.size() - 1){
output.append(", ");
}
}
return output.toString();
}
} |
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.
| #Ring | Ring |
# Project : Stern-Brocot sequence
limit = 1200
item = list(limit+1)
item[1] = 1
item[2] = 1
nr = 2
gcd = 1
gcdall = 1
for num = 3 to limit
item[num] = item[nr] + item[nr-1]
item[num+1] = item[nr]
nr = nr + 1
num = num + 1
next
showarray(item,15)
for x = 1 to 100
if x < 11 or x = 100
totalitem(x)
ok
next
for n = 1 to len(item) - 1
if gcd(item[n],item[n+1]) != 1
gcdall = gcd
ok
next
if gcdall = 1
see "Correct: The first 999 consecutive pairs are relative prime!" + nl
ok
func totalitem(p)
pos = find(item, p)
see string(x) + " at Stern #" + pos + "." + nl
func showarray(vect,ln)
svect = ""
for n = 1 to ln
svect = svect + vect[n] + ", "
next
svect = left(svect, len(svect) - 2)
see svect
see nl
func gcd(gcd,b)
while b
c = gcd
gcd = b
b = c % b
end
return gcd
|
http://rosettacode.org/wiki/Spinning_rod_animation/Text | Spinning rod animation/Text | Task
An animation with the following frames in the following order (if certain characters aren't available or can't be used correctly in the programming language, alternate characters can replace any of these frames) must animate with a delay of 0.25 seconds between each frame, with the previous frame being cleared before the next frame appears:
|
/
- or ─
\
A stand-alone version that loops and/or a version that doesn't loop can be made. These examples can also be converted into a system used in game development which is called on a HUD or GUI element requiring it to be called each frame to output the text, and advance the frame when the frame delay has passed. You can also use alternate text such as the . animation ( . | .. | ... | .. | repeat from . ) or the logic can be updated to include a ping/pong style where the frames advance forward, reach the end and then play backwards and when they reach the beginning they start over ( technically, you'd stop one frame prior to prevent the first frame playing twice, or write it another way ).
There are many different ways you can incorporate text animations. Here are a few text ideas - each frame is in quotes. If you can think of any, add them to this page! There are 2 examples for several of these; the first is the base animation with only unique sets of characters. The second consists of the primary set from a - n and doubled, minus the first and last element ie: We only want the center. This way an animation can play forwards, and then in reverse ( ping ponging ) without having to code that feature. For the animations with 3 elements, we only add 1, the center. with 4, it becomes 6. with 10, it becomes 18.
We don't need the second option for some of the animations if they connect smoothly, when animated, back to the first element. ... doesn't connect with . cleanly - there is a large leap. The rotating pipe meets the first perfectly so it isn't necessary, etc..
Dots - Option A requires ping / pong enabled script. Option B just adds the elements in the center.
'.', '..', '...'
'.', '..', '...', '..'
Pipe - This has the uniform sideways pipe instead of a hyphen to prevent non-uniform sizing.
'|', '/', '─', '\'
Stars - Option A requires ping / pong enabled script. Option B just adds the elements from the center.
'⁎', '⁑', '⁂'
'⁎', '⁑', '⁂', '⁑'
Clock - These need to be ordered. I haven't done this yet as the application I was testing the system in doesn't support these wingdings / icons. But this would look quite nice and you could set it up to go forward, or backward during an undo process, etc..
'🕛', '🕧', '🕐', '🕜', '🕑', '🕝', '🕒', '🕞', '🕓', '🕟', '🕔', '🕠', '🕕', '🕖', '🕗', '🕘', '🕙', '🕚', '🕡', '🕢', '🕣', '🕤', '🕥', '🕦'
Arrows:
'⬍', '⬈', '➞', '⬊', '⬍', '⬋', '⬅', '⬉'
Bird - This looks decent but may be missing something.
'︷', '︵', '︹', '︺', '︶', '︸'
'︷', '︵', '︹', '︺', '︶', '︸', '︶', '︺', '︹', '︵'
Plants - This isn't quite complete
'☘', '❀', '❁'
'☘', '❀', '❁', '❀'
Eclipse - From Raku Throbber post author
'🌑', '🌒', '🌓', '🌔', '🌕', '🌖', '🌗', '🌘'
| #NS-HUBASIC | NS-HUBASIC | 10 DIM A(4)
20 A(1)=236
30 A(2)=234
40 A(3)=235
50 A(4)=233
60 FOR I=1 TO 4
70 CLS
80 PRINT CHR$(A(I))
90 PAUSE 15
100 NEXT
110 GOTO 60 |
http://rosettacode.org/wiki/Spinning_rod_animation/Text | Spinning rod animation/Text | Task
An animation with the following frames in the following order (if certain characters aren't available or can't be used correctly in the programming language, alternate characters can replace any of these frames) must animate with a delay of 0.25 seconds between each frame, with the previous frame being cleared before the next frame appears:
|
/
- or ─
\
A stand-alone version that loops and/or a version that doesn't loop can be made. These examples can also be converted into a system used in game development which is called on a HUD or GUI element requiring it to be called each frame to output the text, and advance the frame when the frame delay has passed. You can also use alternate text such as the . animation ( . | .. | ... | .. | repeat from . ) or the logic can be updated to include a ping/pong style where the frames advance forward, reach the end and then play backwards and when they reach the beginning they start over ( technically, you'd stop one frame prior to prevent the first frame playing twice, or write it another way ).
There are many different ways you can incorporate text animations. Here are a few text ideas - each frame is in quotes. If you can think of any, add them to this page! There are 2 examples for several of these; the first is the base animation with only unique sets of characters. The second consists of the primary set from a - n and doubled, minus the first and last element ie: We only want the center. This way an animation can play forwards, and then in reverse ( ping ponging ) without having to code that feature. For the animations with 3 elements, we only add 1, the center. with 4, it becomes 6. with 10, it becomes 18.
We don't need the second option for some of the animations if they connect smoothly, when animated, back to the first element. ... doesn't connect with . cleanly - there is a large leap. The rotating pipe meets the first perfectly so it isn't necessary, etc..
Dots - Option A requires ping / pong enabled script. Option B just adds the elements in the center.
'.', '..', '...'
'.', '..', '...', '..'
Pipe - This has the uniform sideways pipe instead of a hyphen to prevent non-uniform sizing.
'|', '/', '─', '\'
Stars - Option A requires ping / pong enabled script. Option B just adds the elements from the center.
'⁎', '⁑', '⁂'
'⁎', '⁑', '⁂', '⁑'
Clock - These need to be ordered. I haven't done this yet as the application I was testing the system in doesn't support these wingdings / icons. But this would look quite nice and you could set it up to go forward, or backward during an undo process, etc..
'🕛', '🕧', '🕐', '🕜', '🕑', '🕝', '🕒', '🕞', '🕓', '🕟', '🕔', '🕠', '🕕', '🕖', '🕗', '🕘', '🕙', '🕚', '🕡', '🕢', '🕣', '🕤', '🕥', '🕦'
Arrows:
'⬍', '⬈', '➞', '⬊', '⬍', '⬋', '⬅', '⬉'
Bird - This looks decent but may be missing something.
'︷', '︵', '︹', '︺', '︶', '︸'
'︷', '︵', '︹', '︺', '︶', '︸', '︶', '︺', '︹', '︵'
Plants - This isn't quite complete
'☘', '❀', '❁'
'☘', '❀', '❁', '❀'
Eclipse - From Raku Throbber post author
'🌑', '🌒', '🌓', '🌔', '🌕', '🌖', '🌗', '🌘'
| #Perl | Perl | $|= 1;
while () {
for (qw[ | / - \ ]) {
select undef, undef, undef, 0.25;
printf "\r ($_)";
}
} |
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
| #COBOL | COBOL | 01 stack.
05 head USAGE IS POINTER VALUE NULL.
|
http://rosettacode.org/wiki/Spiral_matrix | Spiral matrix | Task
Produce a spiral array.
A spiral array is a square arrangement of the first N2 natural numbers, where the
numbers increase sequentially as you go around the edges of the array spiraling inwards.
For example, given 5, produce this array:
0 1 2 3 4
15 16 17 18 5
14 23 24 19 6
13 22 21 20 7
12 11 10 9 8
Related tasks
Zig-zag matrix
Identity_matrix
Ulam_spiral_(for_primes)
| #11l | 11l | F spiral_matrix(n)
V m = [[0] * n] *n
V d = [(0, 1), (1, 0), (0, -1), (-1, 0)]
V xy = (0, -1)
V c = 0
L(i) 0 .< n + n - 1
L 0 .< (n + n - i) I/ 2
xy += d[i % 4]
m[xy.x][xy.y] = c
c++
R m
F printspiral(myarray)
L(y) 0 .< myarray.len
L(x) 0 .< myarray.len
print(‘#2’.format(myarray[y][x]), end' ‘ ’)
print()
printspiral(spiral_matrix(5)) |
http://rosettacode.org/wiki/Special_variables | Special variables | Special variables have a predefined meaning within a computer programming language.
Task
List the special variables used within the language.
| #AutoHotkey | AutoHotkey | %CD% - expands to the current directory string.
%DATE% - expands to current date using same format as DATE command.
%TIME% - expands to current time using same format as TIME command.
%RANDOM% - expands to a random decimal number between 0 and 32767.
%ERRORLEVEL% - expands to the current ERRORLEVEL value
%CMDEXTVERSION% - expands to the current Command Processor Extensions
version number.
%CMDCMDLINE% - expands to the original command line that invoked the
Command Processor.
%HIGHESTNUMANODENUMBER% - expands to the highest NUMA node number
on this machine. |
http://rosettacode.org/wiki/Special_variables | Special variables | Special variables have a predefined meaning within a computer programming language.
Task
List the special variables used within the language.
| #AWK | AWK | %CD% - expands to the current directory string.
%DATE% - expands to current date using same format as DATE command.
%TIME% - expands to current time using same format as TIME command.
%RANDOM% - expands to a random decimal number between 0 and 32767.
%ERRORLEVEL% - expands to the current ERRORLEVEL value
%CMDEXTVERSION% - expands to the current Command Processor Extensions
version number.
%CMDCMDLINE% - expands to the original command line that invoked the
Command Processor.
%HIGHESTNUMANODENUMBER% - expands to the highest NUMA node number
on this machine. |
http://rosettacode.org/wiki/Stable_marriage_problem | Stable marriage problem | Solve the Stable marriage problem using the Gale/Shapley algorithm.
Problem description
Given an equal number of men and women to be paired for marriage, each man ranks all the women in order of his preference and each woman ranks all the men in order of her preference.
A stable set of engagements for marriage is one where no man prefers a woman over the one he is engaged to, where that other woman also prefers that man over the one she is engaged to. I.e. with consulting marriages, there would be no reason for the engagements between the people to change.
Gale and Shapley proved that there is a stable set of engagements for any set of preferences and the first link above gives their algorithm for finding a set of stable engagements.
Task Specifics
Given ten males:
abe, bob, col, dan, ed, fred, gav, hal, ian, jon
And ten females:
abi, bea, cath, dee, eve, fay, gay, hope, ivy, jan
And a complete list of ranked preferences, where the most liked is to the left:
abe: abi, eve, cath, ivy, jan, dee, fay, bea, hope, gay
bob: cath, hope, abi, dee, eve, fay, bea, jan, ivy, gay
col: hope, eve, abi, dee, bea, fay, ivy, gay, cath, jan
dan: ivy, fay, dee, gay, hope, eve, jan, bea, cath, abi
ed: jan, dee, bea, cath, fay, eve, abi, ivy, hope, gay
fred: bea, abi, dee, gay, eve, ivy, cath, jan, hope, fay
gav: gay, eve, ivy, bea, cath, abi, dee, hope, jan, fay
hal: abi, eve, hope, fay, ivy, cath, jan, bea, gay, dee
ian: hope, cath, dee, gay, bea, abi, fay, ivy, jan, eve
jon: abi, fay, jan, gay, eve, bea, dee, cath, ivy, hope
abi: bob, fred, jon, gav, ian, abe, dan, ed, col, hal
bea: bob, abe, col, fred, gav, dan, ian, ed, jon, hal
cath: fred, bob, ed, gav, hal, col, ian, abe, dan, jon
dee: fred, jon, col, abe, ian, hal, gav, dan, bob, ed
eve: jon, hal, fred, dan, abe, gav, col, ed, ian, bob
fay: bob, abe, ed, ian, jon, dan, fred, gav, col, hal
gay: jon, gav, hal, fred, bob, abe, col, ed, dan, ian
hope: gav, jon, bob, abe, ian, dan, hal, ed, col, fred
ivy: ian, col, hal, gav, fred, bob, abe, ed, jon, dan
jan: ed, hal, gav, abe, bob, jon, col, ian, fred, dan
Use the Gale Shapley algorithm to find a stable set of engagements
Perturb this set of engagements to form an unstable set of engagements then check this new set for stability.
References
The Stable Marriage Problem. (Eloquent description and background information).
Gale-Shapley Algorithm Demonstration.
Another Gale-Shapley Algorithm Demonstration.
Stable Marriage Problem - Numberphile (Video).
Stable Marriage Problem (the math bit) (Video).
The Stable Marriage Problem and School Choice. (Excellent exposition)
| #BBC_BASIC | BBC BASIC | N = 10
DIM mname$(N), wname$(N), mpref$(N), wpref$(N), mpartner%(N), wpartner%(N)
DIM proposed&(N,N)
mname$() = "", "Abe","Bob","Col","Dan","Ed","Fred","Gav","Hal","Ian","Jon"
wname$() = "", "Abi","Bea","Cath","Dee","Eve","Fay","Gay","Hope","Ivy","Jan"
mpref$() = "", "AECIJDFBHG","CHADEFBJIG","HEADBFIGCJ","IFDGHEJBCA","JDBCFEAIHG",\
\ "BADGEICJHF","GEIBCADHJF","AEHFICJBGD","HCDGBAFIJE","AFJGEBDCIH"
wpref$() = "", "BFJGIADECH","BACFGDIEJH","FBEGHCIADJ","FJCAIHGDBE","JHFDAGCEIB",\
\ "BAEIJDFGCH","JGHFBACEDI","GJBAIDHECF","ICHGFBAEJD","EHGABJCIFD"
REM The Gale-Shapley algorithm:
REPEAT
FOR m% = 1 TO N
REPEAT
IF mpartner%(m%) EXIT REPEAT
FOR i% = 1 TO N
w% = ASCMID$(mpref$(m%),i%) - 64
IF proposed&(m%,w%) = 0 EXIT FOR
NEXT i%
IF i% > N EXIT REPEAT
proposed&(m%,w%) = 1
IF wpartner%(w%) = 0 THEN
mpartner%(m%) = w% : REM Get engaged
wpartner%(w%) = m%
ELSE
o% = wpartner%(w%)
IF INSTR(wpref$(w%), LEFT$(mname$(m%),1)) < \
\ INSTR(wpref$(w%), LEFT$(mname$(o%),1)) THEN
mpartner%(o%) = 0 : REM Split up
mpartner%(m%) = w% : REM Get engaged
wpartner%(w%) = m%
ENDIF
ENDIF
UNTIL TRUE
NEXT m%
UNTIL SUM(mpartner%()) = (N*(N+1))/2
FOR m% = 1 TO N
PRINT mname$(m%) " is engaged to " wname$(mpartner%(m%))
NEXT
PRINT "Relationships are ";
IF FNstable PRINT "stable." ELSE PRINT "unstable."
a% = RND(N)
REPEAT b% = RND(N) : UNTIL b%<>a%
PRINT '"Now swapping " mname$(a%) "'s and " mname$(b%) "'s partners:"
SWAP mpartner%(a%), mpartner%(b%)
PRINT mname$(a%) " is engaged to " wname$(mpartner%(a%))
PRINT mname$(b%) " is engaged to " wname$(mpartner%(b%))
PRINT "Relationships are ";
IF FNstable PRINT "stable." ELSE PRINT "unstable."
END
DEF FNstable
LOCAL m%, w%, o%, p%
FOR m% = 1 TO N
w% = mpartner%(m%)
FOR o% = 1 TO N
p% = wpartner%(o%)
IF INSTR(mpref$(m%), LEFT$(wname$(o%),1)) < \
\ INSTR(mpref$(m%), LEFT$(wname$(w%),1)) AND \
\ INSTR(wpref$(o%), LEFT$(mname$(m%),1)) < \
\ INSTR(wpref$(o%), LEFT$(mname$(p%),1)) THEN
= FALSE
ENDIF
NEXT o%
NEXT m%
= TRUE |
http://rosettacode.org/wiki/Spelling_of_ordinal_numbers | Spelling of ordinal numbers | Ordinal numbers (as used in this Rosetta Code task), are numbers that describe the position of something in a list.
It is this context that ordinal numbers will be used, using an English-spelled name of an ordinal number.
The ordinal numbers are (at least, one form of them):
1st 2nd 3rd 4th 5th 6th 7th ··· 99th 100th ··· 1000000000th ··· etc
sometimes expressed as:
1st 2nd 3rd 4th 5th 6th 7th ··· 99th 100th ··· 1000000000th ···
For this task, the following (English-spelled form) will be used:
first second third fourth fifth sixth seventh ninety-nineth one hundredth one billionth
Furthermore, the American version of numbers will be used here (as opposed to the British).
2,000,000,000 is two billion, not two milliard.
Task
Write a driver and a function (subroutine/routine ···) that returns the English-spelled ordinal version of a specified number (a positive integer).
Optionally, try to support as many forms of an integer that can be expressed: 123 00123.0 1.23e2 all are forms of the same integer.
Show all output here.
Test cases
Use (at least) the test cases of:
1 2 3 4 5 11 65 100 101 272 23456 8007006005004003
Related tasks
Number names
N'th
| #J | J | ord=: {{
((us,suf)1+y) rplc ;:{{)n onest first twond second
threerd third fiveth fifth eightth eighth
}}-.LF
}} |
http://rosettacode.org/wiki/Spelling_of_ordinal_numbers | Spelling of ordinal numbers | Ordinal numbers (as used in this Rosetta Code task), are numbers that describe the position of something in a list.
It is this context that ordinal numbers will be used, using an English-spelled name of an ordinal number.
The ordinal numbers are (at least, one form of them):
1st 2nd 3rd 4th 5th 6th 7th ··· 99th 100th ··· 1000000000th ··· etc
sometimes expressed as:
1st 2nd 3rd 4th 5th 6th 7th ··· 99th 100th ··· 1000000000th ···
For this task, the following (English-spelled form) will be used:
first second third fourth fifth sixth seventh ninety-nineth one hundredth one billionth
Furthermore, the American version of numbers will be used here (as opposed to the British).
2,000,000,000 is two billion, not two milliard.
Task
Write a driver and a function (subroutine/routine ···) that returns the English-spelled ordinal version of a specified number (a positive integer).
Optionally, try to support as many forms of an integer that can be expressed: 123 00123.0 1.23e2 all are forms of the same integer.
Show all output here.
Test cases
Use (at least) the test cases of:
1 2 3 4 5 11 65 100 101 272 23456 8007006005004003
Related tasks
Number names
N'th
| #Java | Java |
import java.util.HashMap;
import java.util.Map;
public class SpellingOfOrdinalNumbers {
public static void main(String[] args) {
for ( long test : new long[] {1, 2, 3, 4, 5, 11, 65, 100, 101, 272, 23456, 8007006005004003L} ) {
System.out.printf("%d = %s%n", test, toOrdinal(test));
}
}
private static Map<String,String> ordinalMap = new HashMap<>();
static {
ordinalMap.put("one", "first");
ordinalMap.put("two", "second");
ordinalMap.put("three", "third");
ordinalMap.put("five", "fifth");
ordinalMap.put("eight", "eighth");
ordinalMap.put("nine", "ninth");
ordinalMap.put("twelve", "twelfth");
}
private static String toOrdinal(long n) {
String spelling = numToString(n);
String[] split = spelling.split(" ");
String last = split[split.length - 1];
String replace = "";
if ( last.contains("-") ) {
String[] lastSplit = last.split("-");
String lastWithDash = lastSplit[1];
String lastReplace = "";
if ( ordinalMap.containsKey(lastWithDash) ) {
lastReplace = ordinalMap.get(lastWithDash);
}
else if ( lastWithDash.endsWith("y") ) {
lastReplace = lastWithDash.substring(0, lastWithDash.length() - 1) + "ieth";
}
else {
lastReplace = lastWithDash + "th";
}
replace = lastSplit[0] + "-" + lastReplace;
}
else {
if ( ordinalMap.containsKey(last) ) {
replace = ordinalMap.get(last);
}
else if ( last.endsWith("y") ) {
replace = last.substring(0, last.length() - 1) + "ieth";
}
else {
replace = last + "th";
}
}
split[split.length - 1] = replace;
return String.join(" ", split);
}
private static final String[] nums = new String[] {
"zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine",
"ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen"
};
private static final String[] tens = new String[] {"zero", "ten", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"};
private static final String numToString(long n) {
return numToStringHelper(n);
}
private static final String numToStringHelper(long n) {
if ( n < 0 ) {
return "negative " + numToStringHelper(-n);
}
int index = (int) n;
if ( n <= 19 ) {
return nums[index];
}
if ( n <= 99 ) {
return tens[index/10] + (n % 10 > 0 ? "-" + numToStringHelper(n % 10) : "");
}
String label = null;
long factor = 0;
if ( n <= 999 ) {
label = "hundred";
factor = 100;
}
else if ( n <= 999999) {
label = "thousand";
factor = 1000;
}
else if ( n <= 999999999) {
label = "million";
factor = 1000000;
}
else if ( n <= 999999999999L) {
label = "billion";
factor = 1000000000;
}
else if ( n <= 999999999999999L) {
label = "trillion";
factor = 1000000000000L;
}
else if ( n <= 999999999999999999L) {
label = "quadrillion";
factor = 1000000000000000L;
}
else {
label = "quintillion";
factor = 1000000000000000000L;
}
return numToStringHelper(n / factor) + " " + label + (n % factor > 0 ? " " + numToStringHelper(n % factor ) : "");
}
}
|
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.
| #Lua | Lua | function nthroot (x, n)
local r = 1
for i = 1, 16 do
r = (((n - 1) * r) + x / (r ^ (n - 1))) / n
end
return r
end
local i, count, sq, cbrt = 0, 0
while count < 30 do
i = i + 1
sq = i * i
-- The next line should say nthroot(sq, 3), right? But this works. Maths, eh?
cbrt = nthroot(i, 3)
if cbrt == math.floor(cbrt) then
print(sq .. " is square and cube")
else
print(sq)
count = count + 1
end
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
| #Scala | Scala | def mean(a:Array[Double])=a.sum / a.size
def stddev(a:Array[Double])={
val sum = a.fold(0.0)((a, b) => a + math.pow(b,2))
math.sqrt((sum/a.size) - math.pow(mean(a),2))
}
def hist(a:Array[Double]) = {
val grouped=(SortedMap[Double, Array[Double]]() ++ (a groupBy (x => math.rint(x*10)/10)))
grouped.map(v => (v._1, v._2.size))
}
def printHist(a:Array[Double])=for((g,v) <- hist(a)){
println(s"$g: ${"*"*(205*v/a.size)} $v")
}
for(n <- Seq(100,1000,10000)){
val a = Array.fill(n)(Random.nextDouble)
println(s"$n numbers")
println(s"Mean: ${mean(a)}")
println(s"StdDev: ${stddev(a)}")
printHist(a)
println
} |
http://rosettacode.org/wiki/Split_a_character_string_based_on_change_of_character | Split a character string based on change of character |
Task
Split a (character) string into comma (plus a blank) delimited
strings based on a change of character (left to right).
Show the output here (use the 1st example below).
Blanks should be treated as any other character (except
they are problematic to display clearly). The same applies
to commas.
For instance, the string:
gHHH5YY++///\
should be split and show:
g, HHH, 5, YY, ++, ///, \
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
| #JavaScript | JavaScript | (() => {
"use strict";
// ----------- SPLIT ON CHARACTER CHANGES ------------
const main = () =>
group("gHHH5YY++///\\")
.map(x => x.join(""))
.join(", ");
// --------------------- GENERIC ---------------------
// group :: [a] -> [[a]]
const group = xs =>
// A list of lists, each containing only
// elements equal under (===), such that the
// concatenation of these lists is xs.
groupBy(a => b => a === b)(xs);
// groupBy :: (a -> a -> Bool) [a] -> [[a]]
const groupBy = eqOp =>
// A list of lists, each containing only elements
// equal under the given equality operator,
// such that the concatenation of these lists is xs.
xs => 0 < xs.length ? (() => {
const [h, ...t] = xs;
const [groups, g] = t.reduce(
([gs, a], x) => eqOp(x)(a[0]) ? (
Tuple(gs)([...a, x])
) : Tuple([...gs, a])([x]),
Tuple([])([h])
);
return [...groups, g];
})() : [];
// Tuple (,) :: a -> b -> (a, b)
const Tuple = a =>
b => ({
type: "Tuple",
"0": a,
"1": b,
length: 2,
*[Symbol.iterator]() {
for (const k in this) {
if (!isNaN(k)) {
yield this[k];
}
}
}
});
// MAIN ---
return main();
})(); |
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.
| #Ruby | Ruby | def sb
return enum_for :sb unless block_given?
a=[1,1]
0.step do |i|
yield a[i]
a << a[i]+a[i+1] << a[i+1]
end
end
puts "First 15: #{sb.first(15)}"
[*1..10,100].each do |n|
puts "#{n} first appears at #{sb.find_index(n)+1}."
end
if sb.take(1000).each_cons(2).all? { |a,b| a.gcd(b) == 1 }
puts "All GCD's are 1"
else
puts "Whoops, not all GCD's are 1!"
end |
http://rosettacode.org/wiki/Spinning_rod_animation/Text | Spinning rod animation/Text | Task
An animation with the following frames in the following order (if certain characters aren't available or can't be used correctly in the programming language, alternate characters can replace any of these frames) must animate with a delay of 0.25 seconds between each frame, with the previous frame being cleared before the next frame appears:
|
/
- or ─
\
A stand-alone version that loops and/or a version that doesn't loop can be made. These examples can also be converted into a system used in game development which is called on a HUD or GUI element requiring it to be called each frame to output the text, and advance the frame when the frame delay has passed. You can also use alternate text such as the . animation ( . | .. | ... | .. | repeat from . ) or the logic can be updated to include a ping/pong style where the frames advance forward, reach the end and then play backwards and when they reach the beginning they start over ( technically, you'd stop one frame prior to prevent the first frame playing twice, or write it another way ).
There are many different ways you can incorporate text animations. Here are a few text ideas - each frame is in quotes. If you can think of any, add them to this page! There are 2 examples for several of these; the first is the base animation with only unique sets of characters. The second consists of the primary set from a - n and doubled, minus the first and last element ie: We only want the center. This way an animation can play forwards, and then in reverse ( ping ponging ) without having to code that feature. For the animations with 3 elements, we only add 1, the center. with 4, it becomes 6. with 10, it becomes 18.
We don't need the second option for some of the animations if they connect smoothly, when animated, back to the first element. ... doesn't connect with . cleanly - there is a large leap. The rotating pipe meets the first perfectly so it isn't necessary, etc..
Dots - Option A requires ping / pong enabled script. Option B just adds the elements in the center.
'.', '..', '...'
'.', '..', '...', '..'
Pipe - This has the uniform sideways pipe instead of a hyphen to prevent non-uniform sizing.
'|', '/', '─', '\'
Stars - Option A requires ping / pong enabled script. Option B just adds the elements from the center.
'⁎', '⁑', '⁂'
'⁎', '⁑', '⁂', '⁑'
Clock - These need to be ordered. I haven't done this yet as the application I was testing the system in doesn't support these wingdings / icons. But this would look quite nice and you could set it up to go forward, or backward during an undo process, etc..
'🕛', '🕧', '🕐', '🕜', '🕑', '🕝', '🕒', '🕞', '🕓', '🕟', '🕔', '🕠', '🕕', '🕖', '🕗', '🕘', '🕙', '🕚', '🕡', '🕢', '🕣', '🕤', '🕥', '🕦'
Arrows:
'⬍', '⬈', '➞', '⬊', '⬍', '⬋', '⬅', '⬉'
Bird - This looks decent but may be missing something.
'︷', '︵', '︹', '︺', '︶', '︸'
'︷', '︵', '︹', '︺', '︶', '︸', '︶', '︺', '︹', '︵'
Plants - This isn't quite complete
'☘', '❀', '❁'
'☘', '❀', '❁', '❀'
Eclipse - From Raku Throbber post author
'🌑', '🌒', '🌓', '🌔', '🌕', '🌖', '🌗', '🌘'
| #Phix | Phix | without js -- (cursor, sleep)
puts(1,"please_wait... ")
cursor(NO_CURSOR)
for i=1 to 10 do -- (approx 10 seconds)
for j=1 to 4 do
printf(1," \b%c\b",`|/-\`[j])
sleep(0.25)
end for
end for
puts(1," \ndone") -- clear rod, "done" on next line
|
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
| #CoffeeScript | CoffeeScript | stack = []
stack.push 1
stack.push 2
console.log stack
console.log stack.pop()
console.log stack |
http://rosettacode.org/wiki/Spiral_matrix | Spiral matrix | Task
Produce a spiral array.
A spiral array is a square arrangement of the first N2 natural numbers, where the
numbers increase sequentially as you go around the edges of the array spiraling inwards.
For example, given 5, produce this array:
0 1 2 3 4
15 16 17 18 5
14 23 24 19 6
13 22 21 20 7
12 11 10 9 8
Related tasks
Zig-zag matrix
Identity_matrix
Ulam_spiral_(for_primes)
| #360_Assembly | 360 Assembly | SPIRALM CSECT
USING SPIRALM,R13
SAVEAREA B STM-SAVEAREA(R15)
DC 17F'0'
DC CL8'SPIRALM'
STM STM R14,R12,12(R13)
ST R13,4(R15)
ST R15,8(R13)
LR R13,R15
* ---- CODE
LA R0,0
LA R1,1
LH R12,N n
LR R4,R1 Row=1
LR R5,R1 Col=1
LR R6,R1 BotRow=1
LR R7,R1 BotCol=1
LR R8,R12 TopRow=n
LR R9,R12 TopCol=n
LR R10,R0 Dir=0
LR R15,R12 n
MR R14,R12 R15=n*n
LA R11,1 k=1
LOOP CR R11,R15
BH ENDLOOP
LR R1,R4
BCTR R1,0
MH R1,N
AR R1,R5
LR R2,R11 k
BCTR R2,0
BCTR R1,0
SLA R1,1
STH R2,MATRIX(R1) Matrix(Row,Col)=k-1
CH R10,=H'0'
BE DIR0
CH R10,=H'1'
BE DIR1
CH R10,=H'2'
BE DIR2
CH R10,=H'3'
BE DIR3
B DIRX
DIR0 CR R5,R9 if Col<TopCol
BNL DIR0S
LA R5,1(R5) Col=Col+1
B DIRX
DIR0S LA R10,1 Dir=1
LA R4,1(R4) Row=Row+1
LA R6,1(R6) BotRow=BotRow+1
B DIRX
DIR1 CR R4,R8 if Row<TopRow
BNL DIR1S
LA R4,1(R4) Row=Row+1
B DIRX
DIR1S LA R10,2 Dir=2
BCTR R5,0 Col=Col-1
BCTR R9,0 TopCol=TopCol-1
B DIRX
DIR2 CR R5,R7 if Col>BotCol
BNH DIR2S
BCTR R5,0 Col=Col-1
B DIRX
DIR2S LA R10,3 Dir=3
BCTR R4,0 Row=Row-1
BCTR R8,0 TopRow=TopRow-1
B DIRX
DIR3 CR R4,R6 if Row>BotRow
BNH DIR3S
BCTR R4,0 Row=Row-1
B DIRX
DIR3S LA R10,0 Dir=0
LA R5,1(R5) Col=Col+1
LA R7,1(R7) BotCol=BotCol+1
DIRX EQU *
LA R11,1(R11) k=k+1
B LOOP
ENDLOOP EQU *
LA R4,1 i
LOOPI CR R4,R12
BH ENDLOOPI
XR R10,R10
LA R5,1 j
LOOPJ CR R5,R12
BH ENDLOOPJ
LR R1,R4
BCTR R1,0
MH R1,N
AR R1,R5
BCTR R1,0
SLA R1,1
LH R2,MATRIX(R1) Matrix(i,j)
LA R3,BUF
AR R3,R10
CVD R2,P8
MVC 0(4,R3),=X'40202120'
ED 0(4,R3),P8+6
LA R10,4(R10)
LA R5,1(R5)
B LOOPJ
ENDLOOPJ EQU *
WTO MF=(E,WTOMSG)
LA R4,1(R4)
B LOOPI
ENDLOOPI EQU *
* ---- END CODE
L R13,4(0,R13)
LM R14,R12,12(R13)
XR R15,R15
BR R14
* ---- DATA
N DC H'5' max=20 (20*4=80)
LTORG
P8 DS PL8
WTOMSG DS 0F
DC H'80',XL2'0000'
BUF DC CL80' '
MATRIX DS H Matrix(n,n)
YREGS
END SPIRALM |
http://rosettacode.org/wiki/Special_variables | Special variables | Special variables have a predefined meaning within a computer programming language.
Task
List the special variables used within the language.
| #Batch_File | Batch File | %CD% - expands to the current directory string.
%DATE% - expands to current date using same format as DATE command.
%TIME% - expands to current time using same format as TIME command.
%RANDOM% - expands to a random decimal number between 0 and 32767.
%ERRORLEVEL% - expands to the current ERRORLEVEL value
%CMDEXTVERSION% - expands to the current Command Processor Extensions
version number.
%CMDCMDLINE% - expands to the original command line that invoked the
Command Processor.
%HIGHESTNUMANODENUMBER% - expands to the highest NUMA node number
on this machine. |
http://rosettacode.org/wiki/Special_variables | Special variables | Special variables have a predefined meaning within a computer programming language.
Task
List the special variables used within the language.
| #BBC_BASIC | BBC BASIC | @% The number output format control variable
@cmd$ The command line of a 'compiled' program
@dir$ The directory (folder) from which the program was loaded
@flags% An integer incorporating BBC BASIC's control flags
@hcsr% The handle of the mouse pointer (cursor)
@haccel% The handle of the keyboard accelerator, if used
@hevent% The handle of the event used to prevent blocking in serial I/O
@hfile%() An array of file handles indexed by channel number
@hmdi% The Multiple Document Interface window handle (if any)
@hwacc% The window handle to which keyboard accelerator commands should be sent
@hwnd% The 'window handle' for the main (output) window
@hwo% The handle of the WAVEOUTPUT device
@hpal% The handle for the colour palette
@ispal% A Boolean which is non-zero if the display is paletted
@lib$ The directory (folder) containing the library files
@lparam% The LPARAM value (for use with ON MOUSE, ON MOVE and ON SYS)
@memhdc% The 'device context' for the main (output) window
@midi% The MIDI device ID (non-zero if a MIDI file is playing)
@msg% The MSG value (for use with ON MOUSE, ON MOVE and ON SYS)
@ox% The horizontal offset (in pixels) between the output bitmap and the window contents
@oy% The vertical offset (in pixels) between the output bitmap and the window contents
@prthdc% The 'device context' for the current printer (if any)
@tmp$ The temporary directory (folder)
@usr$ The user's Documents directory (folder)
@vdu% A pointer to the text and graphics parameters
@vdu{} A structure containing the main text and graphics variables
@wparam% The WPARAM value (for use with ON MOUSE, ON MOVE and ON SYS)
|
http://rosettacode.org/wiki/Stable_marriage_problem | Stable marriage problem | Solve the Stable marriage problem using the Gale/Shapley algorithm.
Problem description
Given an equal number of men and women to be paired for marriage, each man ranks all the women in order of his preference and each woman ranks all the men in order of her preference.
A stable set of engagements for marriage is one where no man prefers a woman over the one he is engaged to, where that other woman also prefers that man over the one she is engaged to. I.e. with consulting marriages, there would be no reason for the engagements between the people to change.
Gale and Shapley proved that there is a stable set of engagements for any set of preferences and the first link above gives their algorithm for finding a set of stable engagements.
Task Specifics
Given ten males:
abe, bob, col, dan, ed, fred, gav, hal, ian, jon
And ten females:
abi, bea, cath, dee, eve, fay, gay, hope, ivy, jan
And a complete list of ranked preferences, where the most liked is to the left:
abe: abi, eve, cath, ivy, jan, dee, fay, bea, hope, gay
bob: cath, hope, abi, dee, eve, fay, bea, jan, ivy, gay
col: hope, eve, abi, dee, bea, fay, ivy, gay, cath, jan
dan: ivy, fay, dee, gay, hope, eve, jan, bea, cath, abi
ed: jan, dee, bea, cath, fay, eve, abi, ivy, hope, gay
fred: bea, abi, dee, gay, eve, ivy, cath, jan, hope, fay
gav: gay, eve, ivy, bea, cath, abi, dee, hope, jan, fay
hal: abi, eve, hope, fay, ivy, cath, jan, bea, gay, dee
ian: hope, cath, dee, gay, bea, abi, fay, ivy, jan, eve
jon: abi, fay, jan, gay, eve, bea, dee, cath, ivy, hope
abi: bob, fred, jon, gav, ian, abe, dan, ed, col, hal
bea: bob, abe, col, fred, gav, dan, ian, ed, jon, hal
cath: fred, bob, ed, gav, hal, col, ian, abe, dan, jon
dee: fred, jon, col, abe, ian, hal, gav, dan, bob, ed
eve: jon, hal, fred, dan, abe, gav, col, ed, ian, bob
fay: bob, abe, ed, ian, jon, dan, fred, gav, col, hal
gay: jon, gav, hal, fred, bob, abe, col, ed, dan, ian
hope: gav, jon, bob, abe, ian, dan, hal, ed, col, fred
ivy: ian, col, hal, gav, fred, bob, abe, ed, jon, dan
jan: ed, hal, gav, abe, bob, jon, col, ian, fred, dan
Use the Gale Shapley algorithm to find a stable set of engagements
Perturb this set of engagements to form an unstable set of engagements then check this new set for stability.
References
The Stable Marriage Problem. (Eloquent description and background information).
Gale-Shapley Algorithm Demonstration.
Another Gale-Shapley Algorithm Demonstration.
Stable Marriage Problem - Numberphile (Video).
Stable Marriage Problem (the math bit) (Video).
The Stable Marriage Problem and School Choice. (Excellent exposition)
| #Bracmat | Bracmat | ( (abe.abi eve cath ivy jan dee fay bea hope gay)
(bob.cath hope abi dee eve fay bea jan ivy gay)
(col.hope eve abi dee bea fay ivy gay cath jan)
(dan.ivy fay dee gay hope eve jan bea cath abi)
(ed.jan dee bea cath fay eve abi ivy hope gay)
(fred.bea abi dee gay eve ivy cath jan hope fay)
(gav.gay eve ivy bea cath abi dee hope jan fay)
(hal.abi eve hope fay ivy cath jan bea gay dee)
(ian.hope cath dee gay bea abi fay ivy jan eve)
(jon.abi fay jan gay eve bea dee cath ivy hope)
: ?Mplan
: ?M
& (abi.bob fred jon gav ian abe dan ed col hal)
(bea.bob abe col fred gav dan ian ed jon hal)
(cath.fred bob ed gav hal col ian abe dan jon)
(dee.fred jon col abe ian hal gav dan bob ed)
(eve.jon hal fred dan abe gav col ed ian bob)
(fay.bob abe ed ian jon dan fred gav col hal)
(gay.jon gav hal fred bob abe col ed dan ian)
(hope.gav jon bob abe ian dan hal ed col fred)
(ivy.ian col hal gav fred bob abe ed jon dan)
(jan.ed hal gav abe bob jon col ian fred dan)
: ?W
& :?engaged
& whl
' ( !Mplan
: ?A
(?m&~(!engaged:? (!m.?) ?).%?w ?ws)
( ?Z
& ( ( ~(!engaged:?a (?m`.!w) ?z)
& (!m.!w) !engaged
| !W:? (!w.? !m ? !m` ?) ?
& !a (!m.!w) !z
)
: ?engaged
|
)
& !Z !A (!m.!ws):?Mplan
)
)
& ( unstable
= m1 m2 w1 w2
. !arg
: ?
(?m1.?w1)
?
(?m2.?w2)
( ?
& ( !M:? (!m1.? !w2 ? !w1 ?) ?
& !W:? (!w2.? !m1 ? !m2 ?) ?
| !M:? (!m2.? !w1 ? !w2 ?) ?
& !W:? (!w1.? !m2 ? !m1 ?) ?
)
)
)
& ( unstable$!engaged&out$unstable
| out$stable
)
& out$!engaged
& !engaged:(?m1.?w1) (?m2.?w2) ?others
& out$(swap !w1 for !w2)
& ( unstable$((!m1.!w2) (!m2.!w1) !others)
& out$unstable
| out$stable
)
); |
http://rosettacode.org/wiki/Spelling_of_ordinal_numbers | Spelling of ordinal numbers | Ordinal numbers (as used in this Rosetta Code task), are numbers that describe the position of something in a list.
It is this context that ordinal numbers will be used, using an English-spelled name of an ordinal number.
The ordinal numbers are (at least, one form of them):
1st 2nd 3rd 4th 5th 6th 7th ··· 99th 100th ··· 1000000000th ··· etc
sometimes expressed as:
1st 2nd 3rd 4th 5th 6th 7th ··· 99th 100th ··· 1000000000th ···
For this task, the following (English-spelled form) will be used:
first second third fourth fifth sixth seventh ninety-nineth one hundredth one billionth
Furthermore, the American version of numbers will be used here (as opposed to the British).
2,000,000,000 is two billion, not two milliard.
Task
Write a driver and a function (subroutine/routine ···) that returns the English-spelled ordinal version of a specified number (a positive integer).
Optionally, try to support as many forms of an integer that can be expressed: 123 00123.0 1.23e2 all are forms of the same integer.
Show all output here.
Test cases
Use (at least) the test cases of:
1 2 3 4 5 11 65 100 101 272 23456 8007006005004003
Related tasks
Number names
N'th
| #Julia | Julia |
const irregular = Dict("one" => "first", "two" => "second", "three" => "third", "five" => "fifth",
"eight" => "eighth", "nine" => "ninth", "twelve" => "twelfth")
const suffix = "th"
const ysuffix = "ieth"
function numtext2ordinal(s)
lastword = split(s)[end]
redolast = split(lastword, "-")[end]
if redolast != lastword
lastsplit = "-"
word = redolast
else
lastsplit = " "
word = lastword
end
firstpart = reverse(split(reverse(s), lastsplit, limit=2)[end])
firstpart = (firstpart == word) ? "": firstpart * lastsplit
if haskey(irregular, word)
word = irregular[word]
elseif word[end] == 'y'
word = word[1:end-1] * ysuffix
else
word = word * suffix
end
firstpart * word
end
const testcases = [1 2 3 4 5 11 65 100 101 272 23456 8007006005004003]
for n in testcases
println("$n => $(numtext2ordinal(num2text(n)))")
end
|
http://rosettacode.org/wiki/Spelling_of_ordinal_numbers | Spelling of ordinal numbers | Ordinal numbers (as used in this Rosetta Code task), are numbers that describe the position of something in a list.
It is this context that ordinal numbers will be used, using an English-spelled name of an ordinal number.
The ordinal numbers are (at least, one form of them):
1st 2nd 3rd 4th 5th 6th 7th ··· 99th 100th ··· 1000000000th ··· etc
sometimes expressed as:
1st 2nd 3rd 4th 5th 6th 7th ··· 99th 100th ··· 1000000000th ···
For this task, the following (English-spelled form) will be used:
first second third fourth fifth sixth seventh ninety-nineth one hundredth one billionth
Furthermore, the American version of numbers will be used here (as opposed to the British).
2,000,000,000 is two billion, not two milliard.
Task
Write a driver and a function (subroutine/routine ···) that returns the English-spelled ordinal version of a specified number (a positive integer).
Optionally, try to support as many forms of an integer that can be expressed: 123 00123.0 1.23e2 all are forms of the same integer.
Show all output here.
Test cases
Use (at least) the test cases of:
1 2 3 4 5 11 65 100 101 272 23456 8007006005004003
Related tasks
Number names
N'th
| #Kotlin | Kotlin | // version 1.1.4-3
typealias IAE = IllegalArgumentException
val names = mapOf(
1 to "one",
2 to "two",
3 to "three",
4 to "four",
5 to "five",
6 to "six",
7 to "seven",
8 to "eight",
9 to "nine",
10 to "ten",
11 to "eleven",
12 to "twelve",
13 to "thirteen",
14 to "fourteen",
15 to "fifteen",
16 to "sixteen",
17 to "seventeen",
18 to "eighteen",
19 to "nineteen",
20 to "twenty",
30 to "thirty",
40 to "forty",
50 to "fifty",
60 to "sixty",
70 to "seventy",
80 to "eighty",
90 to "ninety"
)
val bigNames = mapOf(
1_000L to "thousand",
1_000_000L to "million",
1_000_000_000L to "billion",
1_000_000_000_000L to "trillion",
1_000_000_000_000_000L to "quadrillion",
1_000_000_000_000_000_000L to "quintillion"
)
val irregOrdinals = mapOf(
"one" to "first",
"two" to "second",
"three" to "third",
"five" to "fifth",
"eight" to "eighth",
"nine" to "ninth",
"twelve" to "twelfth"
)
fun String.toOrdinal(): String {
val splits = this.split(' ', '-')
var last = splits[splits.lastIndex]
return if (irregOrdinals.containsKey(last)) this.dropLast(last.length) + irregOrdinals[last]!!
else if (last.endsWith("y")) this.dropLast(1) + "ieth"
else this + "th"
}
fun numToOrdinalText(n: Long, uk: Boolean = false): String {
if (n == 0L) return "zeroth" // or alternatively 'zeroeth'
val neg = n < 0L
val maxNeg = n == Long.MIN_VALUE
var nn = if (maxNeg) -(n + 1) else if (neg) -n else n
val digits3 = IntArray(7)
for (i in 0..6) { // split number into groups of 3 digits from the right
digits3[i] = (nn % 1000).toInt()
nn /= 1000
}
fun threeDigitsToText(number: Int) : String {
val sb = StringBuilder()
if (number == 0) return ""
val hundreds = number / 100
val remainder = number % 100
if (hundreds > 0) {
sb.append(names[hundreds], " hundred")
if (remainder > 0) sb.append(if (uk) " and " else " ")
}
if (remainder > 0) {
val tens = remainder / 10
val units = remainder % 10
if (tens > 1) {
sb.append(names[tens * 10])
if (units > 0) sb.append("-", names[units])
}
else sb.append(names[remainder])
}
return sb.toString()
}
val strings = Array<String>(7) { threeDigitsToText(digits3[it]) }
var text = strings[0]
var andNeeded = uk && digits3[0] in 1..99
var big = 1000L
for (i in 1..6) {
if (digits3[i] > 0) {
var text2 = strings[i] + " " + bigNames[big]
if (text.length > 0) {
text2 += if (andNeeded) " and " else ", "
andNeeded = false
}
else andNeeded = uk && digits3[i] in 1..99
text = text2 + text
}
big *= 1000
}
if (maxNeg) text = text.dropLast(5) + "eight"
if (neg) text = "minus " + text
return text.toOrdinal()
}
fun numToOrdinalText(s: String, uk: Boolean = false): String {
val d = s.toDoubleOrNull() ?: throw IAE("String is not numeric")
if (d !in Long.MIN_VALUE.toDouble() .. Long.MAX_VALUE.toDouble())
throw IAE("Double is outside the range of a Long Integer")
val n = d.toLong()
if (n.toDouble() != d) throw IAE("String does not represent a Long Integer")
return numToOrdinalText(n, uk)
}
fun main(args: Array<String>) {
val la = longArrayOf(1, 2, 3, 4, 5, 11, 65, 100, 101, 272, 23456, 8007006005004003)
println("Using US representation:")
for (i in la) println("${"%16d".format(i)} = ${numToOrdinalText(i)}")
val sa = arrayOf("123", "00123.0", "1.23e2")
for (s in sa) println("${"%16s".format(s)} = ${numToOrdinalText(s)}")
} |
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.
| #MAD | MAD | NORMAL MODE IS INTEGER
CUBE=1
NCUBE=1
SQR=1
NSQR=1
SEEN=0
SQRLP SQR = NSQR*NSQR
CUBELP WHENEVER SQR.G.CUBE
NCUBE = NCUBE+1
CUBE = NCUBE*NCUBE*NCUBE
TRANSFER TO CUBELP
END OF CONDITIONAL
WHENEVER SQR.NE.CUBE
SEEN = SEEN+1
PRINT FORMAT FMT,SQR
END OF CONDITIONAL
NSQR = NSQR+1
WHENEVER SEEN.L.30, TRANSFER TO SQRLP
VECTOR VALUES FMT = $I4*$
END OF PROGRAM |
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.
| #Mathematica_.2F_Wolfram_Language | Mathematica / Wolfram Language | s = Range[50]^2;
c = Range[1, Ceiling[Surd[Max[s], 3]]]^3;
Take[Complement[s, c], 30]
Intersection[s, c] |
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
| #Sidef | Sidef | func generate_statistics(n) {
var(sum=0, sum2=0);
var hist = 10.of(0);
n.times {
var r = 1.rand;
sum += r;
sum2 += r**2;
hist[10*r] += 1;
}
var mean = sum/n;
var stddev = Math.sqrt(sum2/n - mean**2);
say "size: #{n}";
say "mean: #{mean}";
say "stddev: #{stddev}";
var max = hist.max;
hist.range.each {|i|
printf("%.1f:%s\n", 0.1*i, "=" * 70*hist[i]/max);
}
print "\n";
}
[100, 1000, 10000].each {|n| generate_statistics(n) } |
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
| #Stata | Stata | . clear all
. set obs 100000
number of observations (_N) was 0, now 100,000
. gen x=runiform()
. summarize x
Variable | Obs Mean Std. Dev. Min Max
-------------+---------------------------------------------------------
x | 100,000 .4991874 .2885253 1.18e-06 .9999939
. hist x |
http://rosettacode.org/wiki/Split_a_character_string_based_on_change_of_character | Split a character string based on change of character |
Task
Split a (character) string into comma (plus a blank) delimited
strings based on a change of character (left to right).
Show the output here (use the 1st example below).
Blanks should be treated as any other character (except
they are problematic to display clearly). The same applies
to commas.
For instance, the string:
gHHH5YY++///\
should be split and show:
g, HHH, 5, YY, ++, ///, \
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
| #jq | jq | # input: a string
# output: a stream of runs
def runs:
def init:
explode as $s
| $s[0] as $i
| (1 | until( $s[.] != $i; .+1));
if length == 0 then empty
elif length == 1 then .
else init as $n | .[0:$n], (.[$n:] | runs)
end;
"gHHH5YY++///\\" | [runs] | join(", ") |
http://rosettacode.org/wiki/Split_a_character_string_based_on_change_of_character | Split a character string based on change of character |
Task
Split a (character) string into comma (plus a blank) delimited
strings based on a change of character (left to right).
Show the output here (use the 1st example below).
Blanks should be treated as any other character (except
they are problematic to display clearly). The same applies
to commas.
For instance, the string:
gHHH5YY++///\
should be split and show:
g, HHH, 5, YY, ++, ///, \
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
| #Jsish | Jsish | #!/usr/bin/env jsish
;'Split a string based on change of character, in Jsish';
function splitOnChange(str:string):string {
if (str.length < 2) return str;
var last = str[0];
var result = last;
for (var pos = 1; pos < str.length; pos++) {
result += ((last == str[pos]) ? last : ', ' + str[pos]);
last = str[pos];
}
return result;
}
provide('splitOnChange', 1.0);
/* literal backslash needs escaping during initial processing */
;splitOnChange('gHHH5YY++///\\');
;splitOnChange('a');
;splitOnChange('ab');
;splitOnChange('aaa');
;splitOnChange('aaaba');
;splitOnChange('gH HH5YY++//,/\\'); |
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.
| #Scala | Scala | lazy val sbSeq: Stream[BigInt] = {
BigInt("1") #::
BigInt("1") #::
(sbSeq zip sbSeq.tail zip sbSeq.tail).
flatMap{ case ((a,b),c) => List(a+b,c) }
}
// Show the results
{
println( s"First 15 members: ${(for( n <- 0 until 15 ) yield sbSeq(n)) mkString( "," )}" )
println
for( n <- 1 to 10; pos = sbSeq.indexOf(n) + 1 ) println( s"Position of first $n is at $pos" )
println
println( s"Position of first 100 is at ${sbSeq.indexOf(100) + 1}" )
println
println( s"Greatest Common Divisor for first 1000 members is 1: " +
(sbSeq zip sbSeq.tail).take(1000).forall{ case (a,b) => a.gcd(b) == 1 } )
}
|
http://rosettacode.org/wiki/Spinning_rod_animation/Text | Spinning rod animation/Text | Task
An animation with the following frames in the following order (if certain characters aren't available or can't be used correctly in the programming language, alternate characters can replace any of these frames) must animate with a delay of 0.25 seconds between each frame, with the previous frame being cleared before the next frame appears:
|
/
- or ─
\
A stand-alone version that loops and/or a version that doesn't loop can be made. These examples can also be converted into a system used in game development which is called on a HUD or GUI element requiring it to be called each frame to output the text, and advance the frame when the frame delay has passed. You can also use alternate text such as the . animation ( . | .. | ... | .. | repeat from . ) or the logic can be updated to include a ping/pong style where the frames advance forward, reach the end and then play backwards and when they reach the beginning they start over ( technically, you'd stop one frame prior to prevent the first frame playing twice, or write it another way ).
There are many different ways you can incorporate text animations. Here are a few text ideas - each frame is in quotes. If you can think of any, add them to this page! There are 2 examples for several of these; the first is the base animation with only unique sets of characters. The second consists of the primary set from a - n and doubled, minus the first and last element ie: We only want the center. This way an animation can play forwards, and then in reverse ( ping ponging ) without having to code that feature. For the animations with 3 elements, we only add 1, the center. with 4, it becomes 6. with 10, it becomes 18.
We don't need the second option for some of the animations if they connect smoothly, when animated, back to the first element. ... doesn't connect with . cleanly - there is a large leap. The rotating pipe meets the first perfectly so it isn't necessary, etc..
Dots - Option A requires ping / pong enabled script. Option B just adds the elements in the center.
'.', '..', '...'
'.', '..', '...', '..'
Pipe - This has the uniform sideways pipe instead of a hyphen to prevent non-uniform sizing.
'|', '/', '─', '\'
Stars - Option A requires ping / pong enabled script. Option B just adds the elements from the center.
'⁎', '⁑', '⁂'
'⁎', '⁑', '⁂', '⁑'
Clock - These need to be ordered. I haven't done this yet as the application I was testing the system in doesn't support these wingdings / icons. But this would look quite nice and you could set it up to go forward, or backward during an undo process, etc..
'🕛', '🕧', '🕐', '🕜', '🕑', '🕝', '🕒', '🕞', '🕓', '🕟', '🕔', '🕠', '🕕', '🕖', '🕗', '🕘', '🕙', '🕚', '🕡', '🕢', '🕣', '🕤', '🕥', '🕦'
Arrows:
'⬍', '⬈', '➞', '⬊', '⬍', '⬋', '⬅', '⬉'
Bird - This looks decent but may be missing something.
'︷', '︵', '︹', '︺', '︶', '︸'
'︷', '︵', '︹', '︺', '︶', '︸', '︶', '︺', '︹', '︵'
Plants - This isn't quite complete
'☘', '❀', '❁'
'☘', '❀', '❁', '❀'
Eclipse - From Raku Throbber post author
'🌑', '🌒', '🌓', '🌔', '🌕', '🌖', '🌗', '🌘'
| #PicoLisp | PicoLisp |
(de rod ()
(until ()
(for R '(\\ | - /)
(prin R (wait 250) "\r")(flush) ) ) )
(rod)
|
http://rosettacode.org/wiki/Spinning_rod_animation/Text | Spinning rod animation/Text | Task
An animation with the following frames in the following order (if certain characters aren't available or can't be used correctly in the programming language, alternate characters can replace any of these frames) must animate with a delay of 0.25 seconds between each frame, with the previous frame being cleared before the next frame appears:
|
/
- or ─
\
A stand-alone version that loops and/or a version that doesn't loop can be made. These examples can also be converted into a system used in game development which is called on a HUD or GUI element requiring it to be called each frame to output the text, and advance the frame when the frame delay has passed. You can also use alternate text such as the . animation ( . | .. | ... | .. | repeat from . ) or the logic can be updated to include a ping/pong style where the frames advance forward, reach the end and then play backwards and when they reach the beginning they start over ( technically, you'd stop one frame prior to prevent the first frame playing twice, or write it another way ).
There are many different ways you can incorporate text animations. Here are a few text ideas - each frame is in quotes. If you can think of any, add them to this page! There are 2 examples for several of these; the first is the base animation with only unique sets of characters. The second consists of the primary set from a - n and doubled, minus the first and last element ie: We only want the center. This way an animation can play forwards, and then in reverse ( ping ponging ) without having to code that feature. For the animations with 3 elements, we only add 1, the center. with 4, it becomes 6. with 10, it becomes 18.
We don't need the second option for some of the animations if they connect smoothly, when animated, back to the first element. ... doesn't connect with . cleanly - there is a large leap. The rotating pipe meets the first perfectly so it isn't necessary, etc..
Dots - Option A requires ping / pong enabled script. Option B just adds the elements in the center.
'.', '..', '...'
'.', '..', '...', '..'
Pipe - This has the uniform sideways pipe instead of a hyphen to prevent non-uniform sizing.
'|', '/', '─', '\'
Stars - Option A requires ping / pong enabled script. Option B just adds the elements from the center.
'⁎', '⁑', '⁂'
'⁎', '⁑', '⁂', '⁑'
Clock - These need to be ordered. I haven't done this yet as the application I was testing the system in doesn't support these wingdings / icons. But this would look quite nice and you could set it up to go forward, or backward during an undo process, etc..
'🕛', '🕧', '🕐', '🕜', '🕑', '🕝', '🕒', '🕞', '🕓', '🕟', '🕔', '🕠', '🕕', '🕖', '🕗', '🕘', '🕙', '🕚', '🕡', '🕢', '🕣', '🕤', '🕥', '🕦'
Arrows:
'⬍', '⬈', '➞', '⬊', '⬍', '⬋', '⬅', '⬉'
Bird - This looks decent but may be missing something.
'︷', '︵', '︹', '︺', '︶', '︸'
'︷', '︵', '︹', '︺', '︶', '︸', '︶', '︺', '︹', '︵'
Plants - This isn't quite complete
'☘', '❀', '❁'
'☘', '❀', '❁', '❀'
Eclipse - From Raku Throbber post author
'🌑', '🌒', '🌓', '🌔', '🌕', '🌖', '🌗', '🌘'
| #Python | Python | from time import sleep
while True:
for rod in r'\|/-':
print(rod, end='\r')
sleep(0.25) |
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
| #Common_Lisp | Common Lisp | (defstruct stack
elements)
(defun stack-push (element stack)
(push element (stack-elements stack)))
(defun stack-pop (stack)(deftype Stack [elements])
(defun stack-empty (stack)
(endp (stack-elements stack)))
(defun stack-top (stack)
(first (stack-elements stack)))
(defun stack-peek (stack)
(stack-top stack)) |
http://rosettacode.org/wiki/Spiral_matrix | Spiral matrix | Task
Produce a spiral array.
A spiral array is a square arrangement of the first N2 natural numbers, where the
numbers increase sequentially as you go around the edges of the array spiraling inwards.
For example, given 5, produce this array:
0 1 2 3 4
15 16 17 18 5
14 23 24 19 6
13 22 21 20 7
12 11 10 9 8
Related tasks
Zig-zag matrix
Identity_matrix
Ulam_spiral_(for_primes)
| #ABAP | ABAP | REPORT zspiral_matrix.
CLASS lcl_spiral_matrix DEFINITION FINAL.
PUBLIC SECTION.
TYPES:
BEGIN OF ty_coordinates,
dy TYPE i,
dx TYPE i,
value TYPE i,
END OF ty_coordinates,
ty_t_coordinates TYPE STANDARD TABLE OF ty_coordinates WITH EMPTY KEY.
DATA mv_dimention TYPE i.
DATA mv_initial_value TYPE i.
METHODS:
constructor IMPORTING iv_dimention TYPE i
iv_initial_value TYPE i,
get_coordinates RETURNING VALUE(rv_result) TYPE ty_t_coordinates,
print.
PRIVATE SECTION.
DATA lt_coordinates TYPE ty_t_coordinates.
METHODS create RETURNING VALUE(ro_result) TYPE REF TO lcl_spiral_matrix.
ENDCLASS.
CLASS lcl_spiral_matrix IMPLEMENTATION.
METHOD constructor.
mv_dimention = iv_dimention.
mv_initial_value = iv_initial_value.
create( ).
ENDMETHOD.
METHOD create.
DATA dy TYPE i.
DATA dx TYPE i.
DATA value TYPE i.
DATA seq_number TYPE i.
DATA seq_dimention TYPE i.
DATA sign_coef TYPE i VALUE -1.
value = mv_initial_value.
" Fill in the first row (index 0)
DO mv_dimention TIMES.
APPEND VALUE #( dy = dy dx = dx value = value ) TO lt_coordinates.
value = value + 1.
dx = dx + 1.
ENDDO.
seq_dimention = mv_dimention.
" Find the row and column numbers and set the values.
DO ( 2 * mv_dimention - 2 ) / 2 TIMES.
sign_coef = - sign_coef.
seq_dimention = seq_dimention - 1.
DO 2 TIMES.
seq_number = seq_number + 1.
DO seq_dimention TIMES.
IF seq_number MOD 2 <> 0.
dy = dy + 1 * sign_coef.
ELSE.
dx = dx - 1 * sign_coef.
ENDIF.
APPEND VALUE #( dy = dy dx = dx value = value ) TO lt_coordinates.
value = value + 1.
ENDDO.
ENDDO.
ENDDO.
ro_result = me.
ENDMETHOD.
METHOD get_coordinates.
rv_result = lt_coordinates.
ENDMETHOD.
METHOD print.
DATA cnt TYPE i.
DATA line TYPE string.
SORT lt_coordinates BY dy dx ASCENDING.
LOOP AT lt_coordinates ASSIGNING FIELD-SYMBOL(<ls_coordinates>).
cnt = cnt + 1.
line = |{ line } { <ls_coordinates>-value }|.
IF cnt MOD mv_dimention = 0.
WRITE / line.
CLEAR line.
ENDIF.
ENDLOOP.
ENDMETHOD.
ENDCLASS.
START-OF-SELECTION.
DATA(go_spiral_matrix) = NEW lcl_spiral_matrix( iv_dimention = 5
iv_initial_value = 0 ).
go_spiral_matrix->print( ). |
http://rosettacode.org/wiki/Special_variables | Special variables | Special variables have a predefined meaning within a computer programming language.
Task
List the special variables used within the language.
| #bc | bc | #include <iostream>
struct SpecialVariables
{
int i = 0;
SpecialVariables& operator++()
{
// 'this' is a special variable that is a pointer to the current
// class instance. It can optionally be used to refer to elements
// of the class.
this->i++; // has the same meaning as 'i++'
// returning *this lets the object return a reference to itself
return *this;
}
};
int main()
{
SpecialVariables sv;
auto sv2 = ++sv; // makes a copy of sv after it was incremented
std::cout << " sv :" << sv.i << "\n sv2:" << sv2.i << "\n";
} |
http://rosettacode.org/wiki/Special_variables | Special variables | Special variables have a predefined meaning within a computer programming language.
Task
List the special variables used within the language.
| #Bracmat | Bracmat | #include <iostream>
struct SpecialVariables
{
int i = 0;
SpecialVariables& operator++()
{
// 'this' is a special variable that is a pointer to the current
// class instance. It can optionally be used to refer to elements
// of the class.
this->i++; // has the same meaning as 'i++'
// returning *this lets the object return a reference to itself
return *this;
}
};
int main()
{
SpecialVariables sv;
auto sv2 = ++sv; // makes a copy of sv after it was incremented
std::cout << " sv :" << sv.i << "\n sv2:" << sv2.i << "\n";
} |
http://rosettacode.org/wiki/Stable_marriage_problem | Stable marriage problem | Solve the Stable marriage problem using the Gale/Shapley algorithm.
Problem description
Given an equal number of men and women to be paired for marriage, each man ranks all the women in order of his preference and each woman ranks all the men in order of her preference.
A stable set of engagements for marriage is one where no man prefers a woman over the one he is engaged to, where that other woman also prefers that man over the one she is engaged to. I.e. with consulting marriages, there would be no reason for the engagements between the people to change.
Gale and Shapley proved that there is a stable set of engagements for any set of preferences and the first link above gives their algorithm for finding a set of stable engagements.
Task Specifics
Given ten males:
abe, bob, col, dan, ed, fred, gav, hal, ian, jon
And ten females:
abi, bea, cath, dee, eve, fay, gay, hope, ivy, jan
And a complete list of ranked preferences, where the most liked is to the left:
abe: abi, eve, cath, ivy, jan, dee, fay, bea, hope, gay
bob: cath, hope, abi, dee, eve, fay, bea, jan, ivy, gay
col: hope, eve, abi, dee, bea, fay, ivy, gay, cath, jan
dan: ivy, fay, dee, gay, hope, eve, jan, bea, cath, abi
ed: jan, dee, bea, cath, fay, eve, abi, ivy, hope, gay
fred: bea, abi, dee, gay, eve, ivy, cath, jan, hope, fay
gav: gay, eve, ivy, bea, cath, abi, dee, hope, jan, fay
hal: abi, eve, hope, fay, ivy, cath, jan, bea, gay, dee
ian: hope, cath, dee, gay, bea, abi, fay, ivy, jan, eve
jon: abi, fay, jan, gay, eve, bea, dee, cath, ivy, hope
abi: bob, fred, jon, gav, ian, abe, dan, ed, col, hal
bea: bob, abe, col, fred, gav, dan, ian, ed, jon, hal
cath: fred, bob, ed, gav, hal, col, ian, abe, dan, jon
dee: fred, jon, col, abe, ian, hal, gav, dan, bob, ed
eve: jon, hal, fred, dan, abe, gav, col, ed, ian, bob
fay: bob, abe, ed, ian, jon, dan, fred, gav, col, hal
gay: jon, gav, hal, fred, bob, abe, col, ed, dan, ian
hope: gav, jon, bob, abe, ian, dan, hal, ed, col, fred
ivy: ian, col, hal, gav, fred, bob, abe, ed, jon, dan
jan: ed, hal, gav, abe, bob, jon, col, ian, fred, dan
Use the Gale Shapley algorithm to find a stable set of engagements
Perturb this set of engagements to form an unstable set of engagements then check this new set for stability.
References
The Stable Marriage Problem. (Eloquent description and background information).
Gale-Shapley Algorithm Demonstration.
Another Gale-Shapley Algorithm Demonstration.
Stable Marriage Problem - Numberphile (Video).
Stable Marriage Problem (the math bit) (Video).
The Stable Marriage Problem and School Choice. (Excellent exposition)
| #C | C | #include <stdio.h>
int verbose = 0;
enum {
clown = -1,
abe, bob, col, dan, ed, fred, gav, hal, ian, jon,
abi, bea, cath, dee, eve, fay, gay, hope, ivy, jan,
};
const char *name[] = {
"Abe", "Bob", "Col", "Dan", "Ed", "Fred", "Gav", "Hal", "Ian", "Jon",
"Abi", "Bea", "Cath", "Dee", "Eve", "Fay", "Gay", "Hope", "Ivy", "Jan"
};
int pref[jan + 1][jon + 1] = {
{ abi, eve, cath, ivy, jan, dee, fay, bea, hope, gay },
{ cath, hope, abi, dee, eve, fay, bea, jan, ivy, gay },
{ hope, eve, abi, dee, bea, fay, ivy, gay, cath, jan },
{ ivy, fay, dee, gay, hope, eve, jan, bea, cath, abi },
{ jan, dee, bea, cath, fay, eve, abi, ivy, hope, gay },
{ bea, abi, dee, gay, eve, ivy, cath, jan, hope, fay },
{ gay, eve, ivy, bea, cath, abi, dee, hope, jan, fay },
{ abi, eve, hope, fay, ivy, cath, jan, bea, gay, dee },
{ hope, cath, dee, gay, bea, abi, fay, ivy, jan, eve },
{ abi, fay, jan, gay, eve, bea, dee, cath, ivy, hope },
{ bob, fred, jon, gav, ian, abe, dan, ed, col, hal },
{ bob, abe, col, fred, gav, dan, ian, ed, jon, hal },
{ fred, bob, ed, gav, hal, col, ian, abe, dan, jon },
{ fred, jon, col, abe, ian, hal, gav, dan, bob, ed },
{ jon, hal, fred, dan, abe, gav, col, ed, ian, bob },
{ bob, abe, ed, ian, jon, dan, fred, gav, col, hal },
{ jon, gav, hal, fred, bob, abe, col, ed, dan, ian },
{ gav, jon, bob, abe, ian, dan, hal, ed, col, fred },
{ ian, col, hal, gav, fred, bob, abe, ed, jon, dan },
{ ed, hal, gav, abe, bob, jon, col, ian, fred, dan },
};
int pairs[jan + 1], proposed[jan + 1];
void engage(int man, int woman)
{
pairs[man] = woman;
pairs[woman] = man;
if (verbose) printf("%4s is engaged to %4s\n", name[man], name[woman]);
}
void dump(int woman, int man)
{
pairs[man] = pairs[woman] = clown;
if (verbose) printf("%4s dumps %4s\n", name[woman], name[man]);
}
/* how high this person ranks that: lower is more preferred */
int rank(int this, int that)
{
int i;
for (i = abe; i <= jon && pref[this][i] != that; i++);
return i;
}
void propose(int man, int woman)
{
int fiance = pairs[woman];
if (verbose) printf("%4s proposes to %4s\n", name[man], name[woman]);
if (fiance == clown) {
engage(man, woman);
} else if (rank(woman, man) < rank(woman, fiance)) {
dump(woman, fiance);
engage(man, woman);
}
}
int covet(int man1, int wife2)
{
if (rank(man1, wife2) < rank(man1, pairs[man1]) &&
rank(wife2, man1) < rank(wife2, pairs[wife2])) {
printf( " %4s (w/ %4s) and %4s (w/ %4s) prefer each other"
" over current pairing.\n",
name[man1], name[pairs[man1]], name[wife2], name[pairs[wife2]]
);
return 1;
}
return 0;
}
int thy_neighbors_wife(int man1, int man2)
{ /* +: force checking all pairs; "||" would shortcircuit */
return covet(man1, pairs[man2]) + covet(man2, pairs[man1]);
}
int unstable()
{
int i, j, bad = 0;
for (i = abe; i < jon; i++) {
for (j = i + 1; j <= jon; j++)
if (thy_neighbors_wife(i, j)) bad = 1;
}
return bad;
}
int main()
{
int i, unengaged;
/* init: everyone marries the clown */
for (i = abe; i <= jan; i++)
pairs[i] = proposed[i] = clown;
/* rounds */
do {
unengaged = 0;
for (i = abe; i <= jon; i++) {
//for (i = abi; i <= jan; i++) { /* could let women propose */
if (pairs[i] != clown) continue;
unengaged = 1;
propose(i, pref[i][++proposed[i]]);
}
} while (unengaged);
printf("Pairing:\n");
for (i = abe; i <= jon; i++)
printf(" %4s - %s\n", name[i],
pairs[i] == clown ? "clown" : name[pairs[i]]);
printf(unstable()
? "Marriages not stable\n" /* draw sad face here */
: "Stable matchup\n");
printf("\nBut if Bob and Fred were to swap:\n");
i = pairs[bob];
engage(bob, pairs[fred]);
engage(fred, i);
printf(unstable() ? "Marriages not stable\n" : "Stable matchup\n");
return 0;
} |
http://rosettacode.org/wiki/Spelling_of_ordinal_numbers | Spelling of ordinal numbers | Ordinal numbers (as used in this Rosetta Code task), are numbers that describe the position of something in a list.
It is this context that ordinal numbers will be used, using an English-spelled name of an ordinal number.
The ordinal numbers are (at least, one form of them):
1st 2nd 3rd 4th 5th 6th 7th ··· 99th 100th ··· 1000000000th ··· etc
sometimes expressed as:
1st 2nd 3rd 4th 5th 6th 7th ··· 99th 100th ··· 1000000000th ···
For this task, the following (English-spelled form) will be used:
first second third fourth fifth sixth seventh ninety-nineth one hundredth one billionth
Furthermore, the American version of numbers will be used here (as opposed to the British).
2,000,000,000 is two billion, not two milliard.
Task
Write a driver and a function (subroutine/routine ···) that returns the English-spelled ordinal version of a specified number (a positive integer).
Optionally, try to support as many forms of an integer that can be expressed: 123 00123.0 1.23e2 all are forms of the same integer.
Show all output here.
Test cases
Use (at least) the test cases of:
1 2 3 4 5 11 65 100 101 272 23456 8007006005004003
Related tasks
Number names
N'th
| #Nim | Nim | import strutils, algorithm, tables
const irregularOrdinals = {"one": "first",
"two": "second",
"three": "third",
"five": "fifth",
"eight": "eighth",
"nine": "ninth",
"twelve": "twelfth"}.toTable
const
tens = ["", "", "twenty", "thirty", "forty", "fifty", "sixty", "seventy",
"eighty", "ninety"]
small = ["zero", "one", "two", "three", "four", "five", "six", "seven",
"eight", "nine", "ten", "eleven", "twelve", "thirteen", "fourteen",
"fifteen", "sixteen", "seventeen", "eighteen", "nineteen"]
huge = ["", "", "million", "billion", "trillion", "quadrillion",
"quintillion", "sextillion", "septillion", "octillion", "nonillion",
"decillion"]
# Forward reference.
proc spellInteger(n: int64): string
proc nonzero(c: string; n: int64; connect = ""): string =
if n == 0: "" else: connect & c & spellInteger(n)
proc lastAnd(num: string): string =
if ',' in num:
let pos = num.rfind(',')
var (pre, last) = if pos >= 0: (num[0 ..< pos], num[pos+1 .. num.high])
else: ("", num)
if " and " notin last: last = " and" & last
result = [pre, ",", last].join()
else:
result = num
proc big(e, n: int64): string =
if e == 0:
spellInteger(n)
elif e == 1:
spellInteger(n) & " thousand"
else:
spellInteger(n) & " " & huge[e]
iterator base1000Rev(n: int64): int64 =
var n = n
while n != 0:
let r = n mod 1000
n = n div 1000
yield r
proc spellInteger(n: int64): string =
if n < 0:
"minus " & spellInteger(-n)
elif n < 20:
small[int(n)]
elif n < 100:
let a = n div 10
let b = n mod 10
tens[int(a)] & nonzero("-", b)
elif n < 1000:
let a = n div 100
let b = n mod 100
small[int(a)] & " hundred" & nonzero(" ", b, " and")
else:
var sq = newSeq[string]()
var e = 0
for x in base1000Rev(n):
if x > 0: sq.add big(e, x)
inc e
reverse sq
lastAnd(sq.join(", "))
proc num2ordinal(n: SomeInteger|SomeFloat): string =
let n = n.int64
var num = spellInteger(n)
let hyphen = num.rsplit('-', 1)
var number = num.rsplit(' ', 1)
var delim = ' '
if number[^1].len > hyphen[^1].len:
number = hyphen
delim = '-'
if number[^1] in irregularOrdinals:
number[^1] = delim & irregularOrdinals[number[^1]]
elif number[^1].endswith('y'):
number[^1] = delim & number[^1][0..^2] & "ieth"
else:
number[^1] = delim & number[^1] & "th"
result = number.join()
when isMainModule:
const
tests1 = [int64 1, 2, 3, 4, 5, 11, 65, 100, 101, 272, 23456, 8007006005004003, 123]
tests2 = [0123.0, 1.23e2]
for num in tests1:
echo "$1 => $2".format(num, num2ordinal(num))
for num in tests2:
echo "$1 => $2".format(num, num2ordinal(num)) |
http://rosettacode.org/wiki/Spelling_of_ordinal_numbers | Spelling of ordinal numbers | Ordinal numbers (as used in this Rosetta Code task), are numbers that describe the position of something in a list.
It is this context that ordinal numbers will be used, using an English-spelled name of an ordinal number.
The ordinal numbers are (at least, one form of them):
1st 2nd 3rd 4th 5th 6th 7th ··· 99th 100th ··· 1000000000th ··· etc
sometimes expressed as:
1st 2nd 3rd 4th 5th 6th 7th ··· 99th 100th ··· 1000000000th ···
For this task, the following (English-spelled form) will be used:
first second third fourth fifth sixth seventh ninety-nineth one hundredth one billionth
Furthermore, the American version of numbers will be used here (as opposed to the British).
2,000,000,000 is two billion, not two milliard.
Task
Write a driver and a function (subroutine/routine ···) that returns the English-spelled ordinal version of a specified number (a positive integer).
Optionally, try to support as many forms of an integer that can be expressed: 123 00123.0 1.23e2 all are forms of the same integer.
Show all output here.
Test cases
Use (at least) the test cases of:
1 2 3 4 5 11 65 100 101 272 23456 8007006005004003
Related tasks
Number names
N'th
| #Perl | Perl | use Lingua::EN::Numbers 'num2en_ordinal';
printf "%16s : %s\n", $_, num2en_ordinal(0+$_) for
<1 2 3 4 5 11 65 100 101 272 23456 8007006005004003 123 00123.0 '00123.0' 1.23e2 '1.23e2'>; |
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.
| #MiniScript | MiniScript | squares = []
tris = []
both = []
for i in range(1, 100)
tris.push i*i*i
if tris.indexOf(i*i) == null then
squares.push i*i
else
both.push i*i
end if
end for
print "Square but not cube:"
print squares[:30]
print "Both square and cube:"
print both[:3] |
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.
| #Modula-2 | Modula-2 | MODULE SquareNotCube;
FROM InOut IMPORT WriteString, WriteCard, WriteLn;
CONST
Amount = 30;
VAR
CubeRoot, SquareRoot,
Cube, Square,
Seen: CARDINAL;
BEGIN
Seen := 0;
SquareRoot := 1;
CubeRoot := 1;
Square := 1;
Cube := 1;
REPEAT
SquareRoot := SquareRoot + 1;
Square := SquareRoot * SquareRoot;
WHILE Square > Cube DO
CubeRoot := CubeRoot + 1;
Cube := CubeRoot * CubeRoot * CubeRoot;
END;
IF Square # Cube THEN
Seen := Seen + 1;
WriteCard(Square, 4);
WriteLn();
END;
UNTIL Seen = Amount
END SquareNotCube. |
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
| #Tcl | Tcl | package require Tcl 8.5
proc stats {size} {
set sum 0.0
set sum2 0.0
for {set i 0} {$i < $size} {incr i} {
set r [expr {rand()}]
incr histo([expr {int(floor($r*10))}])
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 {0 1 2 3 4 5 6 7 8 9} {
# The 205 is a magic factor stolen from the Go solution
puts [string repeat "*" [expr {$histo($i)*205/int($size)}]]
}
}
stats 100
puts ""
stats 1000
puts ""
stats 10000 |
http://rosettacode.org/wiki/Split_a_character_string_based_on_change_of_character | Split a character string based on change of character |
Task
Split a (character) string into comma (plus a blank) delimited
strings based on a change of character (left to right).
Show the output here (use the 1st example below).
Blanks should be treated as any other character (except
they are problematic to display clearly). The same applies
to commas.
For instance, the string:
gHHH5YY++///\
should be split and show:
g, HHH, 5, YY, ++, ///, \
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
| #Julia | Julia | # v0.6
using IterTools
str = "gHHH5YY++///\\"
sep = map(join, groupby(identity, str))
println("string: $str\nseparated: ", join(sep, ", ")) |
http://rosettacode.org/wiki/Split_a_character_string_based_on_change_of_character | Split a character string based on change of character |
Task
Split a (character) string into comma (plus a blank) delimited
strings based on a change of character (left to right).
Show the output here (use the 1st example below).
Blanks should be treated as any other character (except
they are problematic to display clearly). The same applies
to commas.
For instance, the string:
gHHH5YY++///\
should be split and show:
g, HHH, 5, YY, ++, ///, \
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
| #Kotlin | Kotlin | // version 1.0.6
fun splitOnChange(s: String): String {
if (s.length < 2) return s
var t = s.take(1)
for (i in 1 until s.length)
if (t.last() == s[i]) t += s[i]
else t += ", " + s[i]
return t
}
fun main(args: Array<String>) {
val s = """gHHH5YY++///\"""
println(splitOnChange(s))
} |
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.
| #Scheme | Scheme | ; Recursive function to return the Nth Stern-Brocot sequence number.
(define stern-brocot
(lambda (n)
(cond
((<= n 0)
0)
((<= n 2)
1)
((even? n)
(stern-brocot (/ n 2)))
(else
(let ((earlier (/ (1+ n) 2)))
(+ (stern-brocot earlier) (stern-brocot (1- earlier)))))))) |
http://rosettacode.org/wiki/Spinning_rod_animation/Text | Spinning rod animation/Text | Task
An animation with the following frames in the following order (if certain characters aren't available or can't be used correctly in the programming language, alternate characters can replace any of these frames) must animate with a delay of 0.25 seconds between each frame, with the previous frame being cleared before the next frame appears:
|
/
- or ─
\
A stand-alone version that loops and/or a version that doesn't loop can be made. These examples can also be converted into a system used in game development which is called on a HUD or GUI element requiring it to be called each frame to output the text, and advance the frame when the frame delay has passed. You can also use alternate text such as the . animation ( . | .. | ... | .. | repeat from . ) or the logic can be updated to include a ping/pong style where the frames advance forward, reach the end and then play backwards and when they reach the beginning they start over ( technically, you'd stop one frame prior to prevent the first frame playing twice, or write it another way ).
There are many different ways you can incorporate text animations. Here are a few text ideas - each frame is in quotes. If you can think of any, add them to this page! There are 2 examples for several of these; the first is the base animation with only unique sets of characters. The second consists of the primary set from a - n and doubled, minus the first and last element ie: We only want the center. This way an animation can play forwards, and then in reverse ( ping ponging ) without having to code that feature. For the animations with 3 elements, we only add 1, the center. with 4, it becomes 6. with 10, it becomes 18.
We don't need the second option for some of the animations if they connect smoothly, when animated, back to the first element. ... doesn't connect with . cleanly - there is a large leap. The rotating pipe meets the first perfectly so it isn't necessary, etc..
Dots - Option A requires ping / pong enabled script. Option B just adds the elements in the center.
'.', '..', '...'
'.', '..', '...', '..'
Pipe - This has the uniform sideways pipe instead of a hyphen to prevent non-uniform sizing.
'|', '/', '─', '\'
Stars - Option A requires ping / pong enabled script. Option B just adds the elements from the center.
'⁎', '⁑', '⁂'
'⁎', '⁑', '⁂', '⁑'
Clock - These need to be ordered. I haven't done this yet as the application I was testing the system in doesn't support these wingdings / icons. But this would look quite nice and you could set it up to go forward, or backward during an undo process, etc..
'🕛', '🕧', '🕐', '🕜', '🕑', '🕝', '🕒', '🕞', '🕓', '🕟', '🕔', '🕠', '🕕', '🕖', '🕗', '🕘', '🕙', '🕚', '🕡', '🕢', '🕣', '🕤', '🕥', '🕦'
Arrows:
'⬍', '⬈', '➞', '⬊', '⬍', '⬋', '⬅', '⬉'
Bird - This looks decent but may be missing something.
'︷', '︵', '︹', '︺', '︶', '︸'
'︷', '︵', '︹', '︺', '︶', '︸', '︶', '︺', '︹', '︵'
Plants - This isn't quite complete
'☘', '❀', '❁'
'☘', '❀', '❁', '❀'
Eclipse - From Raku Throbber post author
'🌑', '🌒', '🌓', '🌔', '🌕', '🌖', '🌗', '🌘'
| #Racket | Racket |
#lang racket
(define (anim)
(for ([c "\\|/-"])
(printf "~a\r" c)
(sleep 0.25))
(anim))
(anim)
|
http://rosettacode.org/wiki/Spinning_rod_animation/Text | Spinning rod animation/Text | Task
An animation with the following frames in the following order (if certain characters aren't available or can't be used correctly in the programming language, alternate characters can replace any of these frames) must animate with a delay of 0.25 seconds between each frame, with the previous frame being cleared before the next frame appears:
|
/
- or ─
\
A stand-alone version that loops and/or a version that doesn't loop can be made. These examples can also be converted into a system used in game development which is called on a HUD or GUI element requiring it to be called each frame to output the text, and advance the frame when the frame delay has passed. You can also use alternate text such as the . animation ( . | .. | ... | .. | repeat from . ) or the logic can be updated to include a ping/pong style where the frames advance forward, reach the end and then play backwards and when they reach the beginning they start over ( technically, you'd stop one frame prior to prevent the first frame playing twice, or write it another way ).
There are many different ways you can incorporate text animations. Here are a few text ideas - each frame is in quotes. If you can think of any, add them to this page! There are 2 examples for several of these; the first is the base animation with only unique sets of characters. The second consists of the primary set from a - n and doubled, minus the first and last element ie: We only want the center. This way an animation can play forwards, and then in reverse ( ping ponging ) without having to code that feature. For the animations with 3 elements, we only add 1, the center. with 4, it becomes 6. with 10, it becomes 18.
We don't need the second option for some of the animations if they connect smoothly, when animated, back to the first element. ... doesn't connect with . cleanly - there is a large leap. The rotating pipe meets the first perfectly so it isn't necessary, etc..
Dots - Option A requires ping / pong enabled script. Option B just adds the elements in the center.
'.', '..', '...'
'.', '..', '...', '..'
Pipe - This has the uniform sideways pipe instead of a hyphen to prevent non-uniform sizing.
'|', '/', '─', '\'
Stars - Option A requires ping / pong enabled script. Option B just adds the elements from the center.
'⁎', '⁑', '⁂'
'⁎', '⁑', '⁂', '⁑'
Clock - These need to be ordered. I haven't done this yet as the application I was testing the system in doesn't support these wingdings / icons. But this would look quite nice and you could set it up to go forward, or backward during an undo process, etc..
'🕛', '🕧', '🕐', '🕜', '🕑', '🕝', '🕒', '🕞', '🕓', '🕟', '🕔', '🕠', '🕕', '🕖', '🕗', '🕘', '🕙', '🕚', '🕡', '🕢', '🕣', '🕤', '🕥', '🕦'
Arrows:
'⬍', '⬈', '➞', '⬊', '⬍', '⬋', '⬅', '⬉'
Bird - This looks decent but may be missing something.
'︷', '︵', '︹', '︺', '︶', '︸'
'︷', '︵', '︹', '︺', '︶', '︸', '︶', '︺', '︹', '︵'
Plants - This isn't quite complete
'☘', '❀', '❁'
'☘', '❀', '❁', '❀'
Eclipse - From Raku Throbber post author
'🌑', '🌒', '🌓', '🌔', '🌕', '🌖', '🌗', '🌘'
| #Raku | Raku | class throbber {
has @.frames;
has $.delay is rw = 0;
has $!index = 0;
has Bool $.marquee = False;
method next {
$!index = ($!index + 1) % [email protected];
sleep $.delay if $.delay;
if $!marquee {
("\b" x @.frames) ~ @.frames.rotate($!index).join;
}
else {
"\b" ~ @.frames[$!index];
}
}
}
my $rod = throbber.new( :frames(< | / - \ >), :delay(.25) );
print "\e[?25lLong running process... ";
print $rod.next for ^20;
my $clock = throbber.new( :frames("🕐" .. "🕛") );
print "\r\nSomething else with a delay... ";
until my $done {
# do something in a loop;
sleep 1/12;
print "\b", $clock.next;
$done = True if $++ >= 60;
}
my $moon = throbber.new( :frames('🌑🌒🌓🌔🌕🌖🌗🌘'.comb) );
print "\r\nGonna be a long night... ";
until my $end {
# do something in a loop;
sleep 1/8;
print "\b", $moon.next;
$end = True if $++ >= 60;
}
my $scroll = throbber.new( :frames('PLEASE STAND BY... '.comb), :delay(.1), :marquee );
print "\r\nEXPERIENCING TECHNICAL DIFFICULTIES: { $scroll.frames.join }";
print $scroll.next for ^95;
END { print "\e[?25h\n" } # clean up on exit |
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
| #Component_Pascal | Component Pascal |
MODULE Stacks;
IMPORT StdLog;
TYPE
(* some pointers to records *)
Object* = POINTER TO ABSTRACT RECORD END;
Integer = POINTER TO RECORD (Object)
i: INTEGER
END;
Point = POINTER TO RECORD (Object)
x,y: REAL
END;
Node = POINTER TO LIMITED RECORD
next- : Node;
data-: ANYPTR;
END;
(* Stack *)
Stack* = POINTER TO RECORD
top- : Node;
END;
PROCEDURE (dn: Object) Show*, NEW, ABSTRACT;
PROCEDURE (i: Integer) Show*;
BEGIN
StdLog.String("Integer(");StdLog.Int(i.i);StdLog.String(");");StdLog.Ln
END Show;
PROCEDURE (p: Point) Show*;
BEGIN
StdLog.String("Point(");StdLog.Real(p.x);StdLog.Char(',');
StdLog.Real(p.y);StdLog.String(");");StdLog.Ln
END Show;
PROCEDURE (s: Stack) Init, NEW;
BEGIN
s.top := NIL;
END Init;
PROCEDURE (s: Stack) Push*(data: ANYPTR), NEW;
VAR
n: Node;
BEGIN
NEW(n);n.next := NIL;n.data := data;
IF s.top = NIL THEN
s.top := n
ELSE
n.next := s.top;
s.top := n
END
END Push;
PROCEDURE (s: Stack) Pop*(): ANYPTR, NEW;
VAR
x: ANYPTR;
BEGIN
IF s.top # NIL THEN
x := s.top.data;
s.top := s.top.next
ELSE
x := NIL
END;
RETURN x
END Pop;
PROCEDURE (s: Stack) Empty*(): BOOLEAN, NEW;
BEGIN
RETURN s.top = NIL
END Empty;
PROCEDURE NewStack*(): Stack;
VAR
s: Stack;
BEGIN
NEW(s);s.Init;
RETURN s
END NewStack;
PROCEDURE NewInteger*(data: INTEGER): Integer;
VAR
i: Integer;
BEGIN
NEW(i);i.i := data;
RETURN i
END NewInteger;
PROCEDURE NewPoint*(x,y: REAL): Point;
VAR
p: Point;
BEGIN
NEW(p);p.x := x;p.y := y;
RETURN p
END NewPoint;
PROCEDURE TestStack*;
VAR
s: Stack;
BEGIN
s := NewStack();
s.Push(NewInteger(1));
s.Push(NewPoint(2.0,3.4));
s.Pop()(Object).Show();
s.Pop()(Object).Show();
END TestStack;
END Stacks.
|
http://rosettacode.org/wiki/Spiral_matrix | Spiral matrix | Task
Produce a spiral array.
A spiral array is a square arrangement of the first N2 natural numbers, where the
numbers increase sequentially as you go around the edges of the array spiraling inwards.
For example, given 5, produce this array:
0 1 2 3 4
15 16 17 18 5
14 23 24 19 6
13 22 21 20 7
12 11 10 9 8
Related tasks
Zig-zag matrix
Identity_matrix
Ulam_spiral_(for_primes)
| #Action.21 | Action! | DEFINE MAX_SIZE="10"
DEFINE MAX_MATRIX_SIZE="100"
INT FUNC Index(BYTE size,x,y)
RETURN (x+y*size)
PROC PrintMatrix(BYTE ARRAY a BYTE size)
BYTE i,j,v
FOR j=0 TO size-1
DO
FOR i=0 TO size-1
DO
v=a(Index(size,i,j))
IF v<10 THEN
Print(" ")
ELSE
Print(" ")
FI
PrintB(v)
OD
PutE()
OD
RETURN
PROC FillMatrix(BYTE ARRAY a BYTE size)
INT lev,maxLev,dist,maxDist,v
maxLev=size/2
IF (size&1)=0 THEN
maxLev==-1
FI
maxDist=size-1
v=1
FOR lev=0 TO maxLev
DO
FOR dist=0 TO maxDist
DO
a(Index(size,lev+dist,lev))=v v==+1
OD
FOR dist=0 TO maxDist-1
DO
a(Index(size,size-1-lev,lev+dist+1))=v v==+1
OD
FOR dist=0 TO maxDist-1
DO
a(Index(size,size-2-lev-dist,size-1-lev))=v v==+1
OD
FOR dist=0 TO maxDist-2
DO
a(Index(size,lev,size-2-lev-dist))=v v==+1
OD
maxDist==-2
OD
RETURN
PROC Test(BYTE size)
BYTE ARRAY mat(MAX_MATRIX_SIZE)
PrintF("Matrix size: %B%E",size)
FillMatrix(mat,size)
PrintMatrix(mat,size)
PutE()
RETURN
PROC Main()
Test(5)
Test(6)
RETURN |
http://rosettacode.org/wiki/Special_variables | Special variables | Special variables have a predefined meaning within a computer programming language.
Task
List the special variables used within the language.
| #C | C | #include <iostream>
struct SpecialVariables
{
int i = 0;
SpecialVariables& operator++()
{
// 'this' is a special variable that is a pointer to the current
// class instance. It can optionally be used to refer to elements
// of the class.
this->i++; // has the same meaning as 'i++'
// returning *this lets the object return a reference to itself
return *this;
}
};
int main()
{
SpecialVariables sv;
auto sv2 = ++sv; // makes a copy of sv after it was incremented
std::cout << " sv :" << sv.i << "\n sv2:" << sv2.i << "\n";
} |
http://rosettacode.org/wiki/Special_variables | Special variables | Special variables have a predefined meaning within a computer programming language.
Task
List the special variables used within the language.
| #C.2B.2B | C++ | #include <iostream>
struct SpecialVariables
{
int i = 0;
SpecialVariables& operator++()
{
// 'this' is a special variable that is a pointer to the current
// class instance. It can optionally be used to refer to elements
// of the class.
this->i++; // has the same meaning as 'i++'
// returning *this lets the object return a reference to itself
return *this;
}
};
int main()
{
SpecialVariables sv;
auto sv2 = ++sv; // makes a copy of sv after it was incremented
std::cout << " sv :" << sv.i << "\n sv2:" << sv2.i << "\n";
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.