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/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
| #Batch_File | Batch File | @echo off
setlocal enableDelayedExpansion
:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
:: LIFO stack usage
:: Define the stack
call :newStack myStack
:: Push some values onto the stack
for %%A in (value1 value2 value3) do call :pushStack myStack %%A
:: Test if stack is empty by examining the top "attribute"
if myStack.top==0 (echo myStack is empty) else (echo myStack is NOT empty)
:: Peek at the top stack value
call:peekStack myStack val && echo a peek at the top of myStack shows !val!
:: Pop the top stack value
call :popStack myStack val && echo popped myStack value=!val!
:: Push some more values onto the stack
for %%A in (value4 value5 value6) do call :pushStack myStack %%A
:: Process the remainder of the stack
:processStack
call :popStack myStack val || goto :stackEmpty
echo popped myStack value=!val!
goto :processStack
:stackEmpty
:: Test if stack is empty using the empty "method"/"macro". Use of the
:: second IF statement serves to demonstrate the negation of the empty
:: "method". A single IF could have been used with an ELSE clause instead.
if %myStack.empty% echo myStack is empty
if not %myStack.empty% echo myStack is NOT empty
exit /b
:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
:: LIFO stack definition
:newStack stackName
set /a %~1.top=0
:: Define an empty "method" for this stack as a sort of macro
set "%~1.empty=^!%~1.top^! == 0"
exit /b
:pushStack stackName value
set /a %~1.top+=1
set %~1.!%~1.top!=%2
exit /b
:popStack stackName returnVar
:: Sets errorlevel to 0 if success
:: Sets errorlevel to 1 if failure because stack was empty
if !%~1.top! equ 0 exit /b 1
for %%N in (!%~1.top!) do (
set %~2=!%~1.%%N!
set %~1.%%N=
)
set /a %~1.top-=1
exit /b 0
:peekStack stackName returnVar
:: Sets errorlevel to 0 if success
:: Sets errorlevel to 1 if failure because stack was empty
if !%~1.top! equ 0 exit /b 1
for %%N in (!%~1.top!) do set %~2=!%~1.%%N!
exit /b 0 |
http://rosettacode.org/wiki/Speech_synthesis | Speech synthesis | Render the text This is an example of speech synthesis as speech.
Related task
using a speech engine to highlight words
| #Perl | Perl | use Speech::Synthesis;
($engine) = Speech::Synthesis->InstalledEngines();
($voice) = Speech::Synthesis->InstalledVoices(engine => $engine);
Speech::Synthesis
->new(engine => $engine, voice => $voice->{id})
->speak("This is an example of speech synthesis."); |
http://rosettacode.org/wiki/Speech_synthesis | Speech synthesis | Render the text This is an example of speech synthesis as speech.
Related task
using a speech engine to highlight words
| #Phix | Phix | --
-- demo\rosetta\Speak.exw
-- ======================
--
with javascript_semantics
requires(6) -- WINDOWS or JS, not LINUX
requires(32) -- Windows 32 bit only, for now...
-- (^ runs fine on a 64-bit OS, but needs a 32-bit p.exe)
requires("1.0.2")
include builtins\speak.e -- (new in 1.0.2)
constant text = "This is an example of speech synthesis"
include pGUI.e
function button_cb(Ihandle /*ih*/)
speak(text)
return IUP_CONTINUE
end function
IupOpen()
Ihandle btn = IupButton("Speak",Icallback("button_cb")),
dlg = IupDialog(IupHbox({btn},"MARGIN=180x80"))
IupSetAttribute(dlg,"TITLE",text)
IupShow(dlg)
if platform()!=JS then
IupMainLoop()
IupClose()
end if
|
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.
| #F.23 | F# |
let rec fN n g φ=if φ<31 then match compare(n*n)(g*g*g) with | -1->printfn "%d"(n*n);fN(n+1) g (φ+1)
| 0->printfn "%d cube and square"(n*n);fN(n+1)(g+1)φ
| 1->fN n (g+1) φ
fN 1 1 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
| #Nim | Nim | import random, sequtils, stats, strutils, strformat
proc drawHistogram(ns: seq[float]) =
var h = newSeq[int](11)
for n in ns:
let pos = (n * 10).toInt
inc h[pos]
const maxWidth = 50
let mx = max(h)
echo ""
for n, count in h:
echo n.toFloat / 10, ": ", repeat('+', int(count / mx * maxWidth))
echo ""
randomize()
# First part: compute directly from a sequence of values.
echo "For 100 numbers:"
let ns = newSeqWith(100, rand(1.0))
echo &"μ = {ns.mean:.12f} σ = {ns.standardDeviation:.12f}"
ns.drawHistogram()
# Second part: compute incrementally using "RunningStat".
for count in [1_000, 10_000, 100_000, 1_000_000]:
echo &"For {count} numbers:"
var rs: RunningStat
for _ in 1..count:
let n = rand(1.0)
rs.push(n)
echo &"μ = {rs.mean:.12f} σ = {rs.standardDeviation:.12f}"
echo() |
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
| #Oforth | Oforth | : main(n)
| l m std i nb |
// Create list and calculate avg and stddev
ListBuffer init(n, #[ Float rand ]) dup ->l avg ->m
0 l apply(#[ sq +]) n / m sq - sqrt ->std
System.Out "n = " << n << ", avg = " << m << ", std = " << std << cr
// Histo
0.0 0.9 0.1 step: i [
l count(#[ between(i, i 0.1 +) ]) 400 * n / asInteger ->nb
System.Out i <<wjp(3, JUSTIFY_RIGHT, 2) " - " <<
i 0.1 + <<wjp(3, JUSTIFY_RIGHT, 2) " - " <<
StringBuffer new "*" <<n(nb) << cr
] ; |
http://rosettacode.org/wiki/Square-free_integers | Square-free integers | Task
Write a function to test if a number is square-free.
A square-free is an integer which is divisible by no perfect square other
than 1 (unity).
For this task, only positive square-free numbers will be used.
Show here (on this page) all square-free integers (in a horizontal format) that are between:
1 ───► 145 (inclusive)
1 trillion ───► 1 trillion + 145 (inclusive)
(One trillion = 1,000,000,000,000)
Show here (on this page) the count of square-free integers from:
1 ───► one hundred (inclusive)
1 ───► one thousand (inclusive)
1 ───► ten thousand (inclusive)
1 ───► one hundred thousand (inclusive)
1 ───► one million (inclusive)
See also
the Wikipedia entry: square-free integer
| #Sidef | Sidef | func is_square_free(n) {
n.abs! if (n < 0)
return false if (n == 0)
n.factor_exp + [[1,1]] -> all { .[1] == 1 }
}
func square_free_count(n) {
1 .. n.isqrt -> sum {|k|
moebius(k) * idiv(n, k*k)
}
}
func display_results(a, c, f = { _ }) {
a.each_slice(c, {|*s|
say s.map(f).join(' ')
})
}
var a = range( 1, 145).grep {|n| is_square_free(n) }
var b = range(1e12, 1e12+145).grep {|n| is_square_free(n) }
say "There are #{a.len} square─free numbers between 1 and 145:"
display_results(a, 17, {|n| "%3s" % n })
say "\nThere are #{b.len} square─free numbers between 10^12 and 10^12 + 145:"
display_results(b, 5)
say ''
for (2 .. 6) { |n|
var c = square_free_count(10**n)
say "The number of square─free numbers between 1 and 10^#{n} (inclusive) is: #{c}"
} |
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.
| #Ring | Ring |
# Project : Stem-and-leaf plot
data = list(120)
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(data, len(data))
func leafplot(x,n)
c = n
x = sort(x)
i = floor(x[1] / 10 ) - 1
for j = 1 to n
d = floor(x[j] / 10)
while d > i
i = i + 1
if j > 0
see nl
ok
see "" + i + " |"
end
see "" + (x[j] % 10) + " "
next
see nl
|
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
| #C.2B.2B | C++ |
// Solution for http://rosettacode.org/wiki/Split_a_character_string_based_on_change_of_character
#include<string>
#include<iostream>
auto split(const std::string& input, const std::string& delim){
std::string res;
for(auto ch : input){
if(!res.empty() && ch != res.back())
res += delim;
res += ch;
}
return res;
}
int main(){
std::cout << split("gHHH5 ))YY++,,,///\\", ", ") << std::endl;
} |
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
| #Clojure | Clojure | (defn print-cchanges [s]
(println (clojure.string/join ", " (map first (re-seq #"(.)\1*" s)))))
(print-cchanges "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.
| #PL.2FI | PL/I | sternBrocot: procedure options(main);
%replace MAX by 1200;
declare S(1:MAX) fixed;
/* find the first occurrence of N in S */
findFirst: procedure(n) returns(fixed);
declare (n, i) fixed;
do i=1 to MAX;
if S(i)=n then return(i);
end;
end findFirst;
/* find the greatest common divisor of A and B */
gcd: procedure(a, b) returns(fixed) recursive;
declare (a, b) fixed;
if b = 0 then return(a);
return(gcd(b, mod(a, b)));
end gcd;
/* calculate S(i) up to MAX */
declare i fixed;
S(1) = 1; S(2) = 1;
do i=2 to MAX/2;
S(i*2-1) = S(i) + S(i-1);
S(i*2) = S(i);
end;
/* print first 15 elements */
put skip list('First 15 elements: ');
do i=1 to 15;
put edit(S(i)) (F(2));
end;
/* find first occurrences of 1..10 and 100 */
do i=1 to 10;
put skip list('First',i,'at',findFirst(i));
end;
put skip list('First ',100,'at',findFirst(100));
/* check GCDs of adjacent pairs up to 1000th element */
do i=2 to 1000;
if gcd(S(i-1),S(i)) ^= 1 then do;
put skip list('GCD of adjacent pair not 1 at i=',i);
stop;
end;
end;
put skip list('All GCDs of adjacent pairs are 1.');
end sternBrocot; |
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
'🌑', '🌒', '🌓', '🌔', '🌕', '🌖', '🌗', '🌘'
| #Emacs_Lisp | Emacs Lisp | (while t
(dolist (char (string-to-list "\\|/-"))
(message "%c" char)
(sit-for 0.25))) |
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
'🌑', '🌒', '🌓', '🌔', '🌕', '🌖', '🌗', '🌘'
| #Factor | Factor | USING: calendar combinators.extras formatting io sequences
threads ;
[
"\\|/-" [ "%c\r" printf flush 1/4 seconds sleep ] each
] forever |
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
| #BBC_BASIC | BBC BASIC | STACKSIZE = 1000
FOR n = 3 TO 5
PRINT "Push ";n : PROCpush(n)
NEXT
PRINT "Pop " ; FNpop
PRINT "Push 6" : PROCpush(6)
REPEAT
PRINT "Pop " ; FNpop
UNTIL FNisempty
PRINT "Pop " ; FNpop
END
DEF PROCpush(n) : LOCAL f%
DEF FNpop : LOCAL f% : f% = 1
DEF FNisempty : LOCAL f% : f% = 2
PRIVATE stack(), sptr%
DIM stack(STACKSIZE-1)
CASE f% OF
WHEN 0:
IF sptr% = DIM(stack(),1) ERROR 100, "Error: stack overflowed"
stack(sptr%) = n
sptr% += 1
WHEN 1:
IF sptr% = 0 ERROR 101, "Error: stack empty"
sptr% -= 1
= stack(sptr%)
WHEN 2:
= (sptr% = 0)
ENDCASE
ENDPROC |
http://rosettacode.org/wiki/Speech_synthesis | Speech synthesis | Render the text This is an example of speech synthesis as speech.
Related task
using a speech engine to highlight words
| #PHP | PHP |
<?php
<?php
/*
_ _____ _ _ _ ___ __
| | |_ _| \ | | | | \ \ / /
| | | | | \| | | | |\ V /
| | | | | . ` | | | | > <
| |____ _| |_| |\ | |__| |/ . \
|______|_____|_| \_|\____//_/ \_\
*/
// Install eSpeak - Run this command in a terminal
/*
sudo apt-get install eSpeak
*/
/*
__ __ _____
| \/ | /\ / ____|
| \ / | / \ | |
| |\/| | / /\ \| |
| | | |/ ____ \ |____
|_| |_/_/ \_\_____|
*/
// Mac has it's own Speech Synthesis system
// accessible via the "say" command.
// To use eSpeak on a Mac, change this variable to true.
$mac_use_espeak = false;
// To use eSpeak on a Mac you need to install
// Homebrew Package Manager & eSpeak
// Run these commands in a terminal:
/*
/usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"
brew install espeak
*/
$voice = "espeak";
$statement = 'Hello World!';
$save_file_args = '-w HelloWorld.wav'; // eSpeak args
// Ask PHP what OS it was compiled for,
// CAPITALIZE it and truncate to the first 3 chars.
$OS = strtoupper(substr(PHP_OS, 0, 3));
// If this is Darwin (MacOS) AND we don't want eSpeak
elseif($OS === 'DAR' && $mac_use_espeak == false) {
$voice = "say -v 'Victoria'";
$save_file_args = '-o HelloWorld.wav'; // say args
}
// Say It
exec("$voice '$statement'");
// Save it to a File
exec("$voice '$statement' $save_file_args");
|
http://rosettacode.org/wiki/Speech_synthesis | Speech synthesis | Render the text This is an example of speech synthesis as speech.
Related task
using a speech engine to highlight words
| #PicoLisp | PicoLisp | (call 'espeak "This is an example of speech synthesis.") |
http://rosettacode.org/wiki/Speech_synthesis | Speech synthesis | Render the text This is an example of speech synthesis as speech.
Related task
using a speech engine to highlight words
| #PowerShell | PowerShell |
Add-Type -AssemblyName System.Speech
$anna = New-Object System.Speech.Synthesis.SpeechSynthesizer
$anna.Speak("I'm sorry Dave, I'm afraid I can't do that.")
$anna.Dispose()
|
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.
| #Factor | Factor | USING: combinators interpolate io kernel prettyprint math
math.functions math.order pair-rocket ;
IN: rosetta-code.square-but-not-cube
: fn ( s c n -- s' c' n' )
dup 31 < [
2over [ sq ] [ 3 ^ ] bi* <=> {
+lt+ => [ [ dup sq . 1 + ] 2dip 1 + fn ]
+eq+ => [ [ dup sq [I ${} cube and squareI] nl 1 + ] [ 1 + ] [ ] tri* fn ]
+gt+ => [ [ 1 + ] dip fn ]
} case
] when ;
1 1 1 fn 3drop |
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.
| #FALSE | FALSE | 1 1 1
[2O30>~][
[$$*2O$$**>][\1+\]#
1O$$**1O$*>[$$*.@1+@@" "]?
1+
]#
%%%
10, |
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
| #PARI.2FGP | PARI/GP | mean(v)={
vecsum(v)/#v
};
stdev(v,mu="")={
if(mu=="",mu=mean(v));
sqrt(sum(i=1,#v,(v[i]-mu)^2))/#v
};
histogram(v,bins=16,low=0,high=1)={
my(u=vector(bins),width=(high-low)/bins);
for(i=1,#v,u[(v[i]-low)\width+1]++);
u
};
show(n)={
my(v=vector(n,i,random(1.)),mu=mean(v),s=stdev(v,mu),h=histogram(v),sz=ceil(n/50/16));
for(i=1,16,for(j=1,h[i]\sz,print1("#"));print());
print("Mean: "mu);
print("Stdev: "s);
};
show(100);
show(1000);
show(10000); |
http://rosettacode.org/wiki/Square-free_integers | Square-free integers | Task
Write a function to test if a number is square-free.
A square-free is an integer which is divisible by no perfect square other
than 1 (unity).
For this task, only positive square-free numbers will be used.
Show here (on this page) all square-free integers (in a horizontal format) that are between:
1 ───► 145 (inclusive)
1 trillion ───► 1 trillion + 145 (inclusive)
(One trillion = 1,000,000,000,000)
Show here (on this page) the count of square-free integers from:
1 ───► one hundred (inclusive)
1 ───► one thousand (inclusive)
1 ───► ten thousand (inclusive)
1 ───► one hundred thousand (inclusive)
1 ───► one million (inclusive)
See also
the Wikipedia entry: square-free integer
| #Swift | Swift | import BigInt
import Foundation
extension BinaryInteger {
@inlinable
public var isSquare: Bool {
var x = self / 2
var seen = Set([x])
while x * x != self {
x = (x + (self / x)) / 2
if seen.contains(x) {
return false
}
seen.insert(x)
}
return true
}
@inlinable
public var isSquareFree: Bool {
return factors().dropFirst().reduce(true, { $0 && !$1.isSquare })
}
@inlinable
public func factors() -> [Self] {
let maxN = Self(Double(self).squareRoot())
var res = Set<Self>()
for factor in stride(from: 1, through: maxN, by: 1) where self % factor == 0 {
res.insert(factor)
res.insert(self / factor)
}
return res.sorted()
}
}
let sqFree1to145 = (1...145).filter({ $0.isSquareFree })
print("Square free numbers in range 1...145: \(sqFree1to145)")
let sqFreeBig = (BigInt(1_000_000_000_000)...BigInt(1_000_000_000_145)).filter({ $0.isSquareFree })
print("Square free numbers in range 1_000_000_000_000...1_000_000_000_045: \(sqFreeBig)")
var count = 0
for n in 1...1_000_000 {
if n.isSquareFree {
count += 1
}
switch n {
case 100, 1_000, 10_000, 100_000, 1_000_000:
print("Square free numbers between 1...\(n): \(count)")
case _:
break
}
} |
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.
| #Ruby | Ruby | class StemLeafPlot
def initialize(data, options = {})
opts = {:leaf_digits => 1}.merge(options)
@leaf_digits = opts[:leaf_digits]
@multiplier = 10 ** @leaf_digits
@plot = generate_structure(data)
end
private
def generate_structure(data)
plot = Hash.new {|h,k| h[k] = []}
data.sort.each do |value|
stem, leaf = parse(value)
plot[stem] << leaf
end
plot
end
def parse(value)
stem, leaf = value.abs.divmod(@multiplier)
[Stem.get(stem, value), leaf.round]
end
public
def print
stem_width = Math.log10(@plot.keys.max_by {|s| s.value}.value).ceil + 1
Stem.get_range(@plot.keys).each do |stem|
leaves = @plot[stem].inject("") {|str,leaf| str << "%*d " % [@leaf_digits, leaf]}
puts "%*s | %s" % [stem_width, stem, leaves]
end
puts "key: 5|4=#{5 * @multiplier + 4}"
puts "leaf unit: 1"
puts "stem unit: #@multiplier"
end
end
class Stem
@@cache = {}
def self.get(stem_value, datum)
sign = datum < 0 ? :- : :+
cache(stem_value, sign)
end
private
def self.cache(value, sign)
if @@cache[[value, sign]].nil?
@@cache[[value, sign]] = self.new(value, sign)
end
@@cache[[value, sign]]
end
def initialize(value, sign)
@value = value
@sign = sign
end
public
attr_accessor :value, :sign
def negative?
@sign == :-
end
def <=>(other)
if self.negative?
if other.negative?
other.value <=> self.value
else
-1
end
else
if other.negative?
1
else
self.value <=> other.value
end
end
end
def to_s
"%s%d" % [(self.negative? ? '-' : ' '), @value]
end
def self.get_range(array_of_stems)
min, max = array_of_stems.minmax
if min.negative?
if max.negative?
min.value.downto(max.value).collect {|n| cache(n, :-)}
else
min.value.downto(0).collect {|n| cache(n, :-)} + 0.upto(max.value).collect {|n| cache(n, :+)}
end
else
min.value.upto(max.value).collect {|n| cache(n, :+)}
end
end
end
data = DATA.read.split.map {|s| Float(s)}
StemLeafPlot.new(data).print
__END__
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 |
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
| #CLU | CLU | % Split a string based on a change of character
split_on_change = iter (s: string) yields (string)
part: string := ""
for c: char in string$chars(s) do
if ~string$empty(part)
cand part[string$size(part)] ~= c then
yield(part)
part := ""
end
part := part || string$c2s(c)
end
yield(part)
end split_on_change
start_up = proc ()
po: stream := stream$primary_output()
str: string := "gHHH5YYY++///\\" % \\ escapes, as in C
rslt: string := ""
first: bool := true
for part: string in split_on_change(str) do
if first then first := false
else rslt := rslt || ", "
end
rslt := rslt || part
end
stream$putl(po, rslt)
end start_up |
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
| #COBOL | COBOL |
identification division.
program-id. split-ch.
data division.
1 split-str pic x(30) value space.
88 str-1 value "gHHH5YY++///\".
88 str-2 value "gHHH5 ))YY++,,,///\".
1 binary.
2 ptr pic 9(4) value 1.
2 str-start pic 9(4) value 1.
2 delim-len pic 9(4) value 1.
2 split-str-len pic 9(4) value 0.
2 trash-9 pic 9(4) value 0.
1 delim-char pic x value space.
1 delim-str pic x(6) value space.
1 trash-x pic x.
procedure division.
display "Requested string"
set str-1 to true
perform split-init-and-go
display space
display "With spaces and commas"
set str-2 to true
perform split-init-and-go
stop run
.
split-init-and-go.
move 1 to ptr
move 0 to split-str-len
perform split
.
split.
perform get-split-str-len
display split-str (1:split-str-len)
perform until ptr > split-str-len
move ptr to str-start
move split-str (ptr:1) to delim-char
unstring split-str (1:split-str-len)
delimited all delim-char
into trash-x delimiter delim-str
pointer ptr
end-unstring
subtract str-start from ptr giving delim-len
move split-str (str-start:delim-len)
to delim-str (1:delim-len)
display delim-str (1:delim-len) with no advancing
if ptr <= split-str-len
display ", " with no advancing
end-if
end-perform
display space
.
get-split-str-len.
inspect function reverse (split-str) tallying
trash-9 for leading space
split-str-len for characters after space
.
end program split-ch.
|
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.
| #PL.2FM | PL/M | 100H:
/* FIND LOCATION OF FIRST ELEMENT IN ARRAY */
FIND$FIRST: PROCEDURE (ARR, EL) ADDRESS;
DECLARE (ARR, N) ADDRESS, (EL, A BASED ARR) BYTE;
N = 0;
LOOP:
IF A(N) = EL THEN RETURN N;
ELSE N = N + 1;
GO TO LOOP;
END FIND$FIRST;
/* CP/M CALL */
BDOS: PROCEDURE (FN, ARG);
DECLARE FN BYTE, ARG ADDRESS;
GO TO 5;
END BDOS;
PRINT: PROCEDURE (STRING);
DECLARE STRING ADDRESS;
CALL BDOS(9, STRING);
END PRINT;
/* PRINT NUMBER */
PRINT$NUMBER: PROCEDURE (N);
DECLARE S (6) BYTE INITIAL ('.....$');
DECLARE (N, P) ADDRESS, C BASED P BYTE;
P = .S(5);
DIGIT:
P = P - 1;
C = N MOD 10 + '0';
IF (N := N / 10) > 0 THEN GO TO DIGIT;
CALL PRINT(P);
END PRINT$NUMBER;
/* GENERATE FIRST 1200 ELEMENTS OF STERN-BROCOT SEQUENCE */
DECLARE S (1201) BYTE, I ADDRESS;
S(1) = 1;
S(2) = 1;
DO I = 2 TO 600;
S(I*2-1) = S(I) + S(I-1);
S(I*2) = S(I);
END;
/* PRINT FIRST 15 ELEMENTS */
CALL PRINT(.'FIRST 15 ELEMENTS: $');
DO I = 1 TO 15;
CALL PRINT$NUMBER(S(I));
CALL PRINT(.' $');
END;
CALL PRINT(.(13,10,'$'));
/* PRINT FIRST OCCURRENCE OF N */
PRINT$FIRST: PROCEDURE (N);
DECLARE N BYTE;
CALL PRINT(.'FIRST $');
CALL PRINT$NUMBER(N);
CALL PRINT(.' AT $');
CALL PRINT$NUMBER(FIND$FIRST(.S, N));
CALL PRINT(.(13,10,'$'));
END PRINT$FIRST;
DO I = 1 TO 10;
CALL PRINT$FIRST(I);
END;
CALL PRINT$FIRST(100);
/* CHECK GCDS */
GCD: PROCEDURE (A, B) BYTE;
DECLARE (A, B, C) BYTE;
LOOP:
C = A;
A = B;
B = C MOD A;
IF B <> 0 THEN GO TO LOOP;
RETURN A;
END GCD;
DO I = 2 TO 1000;
IF GCD(S(I-1),S(I)) <> 1 THEN DO;
CALL PRINT(.'GCD NOT 1 AT: $');
CALL PRINT$NUMBER(I);
CALL BDOS(0,0);
END;
END;
CALL PRINT(.'ALL GCDS ARE 1$');
CALL BDOS(0,0);
EOF |
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
'🌑', '🌒', '🌓', '🌔', '🌕', '🌖', '🌗', '🌘'
| #Forth | Forth |
: rod
cr
begin
[char] \ emit 250 ms
13 emit [char] | emit 250 ms
13 emit [char] - emit 250 ms
13 emit [char] / emit 250 ms
13 emit
key?
until
;
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
'🌑', '🌒', '🌓', '🌔', '🌕', '🌖', '🌗', '🌘'
| #FreeBASIC | FreeBASIC | ' version 13-07-2018
' compile with: fbc -s console
Dim As String spinning_rod = "|/-" + Chr(92)
Dim As UInteger c
While InKey <> "" : Wend
While InKey = ""
Cls
Print
Print " hit any key to end program "; Chr(spinning_rod[c And 3])
c += 1
Sleep(250) ' in milliseconds
Wend
End |
http://rosettacode.org/wiki/Stack | Stack |
Data Structure
This illustrates a data structure, a means of storing data within a program.
You may see other such structures in the Data Structures category.
A stack is a container of elements with last in, first out access policy. Sometimes it also called LIFO.
The stack is accessed through its top.
The basic stack operations are:
push stores a new element onto the stack top;
pop returns the last pushed stack element, while removing it from the stack;
empty tests if the stack contains no elements.
Sometimes the last pushed stack element is made accessible for immutable access (for read) or mutable access (for write):
top (sometimes called peek to keep with the p theme) returns the topmost element without modifying the stack.
Stacks allow a very simple hardware implementation.
They are common in almost all processors.
In programming, stacks are also very popular for their way (LIFO) of resource management, usually memory.
Nested scopes of language objects are naturally implemented by a stack (sometimes by multiple stacks).
This is a classical way to implement local variables of a re-entrant or recursive subprogram. Stacks are also used to describe a formal computational framework.
See stack machine.
Many algorithms in pattern matching, compiler construction (e.g. recursive descent parsers), and machine learning (e.g. based on tree traversal) have a natural representation in terms of stacks.
Task
Create a stack supporting the basic operations: push, pop, empty.
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
| #beeswax | beeswax | instruction: _f
gstack: UInt64[0]• (at the beginning of a program lstack is initialized to [0 0 0] |
http://rosettacode.org/wiki/Speech_synthesis | Speech synthesis | Render the text This is an example of speech synthesis as speech.
Related task
using a speech engine to highlight words
| #Python | Python |
import pyttsx
engine = pyttsx.init()
engine.say("It was all a dream.")
engine.runAndWait()
|
http://rosettacode.org/wiki/Speech_synthesis | Speech synthesis | Render the text This is an example of speech synthesis as speech.
Related task
using a speech engine to highlight words
| #Racket | Racket |
#lang racket
(require racket/lazy-require)
(lazy-require [ffi/com (com-create-instance com-release com-invoke)])
(define (speak text)
(cond [(eq? 'windows (system-type))
(define c (com-create-instance "SAPI.SpVoice"))
(com-invoke c "Speak" text)
(com-release c)]
[(ormap find-executable-path '("say" "espeak"))
=> (λ(exe) (void (system* exe text)))]
[else (error 'speak "I'm speechless!")]))
(speak "This is an example of speech synthesis.")
|
http://rosettacode.org/wiki/Speech_synthesis | Speech synthesis | Render the text This is an example of speech synthesis as speech.
Related task
using a speech engine to highlight words
| #Raku | Raku | run 'espeak', 'This is an example of speech synthesis.'; |
http://rosettacode.org/wiki/Speech_synthesis | Speech synthesis | Render the text This is an example of speech synthesis as speech.
Related task
using a speech engine to highlight words
| #REXX | REXX | /*REXX program uses a command line interface to invoke Windows SAM for speech synthesis.*/
parse arg t /*get the (optional) text from the C.L.*/
if t='' then exit /*Nothing to say? Then exit program.*/
dquote= '"'
rate= 1 /*talk: -10 (slow) to 10 (fast). */
/* [↓] where the rubber meets the road*/
'NIRCMD' "speak text" dquote t dquote rate /*NIRCMD invokes Microsoft's Sam voice*/
/*stick a fork in it, we're all 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.
| #FOCAL | FOCAL | 01.10 S C=1;S S=1;S Q=1;S R=1;S N=1
01.20 I (N-30)1.3,1.3,1.8
01.30 S S=Q*Q
01.40 I (S-C)1.6,1.7,1.5
01.50 S R=R+1;S C=R*R*R;G 1.4
01.60 S N=N+1;T %4,S,!
01.70 S Q=Q+1;G 1.2
01.80 Q |
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.
| #Forth | Forth | : square dup * ;
: cube dup dup * * ;
: 30-non-cube-squares
0 1 1
begin 2 pick 30 < while
begin over over square swap cube > while
swap 1+ swap
repeat
over over square swap cube <> if
dup square . rot 1+ -rot
then
1+
repeat
2drop drop
;
30-non-cube-squares cr bye |
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
| #Perl | Perl | my @histogram = (0) x 10;
my $sum = 0;
my $sum_squares = 0;
my $n = $ARGV[0];
for (1..$n) {
my $current = rand();
$sum+= $current;
$sum_squares+= $current ** 2;
$histogram[$current * @histogram]+= 1;
}
my $mean = $sum / $n;
print "$n numbers\n",
"Mean: $mean\n",
"Stddev: ", sqrt(($sum_squares / $n) - ($mean ** 2)), "\n";
for my $i (0..$#histogram) {
printf "%.1f - %.1f : ", $i/@histogram, (1 + $i)/@histogram;
print "*" x (30 * $histogram[$i] * @histogram/$n); # 30 stars expected per row
print "\n";
} |
http://rosettacode.org/wiki/Square-free_integers | Square-free integers | Task
Write a function to test if a number is square-free.
A square-free is an integer which is divisible by no perfect square other
than 1 (unity).
For this task, only positive square-free numbers will be used.
Show here (on this page) all square-free integers (in a horizontal format) that are between:
1 ───► 145 (inclusive)
1 trillion ───► 1 trillion + 145 (inclusive)
(One trillion = 1,000,000,000,000)
Show here (on this page) the count of square-free integers from:
1 ───► one hundred (inclusive)
1 ───► one thousand (inclusive)
1 ───► ten thousand (inclusive)
1 ───► one hundred thousand (inclusive)
1 ───► one million (inclusive)
See also
the Wikipedia entry: square-free integer
| #Tcl | Tcl | proc isSquarefree {n} {
for {set d 2} {($d * $d) <= $n} {set d [expr {($d+1)|1}]} {
if {0 == ($n % $d)} {
set n [expr {$n / $d}]
if {0 == ($n % $d)} {
return 0 ;# no, just found dup divisor
}
}
}
return 1 ;# yes, no dup divisor found
}
proc unComma {str {comma ,}} {
return [string map [list $comma {}] $str]
}
proc showRange {lo hi} {
puts "Square-free integers in range $lo..$hi are:"
set lo [unComma $lo]
set hi [unComma $hi]
set L [string length $hi]
set perLine 5
while {($perLine * 2 * ($L+1)) <= 80} {
set perLine [expr {$perLine * 2}]
}
set k 0
for {set n $lo} {$n <= $hi} {incr n} {
if {[isSquarefree $n]} {
puts -nonewline " [format %${L}s $n]"
incr k
if {$k >= $perLine} {
puts "" ; set k 0
}
}
}
if {$k > 0} {
puts ""
}
}
proc showCount {lo hi} {
set rangtxt "$lo..$hi"
set lo [unComma $lo]
set hi [unComma $hi]
set k 0
for {set n $lo} {$n <= $hi} {incr n} {
incr k [isSquarefree $n]
}
puts "Counting [format %6s $k] square-free integers in range $rangtxt"
}
showRange 1 145
showRange 1,000,000,000,000 1,000,000,000,145
foreach H {100 1000 10000 100000 1000000} {
showCount 1 $H
}
|
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.
| #Scala | Scala | def stemAndLeaf(numbers: List[Int]) = {
val lineFormat = "%" + (numbers map (_.toString.length) max) + "d | %s"
val map = numbers groupBy (_ / 10)
for (stem <- numbers.min / 10 to numbers.max / 10) {
println(lineFormat format (stem, map.getOrElse(stem, Nil) map (_ % 10) sortBy identity mkString " "))
}
} |
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
| #Common_Lisp | Common Lisp | (defun split (string)
(loop :for prev := nil :then c
:for c :across string
:do (format t "~:[~;, ~]~c" (and prev (char/= c prev)) c)))
(split "gHHH5YY++///\\")
|
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
| #Cowgol | Cowgol | include "cowgol.coh";
sub split(in: [uint8], buf: [uint8]): (out: [uint8]) is
out := buf;
loop
[buf] := [in];
if [in] == 0 then break; end if;
if [in] != [@next in] and [@next in] != 0 then
[buf+1] := ',';
[buf+2] := ' ';
buf := buf+2;
end if;
buf := buf+1;
in := in+1;
end loop;
end sub;
var buf: uint8[32];
print(split("gHHH5YY++//\\", &buf[0]));
print_nl(); |
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.
| #PowerShell | PowerShell |
# An iterative approach
function iter_sb($count = 2000)
{
# Taken from RosettaCode GCD challenge
function Get-GCD ($x, $y)
{
if ($y -eq 0) { $x } else { Get-GCD $y ($x%$y) }
}
$answer = @(1,1)
$index = 1
while ($answer.Length -le $count)
{
$answer += $answer[$index] + $answer[$index - 1]
$answer += $answer[$index]
$index++
}
0..14 | foreach {$answer[$_]}
1..10 | foreach {'Index of {0}: {1}' -f $_, ($answer.IndexOf($_) + 1)}
'Index of 100: {0}' -f ($answer.IndexOf(100) + 1)
[bool] $gcd = $true
1..999 | foreach {$gcd = $gcd -and ((Get-GCD $answer[$_] $answer[$_ - 1]) -eq 1)}
'GCD = 1 for first 1000 members: {0}' -f $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
'🌑', '🌒', '🌓', '🌔', '🌕', '🌖', '🌗', '🌘'
| #GlovePIE | GlovePIE | debug="|"
wait 250 ms
debug="/"
wait 250 ms
debug="-"
wait 250 ms
debug="\"
wait 250 ms |
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
'🌑', '🌒', '🌓', '🌔', '🌕', '🌖', '🌗', '🌘'
| #Go | Go | package main
import (
"fmt"
"time"
)
func main() {
a := `|/-\`
fmt.Printf("\033[?25l") // hide the cursor
start := time.Now()
for {
for i := 0; i < 4; i++ {
fmt.Print("\033[2J") // clear terminal
fmt.Printf("\033[0;0H") // place cursor at top left corner
for j := 0; j < 80; j++ { // 80 character terminal width, say
fmt.Printf("%c", a[i])
}
time.Sleep(250 * time.Millisecond)
}
if time.Since(start).Seconds() >= 20.0 { // stop after 20 seconds, say
break
}
}
fmt.Print("\033[?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
| #BQN | BQN | Push ← ∾
∾
Pop ← ¯1⊸↓
¯1⊸↓
Empty ← 0=≠
0=≠
1‿2‿3 Push 4
⟨ 1 2 3 4 ⟩
Pop 1‿2‿3
⟨ 1 2 ⟩
Empty 1‿2‿3
0
Empty ⟨⟩
1 |
http://rosettacode.org/wiki/Speech_synthesis | Speech synthesis | Render the text This is an example of speech synthesis as speech.
Related task
using a speech engine to highlight words
| #Ring | Ring |
load "guilib.ring"
myApp = New qApp
{
Text = "Hello. This is an example of speech synthesis"
voice = new QTextToSpeech(null)
voice.Say(Text)
exec()
}
|
http://rosettacode.org/wiki/Speech_synthesis | Speech synthesis | Render the text This is an example of speech synthesis as speech.
Related task
using a speech engine to highlight words
| #Ring_2 | Ring |
load "guilib.ring"
load "stdlib.ring"
MyApp = New qApp {
win1 = new qWidget() {
setwindowtitle("Hello World")
setGeometry(100,100,370,250)
Text = "This is an example of speech synthesis"
Text = split(Text," ")
label1 = new qLabel(win1) {
settext("What is your name ?")
setGeometry(10,20,350,30)
setalignment(Qt_AlignHCenter)
}
btn1 = new qpushbutton(win1) {
setGeometry(10,200,100,30)
settext("Say Hello")
setclickevent("pHello()")
}
btn2 = new qpushbutton(win1) {
setGeometry(150,200,100,30)
settext("Close")
setclickevent("pClose()")
}
lineedit1 = new qlineedit(win1) {
setGeometry(10,100,350,30)
}
voice = new QTextToSpeech(win1) {
}
show()
}
exec()
}
Func pHello
lineedit1.settext( "Hello " + lineedit1.text())
for n = 1 to len(Text)
voice.Say(Text[n])
see Text[n] + nl
next
Func pClose
MyApp.quit()
|
http://rosettacode.org/wiki/Speech_synthesis | Speech synthesis | Render the text This is an example of speech synthesis as speech.
Related task
using a speech engine to highlight words
| #Ruby | Ruby | module OperatingSystem
require 'rbconfig'
module_function
def operating_system
case RbConfig::CONFIG["host_os"]
when /linux/i
:linux
when /cygwin|mswin|mingw|windows/i
:windows
when /darwin/i
:mac
when /solaris/i
:solaris
else
nil
end
end
def linux?; operating_system == :linux; end
def windows?; operating_system == :windows; end
def mac?; operating_system == :mac; end
end |
http://rosettacode.org/wiki/Speech_synthesis | Speech synthesis | Render the text This is an example of speech synthesis as speech.
Related task
using a speech engine to highlight words
| #Scala | Scala | import javax.speech.Central
import javax.speech.synthesis.{Synthesizer, SynthesizerModeDesc}
object ScalaSpeaker extends App {
def speech(text: String) = {
if (!text.trim.isEmpty) {
val VOICENAME = "kevin16"
System.setProperty("freetts.voices", "com.sun.speech.freetts.en.us.cmu_us_kal.KevinVoiceDirectory")
Central.registerEngineCentral("com.sun.speech.freetts.jsapi.FreeTTSEngineCentral")
val synth = Central.createSynthesizer(null)
synth.allocate()
val desc = synth.getEngineModeDesc match {case g2: SynthesizerModeDesc => g2}
synth.getSynthesizerProperties.setVoice(desc.getVoices.find(_.toString == VOICENAME).get)
synth.speakPlainText(text, null)
synth.waitEngineState(Synthesizer.QUEUE_EMPTY)
synth.deallocate()
}
}
speech( """Thinking of Holland
|I see broad rivers
|slowly chuntering
|through endless lowlands,
|rows of implausibly
|airy poplars
|standing like tall plumes
|against the horizon;
|and sunk in the unbounded
|vastness of space
|homesteads and boweries
|dotted across the land,
|copses, villages,
|couchant towers,
|churches and elm-trees,
|bound in one great unity.
|There the sky hangs low,
|and steadily the sun
|is smothered in a greyly
|iridescent smirr,
|and in every province
|the voice of water
|with its lapping disasters
|is feared and hearkened.""".stripMargin)
} |
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.
| #FreeBASIC | FreeBASIC | function is_pow(n as integer, q as integer) as boolean
'tests if the number n is the q'th power of some other integer
dim as integer r = int( n^(1.0/q) )
for i as integer = r-1 to r+1 'there might be a bit of floating point nonsense, so test adjacent numbers also
if i^q = n then return true
next i
return false
end function
dim as integer count = 0, n = 2
do
if is_pow( n, 2 ) and not is_pow( n, 3 ) then
print n;" ";
count += 1
end if
n += 1
loop until count = 30
print
count = 0
n = 2
do
if is_pow( n, 2 ) and is_pow( n, 3 ) then
print n;" ";
count += 1
end if
n += 1
loop until count = 3
print |
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
| #Phix | Phix | function generate_statistics(integer n)
sequence hist = repeat(0,10)
atom sum_r = 0,
sum_squares = 0.0
for i=1 to n do
atom r = rnd()
sum_r += r
sum_squares += r*r
hist[floor(10*r)+1] += 1
end for
atom mean = sum_r / n
atom stddev = sqrt((sum_squares / n) - mean*mean)
return {n, mean, stddev, hist}
end function
procedure display_statistics(sequence x)
atom n, mean, stddev
sequence hist
{n, mean, stddev, hist} = x
printf(1,"-- Stats for sample size %d\n",{n})
printf(1,"mean: %g\n",{mean})
printf(1,"sdev: %g\n",{stddev})
for i=1 to length(hist) do
integer cnt = hist[i]
string bars = repeat('=',floor(cnt*300/n))
printf(1,"%.1f: %s %d\n",{i/10,bars,cnt})
end for
end procedure
for n=2 to 5 do
display_statistics(generate_statistics(power(10,n+(n=5))))
end for
|
http://rosettacode.org/wiki/Square-free_integers | Square-free integers | Task
Write a function to test if a number is square-free.
A square-free is an integer which is divisible by no perfect square other
than 1 (unity).
For this task, only positive square-free numbers will be used.
Show here (on this page) all square-free integers (in a horizontal format) that are between:
1 ───► 145 (inclusive)
1 trillion ───► 1 trillion + 145 (inclusive)
(One trillion = 1,000,000,000,000)
Show here (on this page) the count of square-free integers from:
1 ───► one hundred (inclusive)
1 ───► one thousand (inclusive)
1 ───► ten thousand (inclusive)
1 ───► one hundred thousand (inclusive)
1 ───► one million (inclusive)
See also
the Wikipedia entry: square-free integer
| #Visual_Basic_.NET | Visual Basic .NET | Module Module1
Function Sieve(limit As Long) As List(Of Long)
Dim primes As New List(Of Long) From {2}
Dim c(limit + 1) As Boolean
Dim p = 3L
While True
Dim p2 = p * p
If p2 > limit Then
Exit While
End If
For i = p2 To limit Step 2 * p
c(i) = True
Next
While True
p += 2
If Not c(p) Then
Exit While
End If
End While
End While
For i = 3 To limit Step 2
If Not c(i) Then
primes.Add(i)
End If
Next
Return primes
End Function
Function SquareFree(from As Long, to_ As Long) As List(Of Long)
Dim limit = CType(Math.Sqrt(to_), Long)
Dim primes = Sieve(limit)
Dim results As New List(Of Long)
Dim i = from
While i <= to_
For Each p In primes
Dim p2 = p * p
If p2 > i Then
Exit For
End If
If (i Mod p2) = 0 Then
i += 1
Continue While
End If
Next
results.Add(i)
i += 1
End While
Return results
End Function
ReadOnly TRILLION As Long = 1_000_000_000_000
Sub Main()
Console.WriteLine("Square-free integers from 1 to 145:")
Dim sf = SquareFree(1, 145)
For index = 0 To sf.Count - 1
Dim v = sf(index)
If index > 1 AndAlso (index Mod 20) = 0 Then
Console.WriteLine()
End If
Console.Write("{0,4}", v)
Next
Console.WriteLine()
Console.WriteLine()
Console.WriteLine("Square-free integers from {0} to {1}:", TRILLION, TRILLION + 145)
sf = SquareFree(TRILLION, TRILLION + 145)
For index = 0 To sf.Count - 1
Dim v = sf(index)
If index > 1 AndAlso (index Mod 5) = 0 Then
Console.WriteLine()
End If
Console.Write("{0,14}", v)
Next
Console.WriteLine()
Console.WriteLine()
Console.WriteLine("Number of square-free integers:")
For Each to_ In {100, 1_000, 10_000, 100_000, 1_000_000}
Console.WriteLine(" from 1 to {0} = {1}", to_, SquareFree(1, to_).Count)
Next
End Sub
End Module |
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.
| #Seed7 | Seed7 | $ include "seed7_05.s7i";
const proc: leafPlot (in var array integer: x) is func
local
var integer: i is 0;
var integer: j is 0;
var integer: d is 0;
begin
x := sort(x);
i := x[1] div 10 - 1;
for key j range x do
d := x[j] div 10;
while d > i do
if j <> 1 then
writeln;
end if;
incr(i);
write(i lpad 3 <& " |");
end while;
write(" " <& x[j] rem 10);
end for;
writeln;
end func;
const proc: main is func
local
const array integer: data is [] (
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);
begin
leafPlot(data);
end func; |
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
| #D | D | import std.stdio;
void main() {
auto source = "gHHH5YY++///\\";
char prev = source[0];
foreach(ch; source) {
if (prev != ch) {
prev = ch;
write(", ");
}
write(ch);
}
writeln();
} |
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
| #Dyalect | Dyalect | func String.SmartSplit() {
var c
var str = ""
var last = this.Length() - 1
for n in 0..last {
if c && this[n] != c {
str += ", "
}
c = this[n]
str += c
}
str
}
print("gHHH5YY++///\\".SmartSplit()) |
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.
| #PureBasic | PureBasic | EnableExplicit
Define.i i
If OpenConsole("")
PrintN("Stern-Brocot_sequence")
Else
End 1
EndIf
Procedure.i f(n.i)
If n<2
ProcedureReturn n
ElseIf n&1
ProcedureReturn f(n/2)+f(n/2+1)
Else
ProcedureReturn f(n/2)
EndIf
EndProcedure
Procedure.i gcd(a.i,b.i)
If b : ProcedureReturn gcd(b,a%b) : EndIf
ProcedureReturn a
EndProcedure
Procedure.i ind(m.i)
Define.i i=1
While f(i)<>m : i+1 : Wend
ProcedureReturn i
EndProcedure
Print("First 15 elements: ")
For i=1 To 15
Print(Str(f(i))+Space(3))
Next
PrintN(~"\n")
For i=1 To 10
PrintN(RSet(Str(i),3)+" is at pos. #"+Str(ind(i)))
Next
PrintN("100 is at pos. #"+Str(ind(100)))
PrintN("")
i=1
While i<1000 And gcd(f(i),f(i+1))=1 : i+1 : Wend
If i=1000
PrintN("All GCDs are 1.")
Else
PrintN("GCD of "+Str(i)+" and "+Str(i+1)+" is not 1")
EndIf
Input() |
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
'🌑', '🌒', '🌓', '🌔', '🌕', '🌖', '🌗', '🌘'
| #Haskell | Haskell | import Control.Concurrent (threadDelay)
import Control.Exception (bracket_)
import Control.Monad (forM_)
import System.Console.Terminfo
import System.IO (hFlush, stdout)
-- Use the terminfo database to write the terminal-specific characters
-- for the given capability.
runCapability :: Terminal -> String -> IO ()
runCapability term cap =
forM_ (getCapability term (tiGetOutput1 cap)) (runTermOutput term)
-- Control the visibility of the cursor.
cursorOff, cursorOn :: Terminal -> IO ()
cursorOff term = runCapability term "civis"
cursorOn term = runCapability term "cnorm"
-- Print the spinning cursor.
spin :: IO ()
spin = forM_ (cycle "|/-\\") $ \c ->
putChar c >> putChar '\r' >>
hFlush stdout >> threadDelay 250000
main :: IO ()
main = do
putStrLn "Spinning rod demo. Hit ^C to stop it.\n"
term <- setupTermFromEnv
bracket_ (cursorOff term) (cursorOn term) spin |
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
| #Bracmat | Bracmat | ( ( stack
= (S=)
(push=.(!arg.!(its.S)):?(its.S))
( pop
= top.!(its.S):(%?top.?(its.S))&!top
)
(top=top.!(its.S):(%?top.?)&!top)
(empty=.!(its.S):)
)
& new$stack:?Stack
& (Stack..push)$(2*a)
& (Stack..push)$pi
& (Stack..push)$
& (Stack..push)$"to be or"
& (Stack..push)$"not to be"
& out$((Stack..pop)$|"Cannot pop (a)")
& out$((Stack..top)$|"Cannot pop (b)")
& out$((Stack..pop)$|"Cannot pop (c)")
& out$((Stack..pop)$|"Cannot pop (d)")
& out$((Stack..pop)$|"Cannot pop (e)")
& out$((Stack..pop)$|"Cannot pop (f)")
& out$((Stack..pop)$|"Cannot pop (g)")
& out$((Stack..pop)$|"Cannot pop (h)")
& out
$ ( str
$ ( "Stack is "
((Stack..empty)$&|not)
" empty"
)
)
&
); |
http://rosettacode.org/wiki/Speech_synthesis | Speech synthesis | Render the text This is an example of speech synthesis as speech.
Related task
using a speech engine to highlight words
| #Sidef | Sidef | func text2speech(text, lang='en') {
Sys.run("espeak -v #{lang} -w /dev/stdout #{text.escape} | aplay");
}
text2speech("This is an example of speech synthesis."); |
http://rosettacode.org/wiki/Speech_synthesis | Speech synthesis | Render the text This is an example of speech synthesis as speech.
Related task
using a speech engine to highlight words
| #Swift | Swift | import Foundation
let task = NSTask()
task.launchPath = "/usr/bin/say"
task.arguments = ["This is an example of speech synthesis."]
task.launch() |
http://rosettacode.org/wiki/Speech_synthesis | Speech synthesis | Render the text This is an example of speech synthesis as speech.
Related task
using a speech engine to highlight words
| #Tcl | Tcl | exec festival --tts << "This is an example of speech synthesis." |
http://rosettacode.org/wiki/Speech_synthesis | Speech synthesis | Render the text This is an example of speech synthesis as speech.
Related task
using a speech engine to highlight words
| #UNIX_Shell | UNIX Shell | #!/bin/sh
espeak "This is an example of speech synthesis." |
http://rosettacode.org/wiki/Speech_synthesis | Speech synthesis | Render the text This is an example of speech synthesis as speech.
Related task
using a speech engine to highlight words
| #VBScript | VBScript |
Dim message, sapi
message = "This is an example of speech synthesis."
Set sapi = CreateObject("sapi.spvoice")
sapi.Speak message
|
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.
| #Go | Go | package main
import (
"fmt"
"math"
)
func main() {
for n, count := 1, 0; count < 30; n++ {
sq := n * n
cr := int(math.Cbrt(float64(sq)))
if cr*cr*cr != sq {
count++
fmt.Println(sq)
} else {
fmt.Println(sq, "is square and cube")
}
}
} |
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.
| #Haskell | Haskell | {-# LANGUAGE TupleSections #-}
import Control.Monad (join)
import Data.List (partition, sortOn)
import Data.Ord (comparing)
------------------- SQUARE BUT NOT CUBE ------------------
isCube :: Int -> Bool
isCube n = n == round (fromIntegral n ** (1 / 3)) ^ 3
both, only :: [Int]
(both, only) = partition isCube $ join (*) <$> [1 ..]
--------------------------- TEST -------------------------
main :: IO ()
main =
(putStrLn . unlines) $
uncurry ((<>) . show)
<$> sortOn
fst
( ((," (also cube)") <$> take 3 both)
<> ((,"") <$> take 30 only)
) |
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
| #PicoLisp | PicoLisp |
(seed (time))
(scl 8)
(de statistics (Cnt . Prg)
(prinl Cnt " numbers")
(let (Sum 0 Sqr 0 Hist (need 10 NIL 0))
(do Cnt
(let N (run Prg 1) # Get next number
(inc 'Sum N)
(inc 'Sqr (*/ N N 1.0))
(inc (nth Hist (inc (/ N 0.1)))) ) )
(let M (*/ Sum Cnt)
(prinl "Mean: " (round M))
(prinl "StdDev: "
(round
(sqrt
(- (*/ Sqr Cnt) (*/ M M 1.0))
1.0 ) ) ) )
(for (I . H) Hist
(prin (format I 1) " ")
(do (*/ H 400 Cnt) (prin '=))
(prinl) ) ) )
(for I (2 4 6)
(statistics (** 10 I)
(rand 0 (dec 1.0)) )
(prinl) )
|
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
| #PL.2FI | PL/I | stat: procedure options (main); /* 21 May 2014 */
stats: procedure (values, mean, standard_deviation);
declare (values(*), mean, standard_deviation) float;
declare n fixed binary (31) initial ( (hbound(values,1)) );
mean = sum(values)/n;
standard_deviation = sqrt( sum(values - mean)**2 / n);
end stats;
declare values (*) float controlled;
declare (mean, stddev) float;
declare bin(0:9) fixed;
declare (i, n) fixed binary (31);
do n = 100, 1000, 10000, 100000;
allocate values(n);
values = random();
call stats (values, mean, stddev);
if n = 100 then
do;
bin = 0;
do i = 1 to 100;
bin(10*values(i)) += 1;
end;
put skip list ('Histogram for 100 values:');
do i = 0 to 9; /* display histogram */
put skip list (repeat('.', bin(i)) );
end;
end;
put skip list (n || ' values: mean=' || mean, 'stddev=' || stddev);
free values;
end;
end stat; |
http://rosettacode.org/wiki/Square-free_integers | Square-free integers | Task
Write a function to test if a number is square-free.
A square-free is an integer which is divisible by no perfect square other
than 1 (unity).
For this task, only positive square-free numbers will be used.
Show here (on this page) all square-free integers (in a horizontal format) that are between:
1 ───► 145 (inclusive)
1 trillion ───► 1 trillion + 145 (inclusive)
(One trillion = 1,000,000,000,000)
Show here (on this page) the count of square-free integers from:
1 ───► one hundred (inclusive)
1 ───► one thousand (inclusive)
1 ───► ten thousand (inclusive)
1 ───► one hundred thousand (inclusive)
1 ───► one million (inclusive)
See also
the Wikipedia entry: square-free integer
| #Wren | Wren | import "/fmt" for Fmt
var isSquareFree = Fn.new { |n|
var i = 2
while (i * i <= n) {
if (n%(i*i) == 0) return false
i = (i > 2) ? i + 2 : i + 1
}
return true
}
var ranges = [ [1..145, 3, 20], [1e12..1e12+145, 12, 5] ]
for (r in ranges) {
System.print("The square-free integers between %(r[0].min) and %(r[0].max) inclusive are:")
var count = 0
for (i in r[0]) {
if (isSquareFree.call(i)) {
count = count + 1
System.write("%(Fmt.d(r[1], i)) ")
if (count %r[2] == 0) System.print()
}
}
System.print("\n")
}
System.print("Counts of square-free integers:")
var count = 0
var lims = [0, 100, 1000, 1e4, 1e5, 1e6]
for (i in 1...lims.count) {
System.write(" from 1 to (inclusive) %(Fmt.d(-7, lims[i])) = ")
for (j in lims[i-1]+1..lims[i]) {
if (isSquareFree.call(j)) count = count + 1
}
System.print(count)
} |
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.
| #Sidef | Sidef | var data = %i(
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
).sort;
var stem_unit = 10;
var h = data.group_by { |i| i / stem_unit -> int }
var rng = RangeNum(h.keys.map{.to_i}.minmax);
var stem_format = "%#{rng.min.len.max(rng.max.len)}d";
rng.each { |stem|
var leafs = (h{stem} \\ [])
say(stem_format % stem, ' | ', leafs.map { _ % stem_unit }.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
| #EasyLang | EasyLang | a$ = "gHHH5YY++///\\"
a$[] = strchars a$
cp$ = a$[0]
for c$ in a$[]
if c$ <> cp$
s$ &= ", "
cp$ = c$
.
s$ &= c$
.
print s$ |
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
| #Elixir | Elixir | split = fn str ->
IO.puts " input string: #{str}"
String.graphemes(str)
|> Enum.chunk_by(&(&1))
|> Enum.map_join(", ", &Enum.join &1)
|> fn s -> IO.puts "output string: #{s}" end.()
end
split.("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.
| #Python | Python | def stern_brocot(predicate=lambda series: len(series) < 20):
"""\
Generates members of the stern-brocot series, in order, returning them when the predicate becomes false
>>> print('The first 10 values:',
stern_brocot(lambda series: len(series) < 10)[:10])
The first 10 values: [1, 1, 2, 1, 3, 2, 3, 1, 4, 3]
>>>
"""
sb, i = [1, 1], 0
while predicate(sb):
sb += [sum(sb[i:i + 2]), sb[i + 1]]
i += 1
return sb
if __name__ == '__main__':
from fractions import gcd
n_first = 15
print('The first %i values:\n ' % n_first,
stern_brocot(lambda series: len(series) < n_first)[:n_first])
print()
n_max = 10
for n_occur in list(range(1, n_max + 1)) + [100]:
print('1-based index of the first occurrence of %3i in the series:' % n_occur,
stern_brocot(lambda series: n_occur not in series).index(n_occur) + 1)
# The following would be much faster. Note that new values always occur at odd indices
# len(stern_brocot(lambda series: n_occur != series[-2])) - 1)
print()
n_gcd = 1000
s = stern_brocot(lambda series: len(series) < n_gcd)[:n_gcd]
assert all(gcd(prev, this) == 1
for prev, this in zip(s, s[1:])), 'A fraction from adjacent terms is reducible' |
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
'🌑', '🌒', '🌓', '🌔', '🌕', '🌖', '🌗', '🌘'
| #Java | Java | public class SpinningRod
{
public static void main(String[] args) throws InterruptedException {
String a = "|/-\\";
System.out.print("\033[2J"); // hide the cursor
long start = System.currentTimeMillis();
while (true) {
for (int i = 0; i < 4; i++) {
System.out.print("\033[2J"); // clear terminal
System.out.print("\033[0;0H"); // place cursor at top left corner
for (int j = 0; j < 80; j++) { // 80 character terminal width, say
System.out.print(a.charAt(i));
}
Thread.sleep(250);
}
long now = System.currentTimeMillis();
// stop after 20 seconds, say
if (now - start >= 20000) break;
}
System.out.print("\033[?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
| #Brat | Brat | stack = []
stack.push 1
stack.push 2
stack.push 3
until { stack.empty? } { p stack.pop } |
http://rosettacode.org/wiki/Speech_synthesis | Speech synthesis | Render the text This is an example of speech synthesis as speech.
Related task
using a speech engine to highlight words
| #Wren | Wren | /* speech_synthesis.wren */
class C {
foreign static getInput(maxSize)
foreign static espeak(s)
}
System.write("Enter something to say (up to 100 characters) : ")
var s = C.getInput(100)
C.espeak(s) |
http://rosettacode.org/wiki/Speech_synthesis | Speech synthesis | Render the text This is an example of speech synthesis as speech.
Related task
using a speech engine to highlight words
| #Zoomscript | Zoomscript | speak "This is an example of speech synthesis." |
http://rosettacode.org/wiki/Speech_synthesis | Speech synthesis | Render the text This is an example of speech synthesis as speech.
Related task
using a speech engine to highlight words
| #ZX_Spectrum_Basic | ZX Spectrum Basic | 10 LET s$="(th)is is an exampul of sp(ee)(ch) sin(th)esis":PAUSE 1 |
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
| #AutoHotkey | AutoHotkey | OrdinalNumber(n){
OrdinalNumber := {"one":"first", "two":"second", "three":"third", "five":"fifth", "eight":"eighth", "nine":"ninth", "twelve": "twelfth"}
RegExMatch(n, "\w+$", m)
return (OrdinalNumber[m] ? RegExReplace(n, "\w+$", OrdinalNumber[m]) : n "th")
}
Spell(n) { ; recursive function to spell out the name of a max 36 digit integer, after leading 0s removed
Static p1=" thousand ",p2=" million ",p3=" billion ",p4=" trillion ",p5=" quadrillion ",p6=" quintillion "
, p7=" sextillion ",p8=" septillion ",p9=" octillion ",p10=" nonillion ",p11=" decillion "
, t2="twenty",t3="thirty",t4="forty",t5="fifty",t6="sixty",t7="seventy",t8="eighty",t9="ninety"
, o0="zero",o1="one",o2="two",o3="three",o4="four",o5="five",o6="six",o7="seven",o8="eight"
, o9="nine",o10="ten",o11="eleven",o12="twelve",o13="thirteen",o14="fourteen",o15="fifteen"
, o16="sixteen",o17="seventeen",o18="eighteen",o19="nineteen"
n :=RegExReplace(n,"^0+(\d)","$1") ; remove leading 0s from n
If (11 < d := (StrLen(n)-1)//3) ; #of digit groups of 3
Return "Number too big"
If (d) ; more than 3 digits 1000+
Return Spell(SubStr(n,1,-3*d)) p%d% ((s:=SubStr(n,1-3*d)) ? ", " Spell(s) : "")
i := SubStr(n,1,1)
If (n > 99) ; 3 digits 100..999
Return o%i% " hundred" ((s:=SubStr(n,2)) ? " and " Spell(s) : "")
If (n > 19) ; n = 20..99
Return t%i% ((o:=SubStr(n,2)) ? "-" o%o% : "")
Return o%n% ; n = 0..19
}
PrettyNumber(n) { ; inserts thousands separators into a number string
Return RegExReplace( RegExReplace(n,"^0+(\d)","$1"), "\G\d+?(?=(\d{3})+(?:\D|$))", "$0,")
} |
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.
| #IS-BASIC | IS-BASIC | 100 PROGRAM "Square.bas"
110 LET SQNOTCB,SQANDCB,SQNUM,CBNUM,CBN,SQN,D1=0:LET SQD,D2=1
120 DO
130 LET SQN=SQN+1:LET SQNUM=SQNUM+SQD:LET SQD=SQD+2
140 IF SQNUM>CBNUM THEN
150 LET CBN=CBN+1:LET CBNUM=CBNUM+D2
160 LET D1=D1+6:LET D2=D2+D1
170 END IF
180 IF SQNUM<>CBNUM THEN
190 PRINT SQNUM:LET SQNOTCB=SQNOTCB+1
200 ELSE
210 PRINT SQNUM,SQN;"*";SQN;"=";CBN;"*";CBN;"*";CBN
220 LET SQANDCB=SQANDCB+1
230 END IF
240 LOOP UNTIL SQNOTCB>=30
250 PRINT SQANDCB;"where numbers are square and cube." |
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.
| #J | J | isSqrNotCubeofInt=: (*. -.)/@(= <.)@(2 3 %:/ ])
getN_Indicies=: adverb def '[ ({. I.) [ (] , [: u (i.200) + #@])^:(> +/)^:_ u@]' |
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
| #PureBasic | PureBasic | Procedure.f randomf()
#RNG_max_resolution = 2147483647
ProcedureReturn Random(#RNG_max_resolution) / #RNG_max_resolution
EndProcedure
Procedure sample(n)
Protected i, nBins, binNumber, tickMarks, maxBinValue
Protected.f sum, sumSq, mean
Dim dat.f(n)
For i = 1 To n
dat(i) = randomf()
Next
;show mean, standard deviation
For i = 1 To n
sum + dat(i)
sumSq + dat(i) * dat(i)
Next i
PrintN(Str(n) + " data terms used.")
mean = sum / n
PrintN("Mean =" + StrF(mean))
PrintN("Stddev =" + StrF((sumSq / n) - Sqr(mean * mean)))
;show histogram
nBins = 10
Dim bins(nBins)
For i = 1 To n
binNumber = Int(nBins * dat(i))
bins(binNumber) + 1
Next
maxBinValue = 1
For i = 0 To nBins
If bins(i) > maxBinValue
maxBinValue = bins(i)
EndIf
Next
#normalizedMaxValue = 70
For binNumber = 0 To nBins
tickMarks = Int(bins(binNumber) * #normalizedMaxValue / maxBinValue)
PrintN(ReplaceString(Space(tickMarks), " ", "#"))
Next
PrintN("")
EndProcedure
If OpenConsole()
sample(100)
sample(1000)
sample(10000)
Print(#CRLF$ + #CRLF$ + "Press ENTER to exit"): Input()
CloseConsole()
EndIf |
http://rosettacode.org/wiki/Square-free_integers | Square-free integers | Task
Write a function to test if a number is square-free.
A square-free is an integer which is divisible by no perfect square other
than 1 (unity).
For this task, only positive square-free numbers will be used.
Show here (on this page) all square-free integers (in a horizontal format) that are between:
1 ───► 145 (inclusive)
1 trillion ───► 1 trillion + 145 (inclusive)
(One trillion = 1,000,000,000,000)
Show here (on this page) the count of square-free integers from:
1 ───► one hundred (inclusive)
1 ───► one thousand (inclusive)
1 ───► ten thousand (inclusive)
1 ───► one hundred thousand (inclusive)
1 ───► one million (inclusive)
See also
the Wikipedia entry: square-free integer
| #zkl | zkl | const Limit=1 + (1e12 + 145).sqrt(); // 1000001 because it fits this task
var [const]
BI=Import.lib("zklBigNum"), // GNU Multiple Precision Arithmetic Library
primes=List.createLong(Limit); // one big allocate (vs lots of allocs)
// GMP provide nice way to generate primes, nextPrime is in-place
p:=BI(0); while(p<Limit){ primes.append(p.nextPrime().toInt()); } // 78,499 primes
fcn squareFree(start,end,save=False){ //-->(cnt,list|n)
sink := Sink(if(save) List else Void); // Sink(Void) is one item sink
cnt, numPrimes := 0, (end - start).toFloat().sqrt().toInt() - 1;
foreach n in ([start..end]){
foreach j in ([0..numPrimes]){
p,p2 := primes[j], p*p;
if(p2>n) break;
if(n%p2==0) continue(2); // -->foreach n
}
sink.write(n); cnt+=1
}
return(cnt,sink.close());
} |
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.
| #Stata | Stata | . clear all
. input x
12
127
28
...
31
116
146
end
. stem x
Stem-and-leaf plot for x
0* | 77
1* | 2388
2* | 357777778899
3* | 011112345677789
4* | 001222233344456788
5* | 23788
6* | 138
7* | 1
8* |
9* | 69
10* | 4555567999
11* | 13333444555666677778899
12* | 00112234445556777788
13* | 1239
14* | 16 |
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
| #F.23 | F# | open System.Text.RegularExpressions
let splitRuns s = Regex("""(.)\1*""").Matches(s) |> Seq.cast<Match> |> Seq.map (fun m -> m.Value) |> Seq.toList
printfn "%A" (splitRuns """gHHH5YY++///\""") |
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
| #Factor | Factor | USE: splitting.monotonic
"gHHH5YY++///\\"
"aaabbccccdeeff" [ [ = ] monotonic-split ", " join print ] bi@ |
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.
| #Quackery | Quackery | [ [ dup while
tuck mod again ]
drop abs ] is gcd ( n n --> n )
[ 2dup peek
dip [ 1+ 2dup peek ]
over + swap join
swap dip join ] is two-terms ( [ n --> [ n )
' [ 1 1 ] 0
8 times two-terms
over 15 split drop
witheach [ echo sp ] cr
[ two-terms
over -2 peek 100 = until ]
drop
10 times
[ i^ 1+ over find 1+ echo sp ] cr
dup size 1 - echo cr
false swap
behead swap witheach
[ tuck gcd 1 != if
[ dip not conclude ] ]
drop iff
[ say "Reducible pair found." ]
else
[ say "No reducible pairs found." ] |
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
'🌑', '🌒', '🌓', '🌔', '🌕', '🌖', '🌗', '🌘'
| #JavaScript | JavaScript |
const rod = (function rod() {
const chars = "|/-\\";
let i=0;
return function() {
i= (i+1) % 4;
// We need to use process.stdout.write since console.log automatically adds a \n to the end of lines
process.stdout.write(` ${chars[i]}\r`);
}
})();
setInterval(rod, 250);
|
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
'🌑', '🌒', '🌓', '🌔', '🌕', '🌖', '🌗', '🌘'
| #Julia | Julia | while true
for rod in "\|/-" # this needs to be a string, a char literal cannot be iterated over
print(rod,'\r')
sleep(0.25)
end
end
|
http://rosettacode.org/wiki/Stack | Stack |
Data Structure
This illustrates a data structure, a means of storing data within a program.
You may see other such structures in the Data Structures category.
A stack is a container of elements with last in, first out access policy. Sometimes it also called LIFO.
The stack is accessed through its top.
The basic stack operations are:
push stores a new element onto the stack top;
pop returns the last pushed stack element, while removing it from the stack;
empty tests if the stack contains no elements.
Sometimes the last pushed stack element is made accessible for immutable access (for read) or mutable access (for write):
top (sometimes called peek to keep with the p theme) returns the topmost element without modifying the stack.
Stacks allow a very simple hardware implementation.
They are common in almost all processors.
In programming, stacks are also very popular for their way (LIFO) of resource management, usually memory.
Nested scopes of language objects are naturally implemented by a stack (sometimes by multiple stacks).
This is a classical way to implement local variables of a re-entrant or recursive subprogram. Stacks are also used to describe a formal computational framework.
See stack machine.
Many algorithms in pattern matching, compiler construction (e.g. recursive descent parsers), and machine learning (e.g. based on tree traversal) have a natural representation in terms of stacks.
Task
Create a stack supporting the basic operations: push, pop, empty.
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
| #C | C | #include <stdio.h>
#include <stdlib.h>
/* to read expanded code, run through cpp | indent -st */
#define DECL_STACK_TYPE(type, name) \
typedef struct stk_##name##_t{type *buf; size_t alloc,len;}*stk_##name; \
stk_##name stk_##name##_create(size_t init_size) { \
stk_##name s; if (!init_size) init_size = 4; \
s = malloc(sizeof(struct stk_##name##_t)); \
if (!s) return 0; \
s->buf = malloc(sizeof(type) * init_size); \
if (!s->buf) { free(s); return 0; } \
s->len = 0, s->alloc = init_size; \
return s; } \
int stk_##name##_push(stk_##name s, type item) { \
type *tmp; \
if (s->len >= s->alloc) { \
tmp = realloc(s->buf, s->alloc*2*sizeof(type)); \
if (!tmp) return -1; s->buf = tmp; \
s->alloc *= 2; } \
s->buf[s->len++] = item; \
return s->len; } \
type stk_##name##_pop(stk_##name s) { \
type tmp; \
if (!s->len) abort(); \
tmp = s->buf[--s->len]; \
if (s->len * 2 <= s->alloc && s->alloc >= 8) { \
s->alloc /= 2; \
s->buf = realloc(s->buf, s->alloc * sizeof(type));} \
return tmp; } \
void stk_##name##_delete(stk_##name s) { \
free(s->buf); free(s); }
#define stk_empty(s) (!(s)->len)
#define stk_size(s) ((s)->len)
DECL_STACK_TYPE(int, int)
int main(void)
{
int i;
stk_int stk = stk_int_create(0);
printf("pushing: ");
for (i = 'a'; i <= 'z'; i++) {
printf(" %c", i);
stk_int_push(stk, i);
}
printf("\nsize now: %d", stk_size(stk));
printf("\nstack is%s empty\n", stk_empty(stk) ? "" : " not");
printf("\npoppoing:");
while (stk_size(stk))
printf(" %c", stk_int_pop(stk));
printf("\nsize now: %d", stk_size(stk));
printf("\nstack is%s empty\n", stk_empty(stk) ? "" : " not");
/* stk_int_pop(stk); <-- will abort() */
stk_int_delete(stk);
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
| #C | C | #include <stdbool.h>
#include <stdio.h>
#include <stdint.h>
#include <glib.h>
typedef uint64_t integer;
typedef struct number_names_tag {
const char* cardinal;
const char* ordinal;
} number_names;
const number_names small[] = {
{ "zero", "zeroth" }, { "one", "first" }, { "two", "second" },
{ "three", "third" }, { "four", "fourth" }, { "five", "fifth" },
{ "six", "sixth" }, { "seven", "seventh" }, { "eight", "eighth" },
{ "nine", "ninth" }, { "ten", "tenth" }, { "eleven", "eleventh" },
{ "twelve", "twelfth" }, { "thirteen", "thirteenth" },
{ "fourteen", "fourteenth" }, { "fifteen", "fifteenth" },
{ "sixteen", "sixteenth" }, { "seventeen", "seventeenth" },
{ "eighteen", "eighteenth" }, { "nineteen", "nineteenth" }
};
const number_names tens[] = {
{ "twenty", "twentieth" }, { "thirty", "thirtieth" },
{ "forty", "fortieth" }, { "fifty", "fiftieth" },
{ "sixty", "sixtieth" }, { "seventy", "seventieth" },
{ "eighty", "eightieth" }, { "ninety", "ninetieth" }
};
typedef struct named_number_tag {
const char* cardinal;
const char* ordinal;
integer number;
} named_number;
const named_number named_numbers[] = {
{ "hundred", "hundredth", 100 },
{ "thousand", "thousandth", 1000 },
{ "million", "millionth", 1000000 },
{ "billion", "billionth", 1000000000 },
{ "trillion", "trillionth", 1000000000000 },
{ "quadrillion", "quadrillionth", 1000000000000000ULL },
{ "quintillion", "quintillionth", 1000000000000000000ULL }
};
const char* get_small_name(const number_names* n, bool ordinal) {
return ordinal ? n->ordinal : n->cardinal;
}
const char* get_big_name(const named_number* n, bool ordinal) {
return ordinal ? n->ordinal : n->cardinal;
}
const named_number* get_named_number(integer n) {
const size_t names_len = sizeof(named_numbers)/sizeof(named_numbers[0]);
for (size_t i = 0; i + 1 < names_len; ++i) {
if (n < named_numbers[i + 1].number)
return &named_numbers[i];
}
return &named_numbers[names_len - 1];
}
void append_number_name(GString* gstr, integer n, bool ordinal) {
if (n < 20)
g_string_append(gstr, get_small_name(&small[n], ordinal));
else if (n < 100) {
if (n % 10 == 0) {
g_string_append(gstr, get_small_name(&tens[n/10 - 2], ordinal));
} else {
g_string_append(gstr, get_small_name(&tens[n/10 - 2], false));
g_string_append_c(gstr, '-');
g_string_append(gstr, get_small_name(&small[n % 10], ordinal));
}
} else {
const named_number* num = get_named_number(n);
integer p = num->number;
append_number_name(gstr, n/p, false);
g_string_append_c(gstr, ' ');
if (n % p == 0) {
g_string_append(gstr, get_big_name(num, ordinal));
} else {
g_string_append(gstr, get_big_name(num, false));
g_string_append_c(gstr, ' ');
append_number_name(gstr, n % p, ordinal);
}
}
}
GString* number_name(integer n, bool ordinal) {
GString* result = g_string_sized_new(8);
append_number_name(result, n, ordinal);
return result;
}
void test_ordinal(integer n) {
GString* name = number_name(n, true);
printf("%llu: %s\n", n, name->str);
g_string_free(name, TRUE);
}
int main() {
test_ordinal(1);
test_ordinal(2);
test_ordinal(3);
test_ordinal(4);
test_ordinal(5);
test_ordinal(11);
test_ordinal(15);
test_ordinal(21);
test_ordinal(42);
test_ordinal(65);
test_ordinal(98);
test_ordinal(100);
test_ordinal(101);
test_ordinal(272);
test_ordinal(300);
test_ordinal(750);
test_ordinal(23456);
test_ordinal(7891233);
test_ordinal(8007006005004003LL);
return 0;
} |
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.
| #Java | Java | public class SquaresCubes {
public static boolean isPerfectCube(long n) {
long c = (long)Math.cbrt((double)n);
return ((c * c * c) == n);
}
public static void main(String... args) {
long n = 1;
int squareOnlyCount = 0;
int squareCubeCount = 0;
while ((squareOnlyCount < 30) || (squareCubeCount < 3)) {
long sq = n * n;
if (isPerfectCube(sq)) {
squareCubeCount++;
System.out.println("Square and cube: " + sq);
}
else {
squareOnlyCount++;
System.out.println("Square: " + sq);
}
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
| #Python | Python | def sd1(numbers):
if numbers:
mean = sum(numbers) / len(numbers)
sd = (sum((n - mean)**2 for n in numbers) / len(numbers))**0.5
return sd, mean
else:
return 0, 0
def sd2(numbers):
if numbers:
sx = sxx = n = 0
for x in numbers:
sx += x
sxx += x*x
n += 1
sd = (n * sxx - sx*sx)**0.5 / n
return sd, sx / n
else:
return 0, 0
def histogram(numbers):
h = [0] * 10
maxwidth = 50 # characters
for n in numbers:
h[int(n*10)] += 1
mx = max(h)
print()
for n, i in enumerate(h):
print('%3.1f: %s' % (n / 10, '+' * int(i / mx * maxwidth)))
print()
if __name__ == '__main__':
import random
for i in range(1, 6):
n = [random.random() for j in range(10**i)]
print("\n##\n## %i numbers\n##" % 10**i)
print(' Naive method: sd: %8.6f, mean: %8.6f' % sd1(n))
print(' Second method: sd: %8.6f, mean: %8.6f' % sd2(n))
histogram(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.
| #Tcl | Tcl | package require Tcl 8.5
# How to process a single value, adding it to the table mapping stems to
# leaves.
proc addSLValue {tblName value {splitFactor 10}} {
upvar 1 $tblName tbl
# Extract the stem and leaf
if {$value < 0} {
set value [expr {round(-$value)}]
set stem -[expr {$value / $splitFactor}]
} else {
set value [expr {round($value)}]
set stem [expr {$value / $splitFactor}]
}
if {![info exist tbl]} {
dict set tbl min $stem
}
dict set tbl max $stem
set leaf [expr {$value % $splitFactor}]
dict lappend tbl $stem $leaf
}
# How to do the actual output of the stem-and-leaf table, given that we have
# already done the splitting into stems and leaves.
proc printSLTable {tblName} {
upvar 1 $tblName tbl
# Get the range of stems
set min [dict get $tbl min]
set max [dict get $tbl max]
# Work out how much width the stems take so everything lines up
set l [expr {max([string length $min], [string length $max])}]
# Print out the table
for {set i $min} {$i <= $max} {incr i} {
if {![dict exist $tbl $i]} {
puts [format " %*d |" $l $i]
} else {
puts [format " %*d | %s" $l $i [dict get $tbl $i]]
}
}
}
# Assemble the parts into a full stem-and-leaf table printer.
proc printStemLeaf {dataList {splitFactor 10}} {
foreach value [lsort -real $dataList] {
addSLValue tbl $value $splitFactor
}
printSLTable tbl
}
# Demo code
set 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
}
printStemLeaf $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
| #Forth | Forth | CREATE A 0 ,
: C@A+ A @ C@ [ 1 CHARS ]L A +! ;
: SPLIT. ( c-addr u --) SWAP A ! A @ C@
BEGIN OVER WHILE
C@A+ TUCK <> IF ." , " THEN
DUP EMIT SWAP 1- SWAP
REPEAT DROP ;
: TEST OVER OVER
." input: " TYPE CR
." split: " SPLIT. CR ;
s" gHHH5YY++///\" TEST
s" gHHH5 ))YY++,,,///\" TEST
BYE |
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
| #Fortran | Fortran | SUBROUTINE SPLATTER(TEXT) !Print a comma-separated list. Repeated characters constitute one item.
Can't display the inserted commas in a different colour so as not to look like any commas in TEXT.
CHARACTER*(*) TEXT !The text.
INTEGER L !A finger.
CHARACTER*1 C !A state follower.
IF (LEN(TEXT).LE.0) RETURN !Prevent surprises in the following..
C = TEXT(1:1) !Syncopation: what went before.
DO L = 1,LEN(TEXT) !Step through the text.
IF (C.NE.TEXT(L:L)) THEN !A change of character?
C = TEXT(L:L) !Yes. This is the new normal.
WRITE (6,1) ", " !Set off from what went before. This is not from TEXT.
END IF !So much for changes.
WRITE (6,1) C !Roll the current character. (=TEXT(L:L))
1 FORMAT (A,$) !The $ sez: do not end the line.
END DO !On to the next character.
WRITE (6,1) !Thus end the line. No output item means that the $ is not reached, so the line is ended.
END SUBROUTINE SPLATTER !TEXT with spaces, or worse, commas, will produce an odd-looking list.
PROGRAM POKE
CALL SPLATTER("gHHH5YY++///\") !The example given.
END |
http://rosettacode.org/wiki/Stern-Brocot_sequence | Stern-Brocot sequence | For this task, the Stern-Brocot sequence is to be generated by an algorithm similar to that employed in generating the Fibonacci sequence.
The first and second members of the sequence are both 1:
1, 1
Start by considering the second member of the sequence
Sum the considered member of the sequence and its precedent, (1 + 1) = 2, and append it to the end of the sequence:
1, 1, 2
Append the considered member of the sequence to the end of the sequence:
1, 1, 2, 1
Consider the next member of the series, (the third member i.e. 2)
GOTO 3
─── Expanding another loop we get: ───
Sum the considered member of the sequence and its precedent, (2 + 1) = 3, and append it to the end of the sequence:
1, 1, 2, 1, 3
Append the considered member of the sequence to the end of the sequence:
1, 1, 2, 1, 3, 2
Consider the next member of the series, (the fourth member i.e. 1)
The task is to
Create a function/method/subroutine/procedure/... to generate the Stern-Brocot sequence of integers using the method outlined above.
Show the first fifteen members of the sequence. (This should be: 1, 1, 2, 1, 3, 2, 3, 1, 4, 3, 5, 2, 5, 3, 4)
Show the (1-based) index of where the numbers 1-to-10 first appears in the sequence.
Show the (1-based) index of where the number 100 first appears in the sequence.
Check that the greatest common divisor of all the two consecutive members of the series up to the 1000th member, is always one.
Show your output on this page.
Related tasks
Fusc sequence.
Continued fraction/Arithmetic
Ref
Infinite Fractions - Numberphile (Video).
Trees, Teeth, and Time: The mathematics of clock making.
A002487 The On-Line Encyclopedia of Integer Sequences.
| #R | R |
## Stern-Brocot sequence
## 12/19/16 aev
SternBrocot <- function(n){
V <- 1; k <- n/2;
for (i in 1:k)
{ V[2*i] = V[i]; V[2*i+1] = V[i] + V[i+1];}
return(V);
}
## Required tests:
require(pracma);
{
cat(" *** The first 15:",SternBrocot(15),"\n");
cat(" *** The first i@n:","\n");
V=SternBrocot(40);
for (i in 1:10) {j=match(i,V); cat(i,"@",j,",")}
V=SternBrocot(1200);
i=100; j=match(i,V); cat(i,"@",j,"\n");
V=SternBrocot(1000); j=1;
for (i in 2:1000) {j=j*gcd(V[i-1],V[i])}
if(j==1) {cat(" *** All GCDs=1!\n")} else {cat(" *** All GCDs!=1??\n")}
}
|
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
'🌑', '🌒', '🌓', '🌔', '🌕', '🌖', '🌗', '🌘'
| #Kotlin | Kotlin | // Version 1.2.50
const val ESC = "\u001b"
fun main(args: Array<String>) {
val a = "|/-\\"
print("$ESC[?25l") // hide the cursor
val start = System.currentTimeMillis()
while (true) {
for (i in 0..3) {
print("$ESC[2J") // clear terminal
print("$ESC[0;0H") // place cursor at top left corner
for (j in 0..79) { // 80 character terminal width, say
print(a[i])
}
Thread.sleep(250)
}
val now = System.currentTimeMillis()
// stop after 20 seconds, say
if (now - start >= 20000) break
}
print("$ESC[?25h") // restore the cursor
} |
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
'🌑', '🌒', '🌓', '🌔', '🌕', '🌖', '🌗', '🌘'
| #Lua | Lua |
--
-- Simple String Animation - semi-hard-coded variant - you can alter the chars table - update the count and run it...
--
-- The basic animation runtime controller. This is where you assign the active animation ( you could create a simple function to replace the animation table and nil count, index and expiry to extend this system to allow multiple animations -
-- and since you can replace after a previous has been output, it would appear as though you were running different animations at the same time - that wouldn't be async compatible though )...
-- So you can either activate the animation you want permanently, or create a simple function to update the animation table and reset the control variables... ie: ( function string.SetBasicAnimation( _tab_of_chars ) string.__basic_anim_runtime.anim = _tab_of_chars; string.__basic_anim_runtime.index = nil; string.__basic_anim_runtime.count = nil; string.__basic_anim_runtime.expiry = nil; end )
string.__basic_anim_runtime = {
-- The animation - can not ping pong... requires full sequence. Resets to first after full sequence. Dots animation.. Requires center segment because of ping / pong
anim = { '.', '..', '...', '..' };
-- Pipes animation - This performs a complete rotation, no need to add extra segments.
-- anim = { '|', '/', '─', '\\' };
-- Stars - This is reversible so requires the center segments..
-- anim = { '⁎', '⁑', '⁂', '⁑' };
-- Clock - This still needs to be ordered...
-- anim = { '🕛', '🕧', '🕐', '🕜', '🕑', '🕝', '🕒', '🕞', '🕓', '🕟', '🕔', '🕠', '🕕', '🕖', '🕗', '🕘', '🕙', '🕚', '🕡', '🕢', '🕣', '🕤', '🕥', '🕦' };
-- Arrows - This does a complete circle and doesn't need to reverse
-- anim = { '⬍', '⬈', '➞', '⬊', '⬍', '⬋', '⬅', '⬉' };
-- Bird Flying - this is reversible so it requires all.. 1 2 3 4 5 6 5 4 3 2
-- anim = { '︷', '︵', '︹', '︺', '︶', '︸', '︶', '︺', '︹', '︵' };
-- Plants - Set as reversible, requires all..
-- anim = { '☘', '❀', '❁', '❀' };
-- Eclipse - From Raku Throbber post author
-- anim = { '🌑', '🌒', '🌓', '🌔', '🌕', '🌖', '🌗', '🌘' };
};
--
-- The basic animator function - accepts a numerical delay and a boolean backwards switch.. It only accepts a single animation from the helper local table above..
--
-- Argument - _delay - <Number> - Accepts a time, in seconds with fraction support, that designates how long a frame should last. Optional. If no number given, it uses the default value of 1 / 8 seconds.
-- Argument - _play_backwards - <Boolean> - Toggles whether or not the animation plays backwards or forwards. Default is forwards. Optional.
--
-- RETURN: <String> - Character( s ) of the current animation frame - if the frame is invalid, it returns an empty string.
-- RETURN: <Boolean> - Has Advanced Frame Controller - set to true if this call resulted in a new frame / index being assigned with new character( s )
--
function string.BasicAnimation( _delay, _play_backwards )
-- Setup delay - make sure it is a number and Reference our runtime var
local _delay = ( ( type( _delay ) == 'number' ) and _delay or 1 / 8 ), string.__basic_anim_runtime, os.clock( );
-- cache our count so we count once per refresh.
_data.count = ( type( _data.count ) == 'number' ) and _data.count or #_data.anim;
-- Setup our helpers...
local _expiry, _index, _chars, _count, _has_advanced_frame = _data.expiry, ( _data.index or ( _play_backwards and _data.count or 1 ) ), _data.anim, _data.count, false;
-- If expiry has occurred, advance... Expiry can be nil the first call, this is ok because it will just use the first character - or the last if playing backwards.
if ( _expiry and _expiry < _time ) then
-- Advance..
_index, _has_advanced_frame = ( ( _index + ( 1 * ( _play_backwards and -1 or 1 ) ) ) % ( _count + 1 ) ), true;
-- If 0, add 1 otherwise keep the same.
_index = _index < 1 and ( _play_backwards and _count or 1 ) or _index;
-- Update the index
_data.index = _index;
end
-- Update the trackers and output the char. -- Note: This is best done in the loop, but since we are checking the expiry above I decided to integrate it here.
_data.expiry = ( not _data.expiry or _has_advanced_frame ) and _time + _delay or _data.expiry;
-- Return the character at the index or nothing.
return _chars[ _index ] or '', _has_advanced_frame;
end
--
-- Helper / OPTIONAL FUNCTION - Updates the animation and resets the controlling variables
--
-- Argument: _tab - <Table> - This is the table containing the animation characters... ie: { '.', '..', '...', '..' } would be a valid entry. Requires at least 2 entries.
--
function string.SetBasicAnimation( _tab )
-- Prevent non tables, empty tables, or tables with only 1 entry.
if not ( type( _tab ) == 'table' and #_tab > 1 ) then return error( 'Can not update basic animation without argument #1 as a table, with at least 2 entries...' ); end
-- Helper
local _data = string.__basic_anim_runtime;
-- Update the animation table and Clear the controllers...
_data.anim, _data.count, _data.index, _data.expiry = _tab, nil, nil, nil;
end
|
http://rosettacode.org/wiki/Stack | Stack |
Data Structure
This illustrates a data structure, a means of storing data within a program.
You may see other such structures in the Data Structures category.
A stack is a container of elements with last in, first out access policy. Sometimes it also called LIFO.
The stack is accessed through its top.
The basic stack operations are:
push stores a new element onto the stack top;
pop returns the last pushed stack element, while removing it from the stack;
empty tests if the stack contains no elements.
Sometimes the last pushed stack element is made accessible for immutable access (for read) or mutable access (for write):
top (sometimes called peek to keep with the p theme) returns the topmost element without modifying the stack.
Stacks allow a very simple hardware implementation.
They are common in almost all processors.
In programming, stacks are also very popular for their way (LIFO) of resource management, usually memory.
Nested scopes of language objects are naturally implemented by a stack (sometimes by multiple stacks).
This is a classical way to implement local variables of a re-entrant or recursive subprogram. Stacks are also used to describe a formal computational framework.
See stack machine.
Many algorithms in pattern matching, compiler construction (e.g. recursive descent parsers), and machine learning (e.g. based on tree traversal) have a natural representation in terms of stacks.
Task
Create a stack supporting the basic operations: push, pop, empty.
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
| #C.23 | C# | // Non-Generic Stack
System.Collections.Stack stack = new System.Collections.Stack();
stack.Push( obj );
bool isEmpty = stack.Count == 0;
object top = stack.Peek(); // Peek without Popping.
top = stack.Pop();
// Generic Stack
System.Collections.Generic.Stack<Foo> stack = new System.Collections.Generic.Stack<Foo>();
stack.Push(new Foo());
bool isEmpty = stack.Count == 0;
Foo top = stack.Peek(); // Peek without Popping.
top = stack.Pop(); |
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.
| #11l | 11l | ;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/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
| #C.2B.2B | C++ | #include <iostream>
#include <string>
#include <cstdint>
typedef std::uint64_t integer;
struct number_names {
const char* cardinal;
const char* ordinal;
};
const number_names small[] = {
{ "zero", "zeroth" }, { "one", "first" }, { "two", "second" },
{ "three", "third" }, { "four", "fourth" }, { "five", "fifth" },
{ "six", "sixth" }, { "seven", "seventh" }, { "eight", "eighth" },
{ "nine", "ninth" }, { "ten", "tenth" }, { "eleven", "eleventh" },
{ "twelve", "twelfth" }, { "thirteen", "thirteenth" },
{ "fourteen", "fourteenth" }, { "fifteen", "fifteenth" },
{ "sixteen", "sixteenth" }, { "seventeen", "seventeenth" },
{ "eighteen", "eighteenth" }, { "nineteen", "nineteenth" }
};
const number_names tens[] = {
{ "twenty", "twentieth" }, { "thirty", "thirtieth" },
{ "forty", "fortieth" }, { "fifty", "fiftieth" },
{ "sixty", "sixtieth" }, { "seventy", "seventieth" },
{ "eighty", "eightieth" }, { "ninety", "ninetieth" }
};
struct named_number {
const char* cardinal;
const char* ordinal;
integer number;
};
const named_number named_numbers[] = {
{ "hundred", "hundredth", 100 },
{ "thousand", "thousandth", 1000 },
{ "million", "millionth", 1000000 },
{ "billion", "billionth", 1000000000 },
{ "trillion", "trillionth", 1000000000000 },
{ "quadrillion", "quadrillionth", 1000000000000000ULL },
{ "quintillion", "quintillionth", 1000000000000000000ULL }
};
const char* get_name(const number_names& n, bool ordinal) {
return ordinal ? n.ordinal : n.cardinal;
}
const char* get_name(const named_number& n, bool ordinal) {
return ordinal ? n.ordinal : n.cardinal;
}
const named_number& get_named_number(integer n) {
constexpr size_t names_len = std::size(named_numbers);
for (size_t i = 0; i + 1 < names_len; ++i) {
if (n < named_numbers[i + 1].number)
return named_numbers[i];
}
return named_numbers[names_len - 1];
}
std::string number_name(integer n, bool ordinal) {
std::string result;
if (n < 20)
result = get_name(small[n], ordinal);
else if (n < 100) {
if (n % 10 == 0) {
result = get_name(tens[n/10 - 2], ordinal);
} else {
result = get_name(tens[n/10 - 2], false);
result += "-";
result += get_name(small[n % 10], ordinal);
}
} else {
const named_number& num = get_named_number(n);
integer p = num.number;
result = number_name(n/p, false);
result += " ";
if (n % p == 0) {
result += get_name(num, ordinal);
} else {
result += get_name(num, false);
result += " ";
result += number_name(n % p, ordinal);
}
}
return result;
}
void test_ordinal(integer n) {
std::cout << n << ": " << number_name(n, true) << '\n';
}
int main() {
test_ordinal(1);
test_ordinal(2);
test_ordinal(3);
test_ordinal(4);
test_ordinal(5);
test_ordinal(11);
test_ordinal(15);
test_ordinal(21);
test_ordinal(42);
test_ordinal(65);
test_ordinal(98);
test_ordinal(100);
test_ordinal(101);
test_ordinal(272);
test_ordinal(300);
test_ordinal(750);
test_ordinal(23456);
test_ordinal(7891233);
test_ordinal(8007006005004003LL);
return 0;
} |
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.
| #JavaScript | JavaScript | (() => {
'use strict';
const main = () =>
unlines(map(
x => x.toString() + (
isCube(x) ? (
` (cube of ${cubeRootInt(x)} and square of ${
Math.pow(x, 1/2)
})`
) : ''
),
map(x => x * x, enumFromTo(1, 33))
));
// isCube :: Int -> Bool
const isCube = n =>
n === Math.pow(cubeRootInt(n), 3);
// cubeRootInt :: Int -> Int
const cubeRootInt = n => Math.round(Math.pow(n, 1 / 3));
// GENERIC FUNCTIONS ----------------------------------
// enumFromTo :: Int -> Int -> [Int]
const enumFromTo = (m, n) =>
m <= n ? iterateUntil(
x => n <= x,
x => 1 + x,
m
) : [];
// iterateUntil :: (a -> Bool) -> (a -> a) -> a -> [a]
const iterateUntil = (p, f, x) => {
const vs = [x];
let h = x;
while (!p(h))(h = f(h), vs.push(h));
return vs;
};
// map :: (a -> b) -> [a] -> [b]
const map = (f, xs) => xs.map(f);
// unlines :: [String] -> String
const unlines = xs => xs.join('\n');
// MAIN ---
return main();
})(); |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.