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/Stable_marriage_problem | Stable marriage problem | Solve the Stable marriage problem using the Gale/Shapley algorithm.
Problem description
Given an equal number of men and women to be paired for marriage, each man ranks all the women in order of his preference and each woman ranks all the men in order of her preference.
A stable set of engagements for marriage is one where no man prefers a woman over the one he is engaged to, where that other woman also prefers that man over the one she is engaged to. I.e. with consulting marriages, there would be no reason for the engagements between the people to change.
Gale and Shapley proved that there is a stable set of engagements for any set of preferences and the first link above gives their algorithm for finding a set of stable engagements.
Task Specifics
Given ten males:
abe, bob, col, dan, ed, fred, gav, hal, ian, jon
And ten females:
abi, bea, cath, dee, eve, fay, gay, hope, ivy, jan
And a complete list of ranked preferences, where the most liked is to the left:
abe: abi, eve, cath, ivy, jan, dee, fay, bea, hope, gay
bob: cath, hope, abi, dee, eve, fay, bea, jan, ivy, gay
col: hope, eve, abi, dee, bea, fay, ivy, gay, cath, jan
dan: ivy, fay, dee, gay, hope, eve, jan, bea, cath, abi
ed: jan, dee, bea, cath, fay, eve, abi, ivy, hope, gay
fred: bea, abi, dee, gay, eve, ivy, cath, jan, hope, fay
gav: gay, eve, ivy, bea, cath, abi, dee, hope, jan, fay
hal: abi, eve, hope, fay, ivy, cath, jan, bea, gay, dee
ian: hope, cath, dee, gay, bea, abi, fay, ivy, jan, eve
jon: abi, fay, jan, gay, eve, bea, dee, cath, ivy, hope
abi: bob, fred, jon, gav, ian, abe, dan, ed, col, hal
bea: bob, abe, col, fred, gav, dan, ian, ed, jon, hal
cath: fred, bob, ed, gav, hal, col, ian, abe, dan, jon
dee: fred, jon, col, abe, ian, hal, gav, dan, bob, ed
eve: jon, hal, fred, dan, abe, gav, col, ed, ian, bob
fay: bob, abe, ed, ian, jon, dan, fred, gav, col, hal
gay: jon, gav, hal, fred, bob, abe, col, ed, dan, ian
hope: gav, jon, bob, abe, ian, dan, hal, ed, col, fred
ivy: ian, col, hal, gav, fred, bob, abe, ed, jon, dan
jan: ed, hal, gav, abe, bob, jon, col, ian, fred, dan
Use the Gale Shapley algorithm to find a stable set of engagements
Perturb this set of engagements to form an unstable set of engagements then check this new set for stability.
References
The Stable Marriage Problem. (Eloquent description and background information).
Gale-Shapley Algorithm Demonstration.
Another Gale-Shapley Algorithm Demonstration.
Stable Marriage Problem - Numberphile (Video).
Stable Marriage Problem (the math bit) (Video).
The Stable Marriage Problem and School Choice. (Excellent exposition)
| #C.23 | C# | using System;
using System.Collections.Generic;
namespace StableMarriage
{
class Person
{
private int _candidateIndex;
public string Name { get; set; }
public List<Person> Prefs { get; set; }
public Person Fiance { get; set; }
public Person(string name) {
Name = name;
Prefs = null;
Fiance = null;
_candidateIndex = 0;
}
public bool Prefers(Person p) {
return Prefs.FindIndex(o => o == p) < Prefs.FindIndex(o => o == Fiance);
}
public Person NextCandidateNotYetProposedTo() {
if (_candidateIndex >= Prefs.Count) return null;
return Prefs[_candidateIndex++];
}
public void EngageTo(Person p) {
if (p.Fiance != null) p.Fiance.Fiance = null;
p.Fiance = this;
if (Fiance != null) Fiance.Fiance = null;
Fiance = p;
}
}
static class MainClass
{
static public bool IsStable(List<Person> men) {
List<Person> women = men[0].Prefs;
foreach (Person guy in men) {
foreach (Person gal in women) {
if (guy.Prefers(gal) && gal.Prefers(guy))
return false;
}
}
return true;
}
static void DoMarriage() {
Person abe = new Person("abe");
Person bob = new Person("bob");
Person col = new Person("col");
Person dan = new Person("dan");
Person ed = new Person("ed");
Person fred = new Person("fred");
Person gav = new Person("gav");
Person hal = new Person("hal");
Person ian = new Person("ian");
Person jon = new Person("jon");
Person abi = new Person("abi");
Person bea = new Person("bea");
Person cath = new Person("cath");
Person dee = new Person("dee");
Person eve = new Person("eve");
Person fay = new Person("fay");
Person gay = new Person("gay");
Person hope = new Person("hope");
Person ivy = new Person("ivy");
Person jan = new Person("jan");
abe.Prefs = new List<Person>() {abi, eve, cath, ivy, jan, dee, fay, bea, hope, gay};
bob.Prefs = new List<Person>() {cath, hope, abi, dee, eve, fay, bea, jan, ivy, gay};
col.Prefs = new List<Person>() {hope, eve, abi, dee, bea, fay, ivy, gay, cath, jan};
dan.Prefs = new List<Person>() {ivy, fay, dee, gay, hope, eve, jan, bea, cath, abi};
ed.Prefs = new List<Person>() {jan, dee, bea, cath, fay, eve, abi, ivy, hope, gay};
fred.Prefs = new List<Person>() {bea, abi, dee, gay, eve, ivy, cath, jan, hope, fay};
gav.Prefs = new List<Person>() {gay, eve, ivy, bea, cath, abi, dee, hope, jan, fay};
hal.Prefs = new List<Person>() {abi, eve, hope, fay, ivy, cath, jan, bea, gay, dee};
ian.Prefs = new List<Person>() {hope, cath, dee, gay, bea, abi, fay, ivy, jan, eve};
jon.Prefs = new List<Person>() {abi, fay, jan, gay, eve, bea, dee, cath, ivy, hope};
abi.Prefs = new List<Person>() {bob, fred, jon, gav, ian, abe, dan, ed, col, hal};
bea.Prefs = new List<Person>() {bob, abe, col, fred, gav, dan, ian, ed, jon, hal};
cath.Prefs = new List<Person>() {fred, bob, ed, gav, hal, col, ian, abe, dan, jon};
dee.Prefs = new List<Person>() {fred, jon, col, abe, ian, hal, gav, dan, bob, ed};
eve.Prefs = new List<Person>() {jon, hal, fred, dan, abe, gav, col, ed, ian, bob};
fay.Prefs = new List<Person>() {bob, abe, ed, ian, jon, dan, fred, gav, col, hal};
gay.Prefs = new List<Person>() {jon, gav, hal, fred, bob, abe, col, ed, dan, ian};
hope.Prefs = new List<Person>() {gav, jon, bob, abe, ian, dan, hal, ed, col, fred};
ivy.Prefs = new List<Person>() {ian, col, hal, gav, fred, bob, abe, ed, jon, dan};
jan.Prefs = new List<Person>() {ed, hal, gav, abe, bob, jon, col, ian, fred, dan};
List<Person> men = new List<Person>(abi.Prefs);
int freeMenCount = men.Count;
while (freeMenCount > 0) {
foreach (Person guy in men) {
if (guy.Fiance == null) {
Person gal = guy.NextCandidateNotYetProposedTo();
if (gal.Fiance == null) {
guy.EngageTo(gal);
freeMenCount--;
} else if (gal.Prefers(guy)) {
guy.EngageTo(gal);
}
}
}
}
foreach (Person guy in men) {
Console.WriteLine("{0} is engaged to {1}", guy.Name, guy.Fiance.Name);
}
Console.WriteLine("Stable = {0}", IsStable(men));
Console.WriteLine("\nSwitching fred & jon's partners");
Person jonsFiance = jon.Fiance;
Person fredsFiance = fred.Fiance;
fred.EngageTo(jonsFiance);
jon.EngageTo(fredsFiance);
Console.WriteLine("Stable = {0}", IsStable(men));
}
public static void Main(string[] args)
{
DoMarriage();
}
}
} |
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
| #Phix | Phix | constant tests = {1, 2, 3, 4, 5, 11, 65, 100, 101, 272, 23456, 8007006005004003,
123, 00123.0, 1.23e2, 0b1111011, 0o173, 0x7B, 861/7}
for i=1 to length(tests) do
puts(1,ordinal(tests[i])&'\n')
end for
|
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.
| #Nim | Nim | var count = 0
var n, c, c3 = 1
while count < 30:
var sq = n * n
while c3 < sq:
inc c
c3 = c * c * c
if c3 == sq:
echo sq, " is square and cube"
else:
echo sq
inc count
inc n |
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.
| #OCaml | OCaml | let rec fN n g phi =
if phi < 31 then
match compare (n*n) (g*g*g) with
| -1 -> Printf.printf "%d\n" (n*n); fN (n+1) g (phi+1)
| 0 -> Printf.printf "%d cube and square\n" (n*n); fN (n+1) (g+1) phi
| 1 -> fN n (g+1) phi
| _ -> assert false
;;
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
| #VBA | VBA | Option Base 1
Private Function mean(s() As Variant) As Double
mean = WorksheetFunction.Average(s)
End Function
Private Function standard_deviation(s() As Variant) As Double
standard_deviation = WorksheetFunction.StDev(s)
End Function
Public Sub basic_statistics()
Dim s() As Variant
For e = 2 To 4
ReDim s(10 ^ e)
For i = 1 To 10 ^ e
s(i) = Rnd()
Next i
Debug.Print "sample size"; UBound(s), "mean"; mean(s), "standard deviation"; standard_deviation(s)
t = WorksheetFunction.Frequency(s, [{0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0}])
For i = 1 To 10
Debug.Print Format((i - 1) / 10, "0.00");
Debug.Print "-"; Format(i / 10, "0.00"),
Debug.Print String$(t(i, 1) / (10 ^ (e - 2)), "X");
Debug.Print
Next i
Debug.Print
Next e
End Sub |
http://rosettacode.org/wiki/Statistics/Basic | Statistics/Basic | Statistics is all about large groups of numbers.
When talking about a set of sampled data, most frequently used is their mean value and standard deviation (stddev).
If you have set of data
x
i
{\displaystyle x_{i}}
where
i
=
1
,
2
,
…
,
n
{\displaystyle i=1,2,\ldots ,n\,\!}
, the mean is
x
¯
≡
1
n
∑
i
x
i
{\displaystyle {\bar {x}}\equiv {1 \over n}\sum _{i}x_{i}}
, while the stddev is
σ
≡
1
n
∑
i
(
x
i
−
x
¯
)
2
{\displaystyle \sigma \equiv {\sqrt {{1 \over n}\sum _{i}\left(x_{i}-{\bar {x}}\right)^{2}}}}
.
When examining a large quantity of data, one often uses a histogram, which shows the counts of data samples falling into a prechosen set of intervals (or bins).
When plotted, often as bar graphs, it visually indicates how often each data value occurs.
Task Using your language's random number routine, generate real numbers in the range of [0, 1]. It doesn't matter if you chose to use open or closed range.
Create 100 of such numbers (i.e. sample size 100) and calculate their mean and stddev.
Do so for sample size of 1,000 and 10,000, maybe even higher if you feel like.
Show a histogram of any of these sets.
Do you notice some patterns about the standard deviation?
Extra Sometimes so much data need to be processed that it's impossible to keep all of them at once. Can you calculate the mean, stddev and histogram of a trillion numbers? (You don't really need to do a trillion numbers, just show how it can be done.)
Hint
For a finite population with equal probabilities at all points, one can derive:
(
x
−
x
¯
)
2
¯
=
x
2
¯
−
x
¯
2
{\displaystyle {\overline {(x-{\overline {x}})^{2}}}={\overline {x^{2}}}-{\overline {x}}^{2}}
Or, more verbosely:
1
N
∑
i
=
1
N
(
x
i
−
x
¯
)
2
=
1
N
(
∑
i
=
1
N
x
i
2
)
−
x
¯
2
.
{\displaystyle {\frac {1}{N}}\sum _{i=1}^{N}(x_{i}-{\overline {x}})^{2}={\frac {1}{N}}\left(\sum _{i=1}^{N}x_{i}^{2}\right)-{\overline {x}}^{2}.}
See also
Statistics/Normal distribution
Tasks for calculating statistical measures
in one go
moving (sliding window)
moving (cumulative)
Mean
Arithmetic
Statistics/Basic
Averages/Arithmetic mean
Averages/Pythagorean means
Averages/Simple moving average
Geometric
Averages/Pythagorean means
Harmonic
Averages/Pythagorean means
Quadratic
Averages/Root mean square
Circular
Averages/Mean angle
Averages/Mean time of day
Median
Averages/Median
Mode
Averages/Mode
Standard deviation
Statistics/Basic
Cumulative standard deviation
| #Vlang | Vlang | import rand
import math
fn main() {
sample(100)
sample(1000)
sample(10000)
}
fn sample(n int) {
// generate data
mut d := []f64{len: n}
for i in 0.. d.len {
d[i] = rand.f64()
}
// show mean, standard deviation
mut sum, mut ssq := f64(0), f64(0)
for s in d {
sum += s
ssq += s * s
}
println("$n numbers")
m := sum / f64(n)
println("Mean: $m")
println("Stddev: ${math.sqrt(ssq/f64(n)-m*m)}")
// show histogram
mut h := []int{len: 10}
for s in d {
h[int(s*10)]++
}
for c in h {
println("*".repeat(c*205/int(n)))
}
println('')
} |
http://rosettacode.org/wiki/Split_a_character_string_based_on_change_of_character | Split a character string based on change of character |
Task
Split a (character) string into comma (plus a blank) delimited
strings based on a change of character (left to right).
Show the output here (use the 1st example below).
Blanks should be treated as any other character (except
they are problematic to display clearly). The same applies
to commas.
For instance, the string:
gHHH5YY++///\
should be split and show:
g, HHH, 5, YY, ++, ///, \
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Lambdatalk | Lambdatalk |
{def mysplit
{def mysplit.r
{lambda {:w :i}
{if {> :i {W.length :w}}
then
else {if {not {W.equal? {W.get :i :w} {W.get {+ :i 1} :w}}}
then ____ else} {W.get {+ :i 1} :w}{mysplit.r :w {+ :i 1}}}}}
{lambda {:w}
{S.replace ____ by in {mysplit.r #:w 0}}}}
-> mysplit
{mysplit gHHH5YY++///\}
-> g HHH 5 YY ++ /// \
|
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
| #Lua | Lua | function charSplit (inStr)
local outStr, nextChar = inStr:sub(1, 1)
for pos = 2, #inStr do
nextChar = inStr:sub(pos, pos)
if nextChar ~= outStr:sub(#outStr, #outStr) then
outStr = outStr .. ", "
end
outStr = outStr .. nextChar
end
return outStr
end
print(charSplit("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.
| #Sidef | Sidef | # Declare a function to generate the Stern-Brocot sequence
func stern_brocot {
var list = [1, 1]
{
list.append(list[0]+list[1], list[1])
list.shift
}
}
# Show the first fifteen members of the sequence.
say 15.of(stern_brocot()).join(' ')
# Show the (1-based) index of where the numbers 1-to-10 first appears
# in the sequence, and where the number 100 first appears in the sequence.
for i (1..10, 100) {
var index = 1
var generator = stern_brocot()
while (generator() != i) {
++index
}
say "First occurrence of #{i} is at index #{index}"
}
# Check that the greatest common divisor of all the two consecutive
# members of the series up to the 1000th member, is always one.
var generator = stern_brocot()
var (a, b) = (generator(), generator())
{
assert_eq(gcd(a, b), 1)
a = b
b = generator()
} * 1000
say "All GCD's are 1" |
http://rosettacode.org/wiki/Spinning_rod_animation/Text | Spinning rod animation/Text | Task
An animation with the following frames in the following order (if certain characters aren't available or can't be used correctly in the programming language, alternate characters can replace any of these frames) must animate with a delay of 0.25 seconds between each frame, with the previous frame being cleared before the next frame appears:
|
/
- or ─
\
A stand-alone version that loops and/or a version that doesn't loop can be made. These examples can also be converted into a system used in game development which is called on a HUD or GUI element requiring it to be called each frame to output the text, and advance the frame when the frame delay has passed. You can also use alternate text such as the . animation ( . | .. | ... | .. | repeat from . ) or the logic can be updated to include a ping/pong style where the frames advance forward, reach the end and then play backwards and when they reach the beginning they start over ( technically, you'd stop one frame prior to prevent the first frame playing twice, or write it another way ).
There are many different ways you can incorporate text animations. Here are a few text ideas - each frame is in quotes. If you can think of any, add them to this page! There are 2 examples for several of these; the first is the base animation with only unique sets of characters. The second consists of the primary set from a - n and doubled, minus the first and last element ie: We only want the center. This way an animation can play forwards, and then in reverse ( ping ponging ) without having to code that feature. For the animations with 3 elements, we only add 1, the center. with 4, it becomes 6. with 10, it becomes 18.
We don't need the second option for some of the animations if they connect smoothly, when animated, back to the first element. ... doesn't connect with . cleanly - there is a large leap. The rotating pipe meets the first perfectly so it isn't necessary, etc..
Dots - Option A requires ping / pong enabled script. Option B just adds the elements in the center.
'.', '..', '...'
'.', '..', '...', '..'
Pipe - This has the uniform sideways pipe instead of a hyphen to prevent non-uniform sizing.
'|', '/', '─', '\'
Stars - Option A requires ping / pong enabled script. Option B just adds the elements from the center.
'⁎', '⁑', '⁂'
'⁎', '⁑', '⁂', '⁑'
Clock - These need to be ordered. I haven't done this yet as the application I was testing the system in doesn't support these wingdings / icons. But this would look quite nice and you could set it up to go forward, or backward during an undo process, etc..
'🕛', '🕧', '🕐', '🕜', '🕑', '🕝', '🕒', '🕞', '🕓', '🕟', '🕔', '🕠', '🕕', '🕖', '🕗', '🕘', '🕙', '🕚', '🕡', '🕢', '🕣', '🕤', '🕥', '🕦'
Arrows:
'⬍', '⬈', '➞', '⬊', '⬍', '⬋', '⬅', '⬉'
Bird - This looks decent but may be missing something.
'︷', '︵', '︹', '︺', '︶', '︸'
'︷', '︵', '︹', '︺', '︶', '︸', '︶', '︺', '︹', '︵'
Plants - This isn't quite complete
'☘', '❀', '❁'
'☘', '❀', '❁', '❀'
Eclipse - From Raku Throbber post author
'🌑', '🌒', '🌓', '🌔', '🌕', '🌖', '🌗', '🌘'
| #REXX | REXX | /*REXX program displays a "spinning rod" (AKA: trobbers or progress indicators). */
if 4=='f4'x then bs= "16"x /*EBCDIC? Then use this backspace chr.*/
else bs= "08"x /* ASCII? " " " " " */
signal on halt /*jump to HALT when user halts pgm.*/
$= '│/─\' /*the throbbing characters for display.*/
do j=1 /*perform until halted by the user. */
call charout , bs || substr($, 1 + j//length($), 1)
call delay .25 /*delays a quarter of a second. */
if result==1 then leave /*see if HALT was issued during DELAY*/
end /*j*/
halt: say bs ' ' /*stick a fork in it, we're all done. */ |
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
'🌑', '🌒', '🌓', '🌔', '🌕', '🌖', '🌗', '🌘'
| #Ring | Ring | load "stdlib.ring"
rod = ["|", "/", "-", "\"]
for n = 1 to len(rod)
see rod[n] + nl
sleep(0.25)
system("cls")
next |
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
| #Crystal | Crystal | stack = [] of Int32
(1..10).each do |x|
stack.push x
end
10.times do
puts stack.pop
end |
http://rosettacode.org/wiki/Spiral_matrix | Spiral matrix | Task
Produce a spiral array.
A spiral array is a square arrangement of the first N2 natural numbers, where the
numbers increase sequentially as you go around the edges of the array spiraling inwards.
For example, given 5, produce this array:
0 1 2 3 4
15 16 17 18 5
14 23 24 19 6
13 22 21 20 7
12 11 10 9 8
Related tasks
Zig-zag matrix
Identity_matrix
Ulam_spiral_(for_primes)
| #Ada | Ada | -- Spiral Square
with Ada.Text_Io; use Ada.Text_Io;
with Ada.Integer_Text_Io; use Ada.Integer_Text_Io;
with Ada.Numerics.Elementary_Functions; use Ada.Numerics.Elementary_Functions;
procedure Spiral_Square is
type Array_Type is array(Positive range <>, Positive range <>) of Natural;
function Spiral (N : Positive) return Array_Type is
Result : Array_Type(1..N, 1..N);
Row : Natural := 1;
Col : Natural := 1;
Max_Row : Natural := N;
Max_Col : Natural := N;
Min_Row : Natural := 1;
Min_Col : Natural := 1;
begin
for I in 0..N**2 - 1 loop
Result(Row, Col) := I;
if Row = Min_Row then
Col := Col + 1;
if Col > Max_Col then
Col := Max_Col;
Row := Row + 1;
end if;
elsif Col = Max_Col then
Row := Row + 1;
if Row > Max_Row then
Row := Max_Row;
Col := Col - 1;
end if;
elsif Row = Max_Row then
Col := Col - 1;
if Col < Min_Col then
Col := Min_Col;
Row := Row - 1;
end if;
elsif Col = Min_Col then
Row := Row - 1;
if Row = Min_Row then -- Reduce spiral
Min_Row := Min_Row + 1;
Max_Row := Max_Row - 1;
Row := Min_Row;
Min_Col := Min_Col + 1;
Max_Col := Max_Col - 1;
Col := Min_Col;
end if;
end if;
end loop;
return Result;
end Spiral;
procedure Print(Item : Array_Type) is
Num_Digits : constant Float := Log(X => Float(Item'Length(1)**2), Base => 10.0);
Spacing : constant Positive := Integer(Num_Digits) + 2;
begin
for I in Item'range(1) loop
for J in Item'range(2) loop
Put(Item => Item(I,J), Width => Spacing);
end loop;
New_Line;
end loop;
end Print;
begin
Print(Spiral(5));
end Spiral_Square; |
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.
| #Clojure | Clojure |
(apply str (interpose " " (sort (filter #(.startsWith % "*") (map str (keys (ns-publics 'clojure.core)))))))
|
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.
| #Common_Lisp | Common Lisp | (defun special-variables ()
(flet ((special-var-p (s)
(and (char= (aref s 0) #\*)
(find-if-not (lambda (x) (char= x #\*)) s)
(char= (aref s (1- (length s))) #\*))))
(let ((lst '()))
(do-symbols (s (find-package 'cl))
(when (special-var-p (symbol-name s))
(push s lst)))
lst)))
(format t "~a~%" (sort (special-variables) #'string<)) |
http://rosettacode.org/wiki/Stable_marriage_problem | Stable marriage problem | Solve the Stable marriage problem using the Gale/Shapley algorithm.
Problem description
Given an equal number of men and women to be paired for marriage, each man ranks all the women in order of his preference and each woman ranks all the men in order of her preference.
A stable set of engagements for marriage is one where no man prefers a woman over the one he is engaged to, where that other woman also prefers that man over the one she is engaged to. I.e. with consulting marriages, there would be no reason for the engagements between the people to change.
Gale and Shapley proved that there is a stable set of engagements for any set of preferences and the first link above gives their algorithm for finding a set of stable engagements.
Task Specifics
Given ten males:
abe, bob, col, dan, ed, fred, gav, hal, ian, jon
And ten females:
abi, bea, cath, dee, eve, fay, gay, hope, ivy, jan
And a complete list of ranked preferences, where the most liked is to the left:
abe: abi, eve, cath, ivy, jan, dee, fay, bea, hope, gay
bob: cath, hope, abi, dee, eve, fay, bea, jan, ivy, gay
col: hope, eve, abi, dee, bea, fay, ivy, gay, cath, jan
dan: ivy, fay, dee, gay, hope, eve, jan, bea, cath, abi
ed: jan, dee, bea, cath, fay, eve, abi, ivy, hope, gay
fred: bea, abi, dee, gay, eve, ivy, cath, jan, hope, fay
gav: gay, eve, ivy, bea, cath, abi, dee, hope, jan, fay
hal: abi, eve, hope, fay, ivy, cath, jan, bea, gay, dee
ian: hope, cath, dee, gay, bea, abi, fay, ivy, jan, eve
jon: abi, fay, jan, gay, eve, bea, dee, cath, ivy, hope
abi: bob, fred, jon, gav, ian, abe, dan, ed, col, hal
bea: bob, abe, col, fred, gav, dan, ian, ed, jon, hal
cath: fred, bob, ed, gav, hal, col, ian, abe, dan, jon
dee: fred, jon, col, abe, ian, hal, gav, dan, bob, ed
eve: jon, hal, fred, dan, abe, gav, col, ed, ian, bob
fay: bob, abe, ed, ian, jon, dan, fred, gav, col, hal
gay: jon, gav, hal, fred, bob, abe, col, ed, dan, ian
hope: gav, jon, bob, abe, ian, dan, hal, ed, col, fred
ivy: ian, col, hal, gav, fred, bob, abe, ed, jon, dan
jan: ed, hal, gav, abe, bob, jon, col, ian, fred, dan
Use the Gale Shapley algorithm to find a stable set of engagements
Perturb this set of engagements to form an unstable set of engagements then check this new set for stability.
References
The Stable Marriage Problem. (Eloquent description and background information).
Gale-Shapley Algorithm Demonstration.
Another Gale-Shapley Algorithm Demonstration.
Stable Marriage Problem - Numberphile (Video).
Stable Marriage Problem (the math bit) (Video).
The Stable Marriage Problem and School Choice. (Excellent exposition)
| #C.2B.2B | C++ | #include <algorithm>
#include <iostream>
#include <map>
#include <queue>
#include <string>
#include <vector>
using namespace std;
const char *men_data[][11] = {
{ "abe", "abi","eve","cath","ivy","jan","dee","fay","bea","hope","gay" },
{ "bob", "cath","hope","abi","dee","eve","fay","bea","jan","ivy","gay" },
{ "col", "hope","eve","abi","dee","bea","fay","ivy","gay","cath","jan" },
{ "dan", "ivy","fay","dee","gay","hope","eve","jan","bea","cath","abi" },
{ "ed", "jan","dee","bea","cath","fay","eve","abi","ivy","hope","gay" },
{ "fred", "bea","abi","dee","gay","eve","ivy","cath","jan","hope","fay" },
{ "gav", "gay","eve","ivy","bea","cath","abi","dee","hope","jan","fay" },
{ "hal", "abi","eve","hope","fay","ivy","cath","jan","bea","gay","dee" },
{ "ian", "hope","cath","dee","gay","bea","abi","fay","ivy","jan","eve" },
{ "jon", "abi","fay","jan","gay","eve","bea","dee","cath","ivy","hope" }
};
const char *women_data[][11] = {
{ "abi", "bob","fred","jon","gav","ian","abe","dan","ed","col","hal" },
{ "bea", "bob","abe","col","fred","gav","dan","ian","ed","jon","hal" },
{ "cath", "fred","bob","ed","gav","hal","col","ian","abe","dan","jon" },
{ "dee", "fred","jon","col","abe","ian","hal","gav","dan","bob","ed" },
{ "eve", "jon","hal","fred","dan","abe","gav","col","ed","ian","bob" },
{ "fay", "bob","abe","ed","ian","jon","dan","fred","gav","col","hal" },
{ "gay", "jon","gav","hal","fred","bob","abe","col","ed","dan","ian" },
{ "hope", "gav","jon","bob","abe","ian","dan","hal","ed","col","fred" },
{ "ivy", "ian","col","hal","gav","fred","bob","abe","ed","jon","dan" },
{ "jan", "ed","hal","gav","abe","bob","jon","col","ian","fred","dan" }
};
typedef vector<string> PrefList;
typedef map<string, PrefList> PrefMap;
typedef map<string, string> Couples;
// Does 'first' appear before 'second' in preference list?
bool prefers(const PrefList &prefer, const string &first, const string &second)
{
for (PrefList::const_iterator it = prefer.begin(); it != prefer.end(); ++it)
{
if (*it == first) return true;
if (*it == second) return false;
}
return false; // no preference
}
void check_stability(const Couples &engaged, const PrefMap &men_pref, const PrefMap &women_pref)
{
cout << "Stablility:\n";
bool stable = true;
for (Couples::const_iterator it = engaged.begin(); it != engaged.end(); ++it)
{
const string &bride = it->first;
const string &groom = it->second;
const PrefList &preflist = men_pref.at(groom);
for (PrefList::const_iterator it = preflist.begin(); it != preflist.end(); ++it)
{
if (*it == bride) // he prefers his bride
break;
if (prefers(preflist, *it, bride) && // he prefers another woman
prefers(women_pref.at(*it), groom, engaged.at(*it))) // other woman prefers him
{
cout << "\t" << *it <<
" prefers " << groom <<
" over " << engaged.at(*it) <<
" and " << groom <<
" prefers " << *it <<
" over " << bride << "\n";
stable = false;
}
}
}
if (stable) cout << "\t(all marriages stable)\n";
}
int main()
{
PrefMap men_pref, women_pref;
queue<string> bachelors;
// init data structures
for (int i = 0; i < 10; ++i) // person
{
for (int j = 1; j < 11; ++j) // preference
{
men_pref[ men_data[i][0]].push_back( men_data[i][j]);
women_pref[women_data[i][0]].push_back(women_data[i][j]);
}
bachelors.push(men_data[i][0]);
}
Couples engaged; // <woman,man>
cout << "Matchmaking:\n";
while (!bachelors.empty())
{
const string &suitor = bachelors.front();
const PrefList &preflist = men_pref[suitor];
for (PrefList::const_iterator it = preflist.begin(); it != preflist.end(); ++it)
{
const string &bride = *it;
if (engaged.find(bride) == engaged.end()) // she's available
{
cout << "\t" << bride << " and " << suitor << "\n";
engaged[bride] = suitor; // hook up
break;
}
const string &groom = engaged[bride];
if (prefers(women_pref[bride], suitor, groom))
{
cout << "\t" << bride << " dumped " << groom << " for " << suitor << "\n";
bachelors.push(groom); // dump that zero
engaged[bride] = suitor; // get a hero
break;
}
}
bachelors.pop(); // pop at the end to not invalidate suitor reference
}
cout << "Engagements:\n";
for (Couples::const_iterator it = engaged.begin(); it != engaged.end(); ++it)
{
cout << "\t" << it->first << " and " << it->second << "\n";
}
check_stability(engaged, men_pref, women_pref);
cout << "Perturb:\n";
std::swap(engaged["abi"], engaged["bea"]);
cout << "\tengage abi with " << engaged["abi"] << " and bea with " << engaged["bea"] << "\n";
check_stability(engaged, men_pref, women_pref);
} |
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
| #Prolog | Prolog | test_ordinal(Number):-
number_name(Number, ordinal, Name),
writef('%w: %w\n', [Number, Name]).
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(8007006005004003). |
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.
| #Pascal | Pascal | program SquareButNotCube;
var
sqN,
sqDelta,
SqNum,
cbN,
cbDelta1,
cbDelta2,
CbNum,
CountSqNotCb,
CountSqAndCb : NativeUint;
begin
CountSqNotCb := 0;
CountSqAndCb := 0;
SqNum := 0;
CbNum := 0;
cbN := 0;
sqN := 0;
sqDelta := 1;
cbDelta1 := 0;
cbDelta2 := 1;
repeat
inc(sqN);
inc(sqNum,sqDelta);
inc(sqDelta,2);
IF sqNum>cbNum then
Begin
inc(cbN);
cbNum := cbNum+cbDelta2;
inc(cbDelta1,6);// 0,6,12,18...
inc(cbDelta2,cbDelta1);//1,7,19,35...
end;
IF sqNum <> cbNUm then
Begin
writeln(sqNum :25);
inc(CountSqNotCb);
end
else
Begin
writeln(sqNum:25,sqN:10,'*',sqN,' = ',cbN,'*',cbN,'*',cbN);
inc(CountSqANDCb);
end;
until CountSqNotCb >= 30;//sqrt(High(NativeUint));
writeln(CountSqANDCb,' where numbers are square and cube ');
end. |
http://rosettacode.org/wiki/Statistics/Basic | Statistics/Basic | Statistics is all about large groups of numbers.
When talking about a set of sampled data, most frequently used is their mean value and standard deviation (stddev).
If you have set of data
x
i
{\displaystyle x_{i}}
where
i
=
1
,
2
,
…
,
n
{\displaystyle i=1,2,\ldots ,n\,\!}
, the mean is
x
¯
≡
1
n
∑
i
x
i
{\displaystyle {\bar {x}}\equiv {1 \over n}\sum _{i}x_{i}}
, while the stddev is
σ
≡
1
n
∑
i
(
x
i
−
x
¯
)
2
{\displaystyle \sigma \equiv {\sqrt {{1 \over n}\sum _{i}\left(x_{i}-{\bar {x}}\right)^{2}}}}
.
When examining a large quantity of data, one often uses a histogram, which shows the counts of data samples falling into a prechosen set of intervals (or bins).
When plotted, often as bar graphs, it visually indicates how often each data value occurs.
Task Using your language's random number routine, generate real numbers in the range of [0, 1]. It doesn't matter if you chose to use open or closed range.
Create 100 of such numbers (i.e. sample size 100) and calculate their mean and stddev.
Do so for sample size of 1,000 and 10,000, maybe even higher if you feel like.
Show a histogram of any of these sets.
Do you notice some patterns about the standard deviation?
Extra Sometimes so much data need to be processed that it's impossible to keep all of them at once. Can you calculate the mean, stddev and histogram of a trillion numbers? (You don't really need to do a trillion numbers, just show how it can be done.)
Hint
For a finite population with equal probabilities at all points, one can derive:
(
x
−
x
¯
)
2
¯
=
x
2
¯
−
x
¯
2
{\displaystyle {\overline {(x-{\overline {x}})^{2}}}={\overline {x^{2}}}-{\overline {x}}^{2}}
Or, more verbosely:
1
N
∑
i
=
1
N
(
x
i
−
x
¯
)
2
=
1
N
(
∑
i
=
1
N
x
i
2
)
−
x
¯
2
.
{\displaystyle {\frac {1}{N}}\sum _{i=1}^{N}(x_{i}-{\overline {x}})^{2}={\frac {1}{N}}\left(\sum _{i=1}^{N}x_{i}^{2}\right)-{\overline {x}}^{2}.}
See also
Statistics/Normal distribution
Tasks for calculating statistical measures
in one go
moving (sliding window)
moving (cumulative)
Mean
Arithmetic
Statistics/Basic
Averages/Arithmetic mean
Averages/Pythagorean means
Averages/Simple moving average
Geometric
Averages/Pythagorean means
Harmonic
Averages/Pythagorean means
Quadratic
Averages/Root mean square
Circular
Averages/Mean angle
Averages/Mean time of day
Median
Averages/Median
Mode
Averages/Mode
Standard deviation
Statistics/Basic
Cumulative standard deviation
| #Wren | Wren | import "random" for Random
import "/math" for Nums
var r = Random.new()
for (i in [100, 1000, 10000]) {
var a = List.filled(i, 0)
for (j in 0...i) a[j] = r.float()
System.print("For %(i) random numbers:")
System.print(" mean = %(Nums.mean(a))")
System.print(" std/dev = %(Nums.popStdDev(a))")
var scale = i / 100
System.print(" scale = %(scale) per asterisk")
var sums = List.filled(10, 0)
for (e in a) {
var f = (e*10).floor
sums[f] = sums[f] + 1
}
for (j in 0..8) {
sums[j] = (sums[j] / scale).round
System.print(" 0.%(j) - 0.%(j+1): %("*" * sums[j])")
}
sums[9] = 100 - Nums.sum(sums[0..8])
System.print(" 0.9 - 1.0: %("*" * sums[9])\n")
} |
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
| #Ksh | Ksh |
#!/bin/ksh
# Split a character string based on change of character
# # Variables:
#
str='gHHH5YY++///\'
delim=', '
# # Functions:
#
# # Function _splitonchg(str, delim) - return str split by delim at char change
#
function _splitonchg {
typeset _str ; _str="$1"
typeset _delim ; _delim="$2"
typeset _i _splitstr ; integer _i
for ((_i=1; _i<${#_str}+1; _i++)); do
if [[ "${_str:$((_i-1)):1}" != "${_str:${_i}:1}" ]]; then
_splitstr+="${_str:$((_i-1)):1}${_delim}"
else
_splitstr+="${_str:$((_i-1)):1}"
fi
done
echo "${_splitstr%"${_delim}"*}"
}
######
# main #
######
print "Original: ${str}"
print " Split: $(_splitonchg "${str}" "${delim}")"
|
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
| #M2000_Interpreter | M2000 Interpreter |
Module PrintParts(splitthis$) {
Def string m$, p$
Def long c
Stack New {
if len(splitthis$)=0 then exit
For i=1 to len(splitthis$)
p$=mid$(splitthis$,i,1)
if m$<>p$ then {
if c>0 then data string$(m$, c)
m$=p$
c=1
} else c++
Next i
if c>0 then data string$(m$, c)
While stack.size>1 {
Print letter$+", ";
}
If not empty then Print letter$
}
}
PrintParts "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.
| #Snobol | Snobol | * GCD function
DEFINE('GCD(A,B)') :(GCD_END)
GCD GCD = A
EQ(B,0) :S(RETURN)
A = B
B = REMDR(GCD,B) :(GCD)
GCD_END
* Find first occurrence of element in array
DEFINE('IDX(ARR,ELM)') :(IDX_END)
IDX IDX = 1
ITEST EQ(ARR<IDX>,ELM) :S(RETURN)
IDX = IDX + 1 :(ITEST)
IDX_END
* Declare array
SEQ = ARRAY(1200,1)
* Fill array with Stern-Brocot sequence
IX = 1
FILL IX = IX + 1
SEQ<IX * 2 - 1> = SEQ<IX> + SEQ<IX - 1>
SEQ<IX * 2> = SEQ<IX> :S(FILL)
* Print first 15 elements
DONE IX = 1
S = "First 15 elements:"
P15 S = S " " SEQ<IX>
IX = IX + 1 LT(IX,15) :S(P15)
OUTPUT = S
* Print first occurrence of 1..10 and 100
N = 1
FIRSTN OUTPUT = "First " N " at " IDX(SEQ,N)
N = N + 1 LT(N,10) :S(FIRSTN)
OUTPUT = "First 100 at " IDX(SEQ,100)
* Test GCD between 1000 consecutive members
IX = 2
GCDTEST EQ(GCD(SEQ<IX - 1>,SEQ<IX>),1) :F(GCDFAIL)
IX = IX + 1 LT(IX,1000) :S(GCDTEST)
OUTPUT = "All GCDs are 1." :(END)
GCDFAIL OUTPUT = "GCD is not 1 at " IX "."
END |
http://rosettacode.org/wiki/Spinning_rod_animation/Text | Spinning rod animation/Text | Task
An animation with the following frames in the following order (if certain characters aren't available or can't be used correctly in the programming language, alternate characters can replace any of these frames) must animate with a delay of 0.25 seconds between each frame, with the previous frame being cleared before the next frame appears:
|
/
- or ─
\
A stand-alone version that loops and/or a version that doesn't loop can be made. These examples can also be converted into a system used in game development which is called on a HUD or GUI element requiring it to be called each frame to output the text, and advance the frame when the frame delay has passed. You can also use alternate text such as the . animation ( . | .. | ... | .. | repeat from . ) or the logic can be updated to include a ping/pong style where the frames advance forward, reach the end and then play backwards and when they reach the beginning they start over ( technically, you'd stop one frame prior to prevent the first frame playing twice, or write it another way ).
There are many different ways you can incorporate text animations. Here are a few text ideas - each frame is in quotes. If you can think of any, add them to this page! There are 2 examples for several of these; the first is the base animation with only unique sets of characters. The second consists of the primary set from a - n and doubled, minus the first and last element ie: We only want the center. This way an animation can play forwards, and then in reverse ( ping ponging ) without having to code that feature. For the animations with 3 elements, we only add 1, the center. with 4, it becomes 6. with 10, it becomes 18.
We don't need the second option for some of the animations if they connect smoothly, when animated, back to the first element. ... doesn't connect with . cleanly - there is a large leap. The rotating pipe meets the first perfectly so it isn't necessary, etc..
Dots - Option A requires ping / pong enabled script. Option B just adds the elements in the center.
'.', '..', '...'
'.', '..', '...', '..'
Pipe - This has the uniform sideways pipe instead of a hyphen to prevent non-uniform sizing.
'|', '/', '─', '\'
Stars - Option A requires ping / pong enabled script. Option B just adds the elements from the center.
'⁎', '⁑', '⁂'
'⁎', '⁑', '⁂', '⁑'
Clock - These need to be ordered. I haven't done this yet as the application I was testing the system in doesn't support these wingdings / icons. But this would look quite nice and you could set it up to go forward, or backward during an undo process, etc..
'🕛', '🕧', '🕐', '🕜', '🕑', '🕝', '🕒', '🕞', '🕓', '🕟', '🕔', '🕠', '🕕', '🕖', '🕗', '🕘', '🕙', '🕚', '🕡', '🕢', '🕣', '🕤', '🕥', '🕦'
Arrows:
'⬍', '⬈', '➞', '⬊', '⬍', '⬋', '⬅', '⬉'
Bird - This looks decent but may be missing something.
'︷', '︵', '︹', '︺', '︶', '︸'
'︷', '︵', '︹', '︺', '︶', '︸', '︶', '︺', '︹', '︵'
Plants - This isn't quite complete
'☘', '❀', '❁'
'☘', '❀', '❁', '❀'
Eclipse - From Raku Throbber post author
'🌑', '🌒', '🌓', '🌔', '🌕', '🌖', '🌗', '🌘'
| #Ruby | Ruby | def spinning_rod
begin
printf("\033[?25l") # Hide cursor
%w[| / - \\].cycle do |rod|
print rod
sleep 0.25
print "\b"
end
ensure
printf("\033[?25h") # Restore cursor
end
end
puts "Ctrl-c to stop."
spinning_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
'🌑', '🌒', '🌓', '🌔', '🌕', '🌖', '🌗', '🌘'
| #Rust | Rust | fn main() {
let characters = ['|', '/', '-', '\\'];
let mut current = 0;
println!("{}[2J", 27 as char); // Clear screen.
loop {
println!("{}[;H{}", 27 as char, characters[current]); // Move cursor to 1,1 and output the next character.
current += 1; // Advance current character.
if current == 4 {current = 0;} // If we reached the end of the array, start from the beginning.
std::thread::sleep(std::time::Duration::from_millis(250)); // Sleep 250 ms.
}
} |
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
| #D | D | import std.array;
class Stack(T) {
private T[] items;
@property bool empty() { return items.empty(); }
void push(T top) { items ~= top; }
T pop() {
if (this.empty)
throw new Exception("Empty Stack.");
auto top = items.back;
items.popBack();
return top;
}
}
void main() {
auto s = new Stack!int();
s.push(10);
s.push(20);
assert(s.pop() == 20);
assert(s.pop() == 10);
assert(s.empty());
} |
http://rosettacode.org/wiki/Spiral_matrix | Spiral matrix | Task
Produce a spiral array.
A spiral array is a square arrangement of the first N2 natural numbers, where the
numbers increase sequentially as you go around the edges of the array spiraling inwards.
For example, given 5, produce this array:
0 1 2 3 4
15 16 17 18 5
14 23 24 19 6
13 22 21 20 7
12 11 10 9 8
Related tasks
Zig-zag matrix
Identity_matrix
Ulam_spiral_(for_primes)
| #ALGOL_68 | ALGOL 68 | INT empty=0;
PROC spiral = (INT n)[,]INT: (
INT dx:=1, dy:=0; # Starting increments #
INT x:=0, y:=0; # Starting location #
[0:n-1,0:n-1]INT my array;
FOR y FROM LWB my array TO UPB my array DO
FOR x FROM LWB my array TO UPB my array DO
my array[x,y]:=empty
OD
OD;
FOR i TO n**2 DO
my array[x,y] := i;
INT nx:=x+dx, ny:=y+dy;
IF ( 0<=nx AND nx<n AND 0<=ny AND ny<n | my array[nx,ny] = empty | FALSE ) THEN
x:=nx; y:=ny
ELSE
INT swap:=dx; dx:=-dy; dy:=swap;
x+:=dx; y+:=dy
FI
OD;
my array
);
PROC print spiral = ([,]INT my array)VOID:(
FOR y FROM LWB my array TO UPB my array DO
FOR x FROM LWB my array TO UPB my array DO
print(whole(my array[x,y],-3))
OD;
print(new line)
OD
);
print spiral(spiral(5)) |
http://rosettacode.org/wiki/Special_variables | Special variables | Special variables have a predefined meaning within a computer programming language.
Task
List the special variables used within the language.
| #D | D | func Integer.Double() {
this + this
}
print(8.Double()) |
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.
| #DWScript | DWScript | func Integer.Double() {
this + this
}
print(8.Double()) |
http://rosettacode.org/wiki/Stable_marriage_problem | Stable marriage problem | Solve the Stable marriage problem using the Gale/Shapley algorithm.
Problem description
Given an equal number of men and women to be paired for marriage, each man ranks all the women in order of his preference and each woman ranks all the men in order of her preference.
A stable set of engagements for marriage is one where no man prefers a woman over the one he is engaged to, where that other woman also prefers that man over the one she is engaged to. I.e. with consulting marriages, there would be no reason for the engagements between the people to change.
Gale and Shapley proved that there is a stable set of engagements for any set of preferences and the first link above gives their algorithm for finding a set of stable engagements.
Task Specifics
Given ten males:
abe, bob, col, dan, ed, fred, gav, hal, ian, jon
And ten females:
abi, bea, cath, dee, eve, fay, gay, hope, ivy, jan
And a complete list of ranked preferences, where the most liked is to the left:
abe: abi, eve, cath, ivy, jan, dee, fay, bea, hope, gay
bob: cath, hope, abi, dee, eve, fay, bea, jan, ivy, gay
col: hope, eve, abi, dee, bea, fay, ivy, gay, cath, jan
dan: ivy, fay, dee, gay, hope, eve, jan, bea, cath, abi
ed: jan, dee, bea, cath, fay, eve, abi, ivy, hope, gay
fred: bea, abi, dee, gay, eve, ivy, cath, jan, hope, fay
gav: gay, eve, ivy, bea, cath, abi, dee, hope, jan, fay
hal: abi, eve, hope, fay, ivy, cath, jan, bea, gay, dee
ian: hope, cath, dee, gay, bea, abi, fay, ivy, jan, eve
jon: abi, fay, jan, gay, eve, bea, dee, cath, ivy, hope
abi: bob, fred, jon, gav, ian, abe, dan, ed, col, hal
bea: bob, abe, col, fred, gav, dan, ian, ed, jon, hal
cath: fred, bob, ed, gav, hal, col, ian, abe, dan, jon
dee: fred, jon, col, abe, ian, hal, gav, dan, bob, ed
eve: jon, hal, fred, dan, abe, gav, col, ed, ian, bob
fay: bob, abe, ed, ian, jon, dan, fred, gav, col, hal
gay: jon, gav, hal, fred, bob, abe, col, ed, dan, ian
hope: gav, jon, bob, abe, ian, dan, hal, ed, col, fred
ivy: ian, col, hal, gav, fred, bob, abe, ed, jon, dan
jan: ed, hal, gav, abe, bob, jon, col, ian, fred, dan
Use the Gale Shapley algorithm to find a stable set of engagements
Perturb this set of engagements to form an unstable set of engagements then check this new set for stability.
References
The Stable Marriage Problem. (Eloquent description and background information).
Gale-Shapley Algorithm Demonstration.
Another Gale-Shapley Algorithm Demonstration.
Stable Marriage Problem - Numberphile (Video).
Stable Marriage Problem (the math bit) (Video).
The Stable Marriage Problem and School Choice. (Excellent exposition)
| #Ceylon | Ceylon | abstract class Single(name) of Gal | Guy {
shared String name;
shared late Single[] preferences;
shared variable Single? fiance = null;
shared Boolean free => fiance is Null;
shared variable Integer currentProposalIndex = 0;
"Does this single prefer this other single over their fiance?"
shared Boolean prefers(Single otherSingle) =>
let (p1 = preferences.firstIndexWhere(otherSingle.equals), f = fiance)
if (!exists p1)
then false
else if (!exists f)
then true
else if (exists p2 = preferences.firstIndexWhere(f.equals))
then p1 < p2
else false;
string => name;
}
abstract class Guy(String name) of abe | bob | col | dan | ed | fred | gav | hal | ian | jon extends Single(name) {}
object abe extends Guy("Abe") {}
object bob extends Guy("Bob") {}
object col extends Guy("Col") {}
object dan extends Guy("Dan") {}
object ed extends Guy("Ed") {}
object fred extends Guy("Fred") {}
object gav extends Guy("Gav") {}
object hal extends Guy("Hal") {}
object ian extends Guy("Ian") {}
object jon extends Guy("Jon") {}
abstract class Gal(String name) of abi | bea | cath | dee | eve | fay | gay | hope | ivy | jan extends Single(name) {}
object abi extends Gal("Abi") {}
object bea extends Gal("Bea") {}
object cath extends Gal("Cath") {}
object dee extends Gal("Dee") {}
object eve extends Gal("Eve") {}
object fay extends Gal("Fay") {}
object gay extends Gal("Gay") {}
object hope extends Gal("Hope") {}
object ivy extends Gal("Ivy") {}
object jan extends Gal("Jan") {}
Guy[] guys = `Guy`.caseValues;
Gal[] gals = `Gal`.caseValues;
"The main function. Run this one."
shared void run() {
abe.preferences = [ abi, eve, cath, ivy, jan, dee, fay, bea, hope, gay ];
bob.preferences = [ cath, hope, abi, dee, eve, fay, bea, jan, ivy, gay ];
col.preferences = [ hope, eve, abi, dee, bea, fay, ivy, gay, cath, jan ];
dan.preferences = [ ivy, fay, dee, gay, hope, eve, jan, bea, cath, abi ];
ed.preferences = [ jan, dee, bea, cath, fay, eve, abi, ivy, hope, gay ];
fred.preferences = [ bea, abi, dee, gay, eve, ivy, cath, jan, hope, fay ];
gav.preferences = [ gay, eve, ivy, bea, cath, abi, dee, hope, jan, fay ];
hal.preferences = [ abi, eve, hope, fay, ivy, cath, jan, bea, gay, dee ];
ian.preferences = [ hope, cath, dee, gay, bea, abi, fay, ivy, jan, eve ];
jon.preferences = [ abi, fay, jan, gay, eve, bea, dee, cath, ivy, hope ];
abi.preferences = [ bob, fred, jon, gav, ian, abe, dan, ed, col, hal ];
bea.preferences = [ bob, abe, col, fred, gav, dan, ian, ed, jon, hal ];
cath.preferences = [ fred, bob, ed, gav, hal, col, ian, abe, dan, jon ];
dee.preferences = [ fred, jon, col, abe, ian, hal, gav, dan, bob, ed ];
eve.preferences = [ jon, hal, fred, dan, abe, gav, col, ed, ian, bob ];
fay.preferences = [ bob, abe, ed, ian, jon, dan, fred, gav, col, hal ];
gay.preferences = [ jon, gav, hal, fred, bob, abe, col, ed, dan, ian ];
hope.preferences = [ gav, jon, bob, abe, ian, dan, hal, ed, col, fred ];
ivy.preferences = [ ian, col, hal, gav, fred, bob, abe, ed, jon, dan ];
jan.preferences = [ ed, hal, gav, abe, bob, jon, col, ian, fred, dan ];
print("------ the matchmaking process ------");
matchmake();
print("------ the final engagements ------");
for (guy in guys) {
print("``guy`` is engaged to ``guy.fiance else "no one"``");
}
print("------ is it stable? ------");
checkStability();
value temp = jon.fiance;
jon.fiance = fred.fiance;
fred.fiance = temp;
print("------ is it stable after switching jon and fred's partners? ------");
checkStability();
}
"Match up all the singles with the Gale/Shapley algorithm."
void matchmake() {
while (true) {
value singleGuys = guys.filter(Guy.free);
if (singleGuys.empty) {
return;
}
for (guy in singleGuys) {
if (exists gal = guy.preferences[guy.currentProposalIndex]) {
guy.currentProposalIndex++;
value fiance = gal.fiance;
if (!exists fiance) {
print("``guy`` and ``gal`` just got engaged!");
guy.fiance = gal;
gal.fiance = guy;
}
else {
if (gal.prefers(guy)) {
print("``gal`` dumped ``fiance`` for ``guy``!");
fiance.fiance = null;
gal.fiance = guy;
guy.fiance = gal;
}
else {
print("``gal`` turned down ``guy`` and stayed with ``fiance``!");
}
}
}
}
}
}
void checkStability() {
variable value stabilityFlag = true;
for (gal in gals) {
for (guy in guys) {
if (guy.prefers(gal) && gal.prefers(guy)) {
stabilityFlag = false;
print("``guy`` prefers ``gal`` over ``guy.fiance else "nobody"``
and ``gal`` prefers ``guy`` over ``gal.fiance else "nobody"``!".normalized);
}
}
}
print("``if(!stabilityFlag) then "Not " else ""``Stable!");
} |
http://rosettacode.org/wiki/Spelling_of_ordinal_numbers | Spelling of ordinal numbers | Ordinal numbers (as used in this Rosetta Code task), are numbers that describe the position of something in a list.
It is this context that ordinal numbers will be used, using an English-spelled name of an ordinal number.
The ordinal numbers are (at least, one form of them):
1st 2nd 3rd 4th 5th 6th 7th ··· 99th 100th ··· 1000000000th ··· etc
sometimes expressed as:
1st 2nd 3rd 4th 5th 6th 7th ··· 99th 100th ··· 1000000000th ···
For this task, the following (English-spelled form) will be used:
first second third fourth fifth sixth seventh ninety-nineth one hundredth one billionth
Furthermore, the American version of numbers will be used here (as opposed to the British).
2,000,000,000 is two billion, not two milliard.
Task
Write a driver and a function (subroutine/routine ···) that returns the English-spelled ordinal version of a specified number (a positive integer).
Optionally, try to support as many forms of an integer that can be expressed: 123 00123.0 1.23e2 all are forms of the same integer.
Show all output here.
Test cases
Use (at least) the test cases of:
1 2 3 4 5 11 65 100 101 272 23456 8007006005004003
Related tasks
Number names
N'th
| #Python | Python | irregularOrdinals = {
"one": "first",
"two": "second",
"three": "third",
"five": "fifth",
"eight": "eighth",
"nine": "ninth",
"twelve": "twelfth",
}
def num2ordinal(n):
conversion = int(float(n))
num = spell_integer(conversion)
hyphen = num.rsplit("-", 1)
num = num.rsplit(" ", 1)
delim = " "
if len(num[-1]) > len(hyphen[-1]):
num = hyphen
delim = "-"
if num[-1] in irregularOrdinals:
num[-1] = delim + irregularOrdinals[num[-1]]
elif num[-1].endswith("y"):
num[-1] = delim + num[-1][:-1] + "ieth"
else:
num[-1] = delim + num[-1] + "th"
return "".join(num)
if __name__ == "__main__":
tests = "1 2 3 4 5 11 65 100 101 272 23456 8007006005004003 123 00123.0 1.23e2".split()
for num in tests:
print("{} => {}".format(num, num2ordinal(num)))
#This is a copy of the code from https://rosettacode.org/wiki/Number_names#Python
TENS = [None, None, "twenty", "thirty", "forty",
"fifty", "sixty", "seventy", "eighty", "ninety"]
SMALL = ["zero", "one", "two", "three", "four", "five",
"six", "seven", "eight", "nine", "ten", "eleven",
"twelve", "thirteen", "fourteen", "fifteen",
"sixteen", "seventeen", "eighteen", "nineteen"]
HUGE = [None, None] + [h + "illion"
for h in ("m", "b", "tr", "quadr", "quint", "sext",
"sept", "oct", "non", "dec")]
def nonzero(c, n, connect=''):
return "" if n == 0 else connect + c + spell_integer(n)
def last_and(num):
if ',' in num:
pre, last = num.rsplit(',', 1)
if ' and ' not in last:
last = ' and' + last
num = ''.join([pre, ',', last])
return num
def big(e, n):
if e == 0:
return spell_integer(n)
elif e == 1:
return spell_integer(n) + " thousand"
else:
return spell_integer(n) + " " + HUGE[e]
def base1000_rev(n):
# generates the value of the digits of n in base 1000
# (i.e. 3-digit chunks), in reverse.
while n != 0:
n, r = divmod(n, 1000)
yield r
def spell_integer(n):
if n < 0:
return "minus " + spell_integer(-n)
elif n < 20:
return SMALL[n]
elif n < 100:
a, b = divmod(n, 10)
return TENS[a] + nonzero("-", b)
elif n < 1000:
a, b = divmod(n, 100)
return SMALL[a] + " hundred" + nonzero(" ", b, ' and')
else:
num = ", ".join([big(e, x) for e, x in
enumerate(base1000_rev(n)) if x][::-1])
return last_and(num) |
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.
| #Perl | Perl | while ($cnt < 30) {
$n++;
$h{$n**2}++;
$h{$n**3}--;
$cnt++ if $h{$n**2} > 0;
}
print "First 30 positive integers that are a square but not a cube:\n";
print "$_ " for sort { $a <=> $b } grep { $h{$_} == 1 } keys %h;
print "\n\nFirst 3 positive integers that are both a square and a cube:\n";
print "$_ " for sort { $a <=> $b } grep { $h{$_} == 0 } keys %h; |
http://rosettacode.org/wiki/Statistics/Basic | Statistics/Basic | Statistics is all about large groups of numbers.
When talking about a set of sampled data, most frequently used is their mean value and standard deviation (stddev).
If you have set of data
x
i
{\displaystyle x_{i}}
where
i
=
1
,
2
,
…
,
n
{\displaystyle i=1,2,\ldots ,n\,\!}
, the mean is
x
¯
≡
1
n
∑
i
x
i
{\displaystyle {\bar {x}}\equiv {1 \over n}\sum _{i}x_{i}}
, while the stddev is
σ
≡
1
n
∑
i
(
x
i
−
x
¯
)
2
{\displaystyle \sigma \equiv {\sqrt {{1 \over n}\sum _{i}\left(x_{i}-{\bar {x}}\right)^{2}}}}
.
When examining a large quantity of data, one often uses a histogram, which shows the counts of data samples falling into a prechosen set of intervals (or bins).
When plotted, often as bar graphs, it visually indicates how often each data value occurs.
Task Using your language's random number routine, generate real numbers in the range of [0, 1]. It doesn't matter if you chose to use open or closed range.
Create 100 of such numbers (i.e. sample size 100) and calculate their mean and stddev.
Do so for sample size of 1,000 and 10,000, maybe even higher if you feel like.
Show a histogram of any of these sets.
Do you notice some patterns about the standard deviation?
Extra Sometimes so much data need to be processed that it's impossible to keep all of them at once. Can you calculate the mean, stddev and histogram of a trillion numbers? (You don't really need to do a trillion numbers, just show how it can be done.)
Hint
For a finite population with equal probabilities at all points, one can derive:
(
x
−
x
¯
)
2
¯
=
x
2
¯
−
x
¯
2
{\displaystyle {\overline {(x-{\overline {x}})^{2}}}={\overline {x^{2}}}-{\overline {x}}^{2}}
Or, more verbosely:
1
N
∑
i
=
1
N
(
x
i
−
x
¯
)
2
=
1
N
(
∑
i
=
1
N
x
i
2
)
−
x
¯
2
.
{\displaystyle {\frac {1}{N}}\sum _{i=1}^{N}(x_{i}-{\overline {x}})^{2}={\frac {1}{N}}\left(\sum _{i=1}^{N}x_{i}^{2}\right)-{\overline {x}}^{2}.}
See also
Statistics/Normal distribution
Tasks for calculating statistical measures
in one go
moving (sliding window)
moving (cumulative)
Mean
Arithmetic
Statistics/Basic
Averages/Arithmetic mean
Averages/Pythagorean means
Averages/Simple moving average
Geometric
Averages/Pythagorean means
Harmonic
Averages/Pythagorean means
Quadratic
Averages/Root mean square
Circular
Averages/Mean angle
Averages/Mean time of day
Median
Averages/Median
Mode
Averages/Mode
Standard deviation
Statistics/Basic
Cumulative standard deviation
| #zkl | zkl | fcn mean(ns) { ns.sum(0.0)/ns.len() }
fcn stdDev(ns){
m:=mean(ns); (ns.reduce('wrap(p,n){ x:=(n-m); p+x*x },0.0)/ns.len()).sqrt()
} |
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
| #Maple | Maple | splitChange := proc(str::string)
local start,i,len;
start := 1;
len := StringTools:-Length(str);
for i from 2 to len do
if str[i] <> str[start] then
printf("%s, ", str[start..i-1]);
start := i:
end if;
end do;
printf("%s", str[start..len]);
end proc;
splitChange("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
| #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | StringJoin@@Riffle[StringCases["gHHH5YY++///\\", p : (x_) .. -> p], ", "] |
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.
| #Swift | Swift | struct SternBrocot: Sequence, IteratorProtocol {
private var seq = [1, 1]
mutating func next() -> Int? {
seq += [seq[0] + seq[1], seq[1]]
return seq.removeFirst()
}
}
func gcd<T: BinaryInteger>(_ a: T, _ b: T) -> T {
guard a != 0 else {
return b
}
return a < b ? gcd(b % a, a) : gcd(a % b, b)
}
print("First 15: \(Array(SternBrocot().prefix(15)))")
var found = Set<Int>()
for (i, val) in SternBrocot().enumerated() {
switch val {
case 1...10 where !found.contains(val), 100 where !found.contains(val):
print("First \(val) at \(i + 1)")
found.insert(val)
case _:
continue
}
if found.count == 11 {
break
}
}
let firstThousand = SternBrocot().prefix(1000)
let gcdIsOne = zip(firstThousand, firstThousand.dropFirst()).allSatisfy({ gcd($0.0, $0.1) == 1 })
print("GCDs of all two consecutive members are \(gcdIsOne ? "" : "not")one") |
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
'🌑', '🌒', '🌓', '🌔', '🌕', '🌖', '🌗', '🌘'
| #Scala | Scala | object SpinningRod extends App {
val start = System.currentTimeMillis
def a = "|/-\\"
print("\033[2J") // hide the cursor
while (System.currentTimeMillis - start < 20000) {
for (i <- 0 until 4) {
print("\033[2J\033[0;0H") // clear terminal, place cursor at top left corner
for (j <- 0 until 80) print(a(i)) // 80 character terminal width, say
Thread.sleep(250)
}
}
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
| #Delphi | Delphi | program Stack;
{$APPTYPE CONSOLE}
uses Generics.Collections;
var
lStack: TStack<Integer>;
begin
lStack := TStack<Integer>.Create;
try
lStack.Push(1);
lStack.Push(2);
lStack.Push(3);
Assert(lStack.Peek = 3); // 3 should be at the top of the stack
Writeln(lStack.Pop); // 3
Writeln(lStack.Pop); // 2
Writeln(lStack.Pop); // 1
Assert(lStack.Count = 0); // should be empty
finally
lStack.Free;
end;
end. |
http://rosettacode.org/wiki/Spiral_matrix | Spiral matrix | Task
Produce a spiral array.
A spiral array is a square arrangement of the first N2 natural numbers, where the
numbers increase sequentially as you go around the edges of the array spiraling inwards.
For example, given 5, produce this array:
0 1 2 3 4
15 16 17 18 5
14 23 24 19 6
13 22 21 20 7
12 11 10 9 8
Related tasks
Zig-zag matrix
Identity_matrix
Ulam_spiral_(for_primes)
| #AppleScript | AppleScript | ---------------------- SPIRAL MATRIX ---------------------
-- spiral :: Int -> [[Int]]
on spiral(n)
script go
on |λ|(rows, cols, start)
if 0 < rows then
{enumFromTo(start, start + pred(cols))} & ¬
map(my |reverse|, ¬
transpose(|λ|(cols, pred(rows), start + cols)))
else
{{}}
end if
end |λ|
end script
go's |λ|(n, n, 0)
end spiral
--------------------------- TEST -------------------------
on run
wikiTable(spiral(5), ¬
false, ¬
"text-align:center;width:12em;height:12em;table-layout:fixed;")
end run
-------------------- WIKI TABLE FORMAT -------------------
-- wikiTable :: [Text] -> Bool -> Text -> Text
on wikiTable(lstRows, blnHdr, strStyle)
script fWikiRows
on |λ|(lstRow, iRow)
set strDelim to if_(blnHdr and (iRow = 0), "!", "|")
set strDbl to strDelim & strDelim
linefeed & "|-" & linefeed & strDelim & space & ¬
intercalateS(space & strDbl & space, lstRow)
end |λ|
end script
linefeed & "{| class=\"wikitable\" " & ¬
if_(strStyle ≠ "", "style=\"" & strStyle & "\"", "") & ¬
intercalateS("", ¬
map(fWikiRows, lstRows)) & linefeed & "|}" & linefeed
end wikiTable
------------------------- GENERIC ------------------------
-- comparing :: (a -> b) -> (a -> a -> Ordering)
on comparing(f)
script
on |λ|(a, b)
tell mReturn(f)
set fa to |λ|(a)
set fb to |λ|(b)
if fa < fb then
-1
else if fa > fb then
1
else
0
end if
end tell
end |λ|
end script
end comparing
-- concatMap :: (a -> [b]) -> [a] -> [b]
on concatMap(f, xs)
set lng to length of xs
set acc to {}
tell mReturn(f)
repeat with i from 1 to lng
set acc to acc & (|λ|(item i of xs, i, xs))
end repeat
end tell
if {text, string} contains class of xs then
acc as text
else
acc
end if
end concatMap
-- enumFromTo :: Int -> Int -> [Int]
on enumFromTo(m, n)
if m ≤ n then
set lst to {}
repeat with i from m to n
set end of lst to i
end repeat
return lst
else
return {}
end if
end enumFromTo
-- foldl :: (a -> b -> a) -> a -> [b] -> a
on foldl(f, startValue, xs)
tell mReturn(f)
set v to startValue
set lng to length of xs
repeat with i from 1 to lng
set v to |λ|(v, item i of xs, i, xs)
end repeat
return v
end tell
end foldl
-- if_ :: Bool -> a -> a -> a
on if_(bool, x, y)
if bool then
x
else
y
end if
end if_
-- intercalateS :: String -> [String] -> String
on intercalateS(sep, xs)
set {dlm, my text item delimiters} to {my text item delimiters, sep}
set s to xs as text
set my text item delimiters to dlm
return s
end intercalateS
-- length :: [a] -> Int
on |length|(xs)
length of xs
end |length|
-- max :: Ord a => a -> a -> a
on max(x, y)
if x > y then
x
else
y
end if
end max
-- maximumBy :: (a -> a -> Ordering) -> [a] -> a
on maximumBy(f, xs)
set cmp to mReturn(f)
script max
on |λ|(a, b)
if a is missing value or cmp's |λ|(a, b) < 0 then
b
else
a
end if
end |λ|
end script
foldl(max, missing value, xs)
end maximumBy
-- Lift 2nd class handler function into 1st class script wrapper
-- mReturn :: First-class m => (a -> b) -> m (a -> b)
on mReturn(f)
if class of f is script then
f
else
script
property |λ| : f
end script
end if
end mReturn
-- map :: (a -> b) -> [a] -> [b]
on map(f, xs)
tell mReturn(f)
set lng to length of xs
set lst to {}
repeat with i from 1 to lng
set end of lst to |λ|(item i of xs, i, xs)
end repeat
return lst
end tell
end map
-- pred :: Enum a => a -> a
on pred(x)
x - 1
end pred
-- Egyptian multiplication - progressively doubling a list, appending
-- stages of doubling to an accumulator where needed for binary
-- assembly of a target length
-- replicate :: Int -> a -> [a]
on replicate(n, a)
set out to {}
if n < 1 then return out
set dbl to {a}
repeat while (n > 1)
if (n mod 2) > 0 then set out to out & dbl
set n to (n div 2)
set dbl to (dbl & dbl)
end repeat
return out & dbl
end replicate
-- reverse :: [a] -> [a]
on |reverse|(xs)
if class of xs is text then
(reverse of characters of xs) as text
else
reverse of xs
end if
end |reverse|
-- Simplified version - assuming rows of unvarying length.
-- transpose :: [[a]] -> [[a]]
on transpose(rows)
script cols
on |λ|(_, iCol)
script cell
on |λ|(row)
item iCol of row
end |λ|
end script
concatMap(cell, rows)
end |λ|
end script
map(cols, item 1 of rows)
end transpose
-- unlines :: [String] -> String
on unlines(xs)
set {dlm, my text item delimiters} to ¬
{my text item delimiters, linefeed}
set str to xs as text
set my text item delimiters to dlm
str
end unlines
-- unwords :: [String] -> String
on unwords(xs)
intercalateS(space, xs)
end unwords |
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.
| #Dyalect | Dyalect | func Integer.Double() {
this + this
}
print(8.Double()) |
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.
| #D.C3.A9j.C3.A0_Vu | Déjà Vu | set setglobal local get getlocal return recurse drop dup swap rot over
[] {} pop-from push-to push-through has get-from set-to raise reraise
call for pass |
http://rosettacode.org/wiki/Special_characters | Special characters | Special characters are symbols (single characters or sequences of characters) that have a "special" built-in meaning in the language and typically cannot be used in identifiers.
Escape sequences are methods that the language uses to remove the special meaning from the symbol, enabling it to be used as a normal character, or sequence of characters when this can be done.
Task
List the special characters and show escape sequences in the language.
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
| #11l | 11l | with Ada.Text_IO; use Ada.Text_IO;
procedure Test is
begin
Put ("Quote """ & ''' & """" & Character'Val (10));
end Test; |
http://rosettacode.org/wiki/Sparkline_in_unicode | Sparkline in unicode | A sparkline is a graph of successive values laid out horizontally
where the height of the line is proportional to the values in succession.
Task
Use the following series of Unicode characters to create a program
that takes a series of numbers separated by one or more whitespace or comma characters
and generates a sparkline-type bar graph of the values on a single line of output.
The eight characters: '▁▂▃▄▅▆▇█'
(Unicode values U+2581 through U+2588).
Use your program to show sparklines for the following input,
here on this page:
1 2 3 4 5 6 7 8 7 6 5 4 3 2 1
1.5, 0.5 3.5, 2.5 5.5, 4.5 7.5, 6.5
(note the mix of separators in this second case)!
Notes
A space is not part of the generated sparkline.
The sparkline may be accompanied by simple statistics of the data such as its range.
A suggestion emerging in later discussion (see Discussion page) is that the bounds between bins should ideally be set to yield the following results for two particular edge cases:
"0, 1, 19, 20" -> ▁▁██
(Aiming to use just two spark levels)
"0, 999, 4000, 4999, 7000, 7999" -> ▁▁▅▅██
(Aiming to use just three spark levels)
It may be helpful to include these cases in output tests.
You may find that the unicode sparklines on this page are rendered less noisily by Google Chrome than by Firefox or Safari.
| #APL | APL | sparkln←{'▁▂▃▄▅▆▇█'[⌊0.5+7×⍵÷⌈/⍵]} |
http://rosettacode.org/wiki/Sorting_algorithms/Strand_sort | Sorting algorithms/Strand sort |
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
O(n2) sorts
Bubble sort |
Cocktail sort |
Cocktail sort with shifting bounds |
Comb sort |
Cycle sort |
Gnome sort |
Insertion sort |
Selection sort |
Strand sort
other sorts
Bead sort |
Bogo sort |
Common sorted list |
Composite structures sort |
Custom comparator sort |
Counting sort |
Disjoint sublist sort |
External sort |
Jort sort |
Lexicographical sort |
Natural sorting |
Order by pair comparisons |
Order disjoint list items |
Order two numerical lists |
Object identifier (OID) sort |
Pancake sort |
Quickselect |
Permutation sort |
Radix sort |
Ranking methods |
Remove duplicate elements |
Sleep sort |
Stooge sort |
[Sort letters of a string] |
Three variable sort |
Topological sort |
Tree sort
This page uses content from Wikipedia. The original article was at Strand sort. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Task
Implement the Strand sort.
This is a way of sorting numbers by extracting shorter sequences of already sorted numbers from an unsorted list.
| #11l | 11l | F merge_list(&a, &b)
[Int] out
L !a.empty & !b.empty
I a[0] < b[0]
out.append(a.pop(0))
E
out.append(b.pop(0))
out [+]= a
out [+]= b
R out
F strand(&a)
V i = 0
V s = [a.pop(0)]
L i < a.len
I a[i] > s.last
s.append(a.pop(i))
E
i++
R s
F strand_sort(&a)
V out = strand(&a)
L !a.empty
out = merge_list(&out, &strand(&a))
R out
print(strand_sort(&[1, 6, 3, 2, 1, 7, 5, 3])) |
http://rosettacode.org/wiki/Stable_marriage_problem | Stable marriage problem | Solve the Stable marriage problem using the Gale/Shapley algorithm.
Problem description
Given an equal number of men and women to be paired for marriage, each man ranks all the women in order of his preference and each woman ranks all the men in order of her preference.
A stable set of engagements for marriage is one where no man prefers a woman over the one he is engaged to, where that other woman also prefers that man over the one she is engaged to. I.e. with consulting marriages, there would be no reason for the engagements between the people to change.
Gale and Shapley proved that there is a stable set of engagements for any set of preferences and the first link above gives their algorithm for finding a set of stable engagements.
Task Specifics
Given ten males:
abe, bob, col, dan, ed, fred, gav, hal, ian, jon
And ten females:
abi, bea, cath, dee, eve, fay, gay, hope, ivy, jan
And a complete list of ranked preferences, where the most liked is to the left:
abe: abi, eve, cath, ivy, jan, dee, fay, bea, hope, gay
bob: cath, hope, abi, dee, eve, fay, bea, jan, ivy, gay
col: hope, eve, abi, dee, bea, fay, ivy, gay, cath, jan
dan: ivy, fay, dee, gay, hope, eve, jan, bea, cath, abi
ed: jan, dee, bea, cath, fay, eve, abi, ivy, hope, gay
fred: bea, abi, dee, gay, eve, ivy, cath, jan, hope, fay
gav: gay, eve, ivy, bea, cath, abi, dee, hope, jan, fay
hal: abi, eve, hope, fay, ivy, cath, jan, bea, gay, dee
ian: hope, cath, dee, gay, bea, abi, fay, ivy, jan, eve
jon: abi, fay, jan, gay, eve, bea, dee, cath, ivy, hope
abi: bob, fred, jon, gav, ian, abe, dan, ed, col, hal
bea: bob, abe, col, fred, gav, dan, ian, ed, jon, hal
cath: fred, bob, ed, gav, hal, col, ian, abe, dan, jon
dee: fred, jon, col, abe, ian, hal, gav, dan, bob, ed
eve: jon, hal, fred, dan, abe, gav, col, ed, ian, bob
fay: bob, abe, ed, ian, jon, dan, fred, gav, col, hal
gay: jon, gav, hal, fred, bob, abe, col, ed, dan, ian
hope: gav, jon, bob, abe, ian, dan, hal, ed, col, fred
ivy: ian, col, hal, gav, fred, bob, abe, ed, jon, dan
jan: ed, hal, gav, abe, bob, jon, col, ian, fred, dan
Use the Gale Shapley algorithm to find a stable set of engagements
Perturb this set of engagements to form an unstable set of engagements then check this new set for stability.
References
The Stable Marriage Problem. (Eloquent description and background information).
Gale-Shapley Algorithm Demonstration.
Another Gale-Shapley Algorithm Demonstration.
Stable Marriage Problem - Numberphile (Video).
Stable Marriage Problem (the math bit) (Video).
The Stable Marriage Problem and School Choice. (Excellent exposition)
| #CoffeeScript | CoffeeScript | class Person
constructor: (@name, @preferences) ->
@mate = null
@best_mate_rank = 0
@rank = {}
for preference, i in @preferences
@rank[preference] = i
preferred_mate_name: =>
@preferences[@best_mate_rank]
reject: =>
@best_mate_rank += 1
set_mate: (mate) =>
@mate = mate
offer_mate: (free_mate, reject_mate_cb) =>
if @mate
if @covets(free_mate)
console.log "#{free_mate.name} steals #{@name} from #{@mate.name}"
reject_mate_cb @mate
free_mate.set_mate @
@set_mate free_mate
else
console.log "#{free_mate.name} cannot steal #{@name} from #{@mate.name}"
reject_mate_cb free_mate
else
console.log "#{free_mate.name} gets #{@name} first"
free_mate.set_mate @
@set_mate free_mate
happiness: =>
@rank[@mate.name]
covets: (other_mate) =>
@rank[other_mate.name] <= @rank[@mate.name]
persons_by_name = (persons) ->
hsh = {}
for person in persons
hsh[person.name] = person
hsh
mate_off = (guys, gals) ->
free_pursuers = (guy for guy in guys)
guys_by_name = persons_by_name guys
gals_by_name = persons_by_name gals
while free_pursuers.length > 0
free_pursuer = free_pursuers.shift()
gal_name = free_pursuer.preferred_mate_name()
gal = gals_by_name[gal_name]
reject_mate_cb = (guy) ->
guy.reject()
free_pursuers.push guy
gal.offer_mate free_pursuer, reject_mate_cb
report_on_mates = (guys) ->
console.log "\n----Marriage Report"
for guy, i in guys
throw Error("illegal marriage") if guy.mate.mate isnt guy
console.log guy.name, guy.mate.name, \
"(his choice #{guy.happiness()}, her choice #{guy.mate.happiness()} )"
report_potential_adulteries = (guys) ->
for guy1, i in guys
gal1 = guy1.mate
for j in [0...i]
guy2 = guys[j]
gal2 = guy2.mate
if guy1.covets(gal2) and gal2.covets(guy1)
console.log "#{guy1.name} and #{gal2.name} would stray"
if guy2.covets(gal1) and gal1.covets(guy2)
console.log "#{guy2.name} and #{gal1.name} would stray"
perturb = (guys) ->
# mess up marriages by swapping two couples...this is mainly to drive
# out that report_potential_adulteries will actually work
guy0 = guys[0]
guy1 = guys[1]
gal0 = guy0.mate
gal1 = guy1.mate
console.log "\nPerturbing with #{guy0.name}, #{gal0.name}, #{guy1.name}, #{gal1.name}"
guy0.set_mate gal1
guy1.set_mate gal0
gal1.set_mate guy0
gal0.set_mate guy1
Population = ->
guy_preferences =
abe: ['abi', 'eve', 'cath', 'ivy', 'jan', 'dee', 'fay', 'bea', 'hope', 'gay']
bob: ['cath', 'hope', 'abi', 'dee', 'eve', 'fay', 'bea', 'jan', 'ivy', 'gay']
col: ['hope', 'eve', 'abi', 'dee', 'bea', 'fay', 'ivy', 'gay', 'cath', 'jan']
dan: ['ivy', 'fay', 'dee', 'gay', 'hope', 'eve', 'jan', 'bea', 'cath', 'abi']
ed: ['jan', 'dee', 'bea', 'cath', 'fay', 'eve', 'abi', 'ivy', 'hope', 'gay']
fred: ['bea', 'abi', 'dee', 'gay', 'eve', 'ivy', 'cath', 'jan', 'hope', 'fay']
gav: ['gay', 'eve', 'ivy', 'bea', 'cath', 'abi', 'dee', 'hope', 'jan', 'fay']
hal: ['abi', 'eve', 'hope', 'fay', 'ivy', 'cath', 'jan', 'bea', 'gay', 'dee']
ian: ['hope', 'cath', 'dee', 'gay', 'bea', 'abi', 'fay', 'ivy', 'jan', 'eve']
jon: ['abi', 'fay', 'jan', 'gay', 'eve', 'bea', 'dee', 'cath', 'ivy', 'hope']
gal_preferences =
abi: ['bob', 'fred', 'jon', 'gav', 'ian', 'abe', 'dan', 'ed', 'col', 'hal']
bea: ['bob', 'abe', 'col', 'fred', 'gav', 'dan', 'ian', 'ed', 'jon', 'hal']
cath: ['fred', 'bob', 'ed', 'gav', 'hal', 'col', 'ian', 'abe', 'dan', 'jon']
dee: ['fred', 'jon', 'col', 'abe', 'ian', 'hal', 'gav', 'dan', 'bob', 'ed']
eve: ['jon', 'hal', 'fred', 'dan', 'abe', 'gav', 'col', 'ed', 'ian', 'bob']
fay: ['bob', 'abe', 'ed', 'ian', 'jon', 'dan', 'fred', 'gav', 'col', 'hal']
gay: ['jon', 'gav', 'hal', 'fred', 'bob', 'abe', 'col', 'ed', 'dan', 'ian']
hope: ['gav', 'jon', 'bob', 'abe', 'ian', 'dan', 'hal', 'ed', 'col', 'fred']
ivy: ['ian', 'col', 'hal', 'gav', 'fred', 'bob', 'abe', 'ed', 'jon', 'dan']
jan: ['ed', 'hal', 'gav', 'abe', 'bob', 'jon', 'col', 'ian', 'fred', 'dan']
guys = (new Person(name, preferences) for name, preferences of guy_preferences)
gals = (new Person(name, preferences) for name, preferences of gal_preferences)
[guys, gals]
do ->
[guys, gals] = Population()
mate_off guys, gals
report_on_mates guys
report_potential_adulteries guys
perturb guys
report_on_mates guys
report_potential_adulteries guys |
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
| #Raku | Raku | use Lingua::EN::Numbers;
# The task
+$_ ?? printf( "Type: \%-14s %16s : %s\n", .^name, $_, .&ordinal ) !! say "\n$_:" for
# Testing
'Required tests',
1, 2, 3, 4, 5, 11, 65, 100, 101, 272, 23456, 8007006005004003,
'Optional tests - different forms of 123',
'Numerics',
123, 00123.0, 1.23e2, 123+0i,
'Allomorphs',
|<123 1_2_3 00123.0 1.23e2 123+0i 0b1111011 0o173 0x7B 861/7>,
'Numeric Strings',
|'1_2_3 00123.0 1.23e2 123+0i 0b1111011 0o173 0x7B 861/7'.words,
'Unicode Numeric Strings',
# (Only using groups of digits from the same Unicode block. Technically,
# digits from any block could be combined with digits from any other block.)
|(^0x1FFFF).grep( { .chr ~~ /<:Nd>/ and .unival == 1|2|3 }).rotor(3)».chr».join,
'Role Mixin',
'17' but 123; |
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.
| #Phix | Phix | integer square = 1, squared = 1*1,
cube = 1, cubed = 1*1*1,
count = 0
while count<30 do
squared = square*square
while squared>cubed do cube += 1; cubed = cube*cube*cube end while
if squared=cubed then
printf(1,"%d: %d == %d^3\n",{square,squared,cube})
else
count += 1
printf(1,"%d: %d\n",{square,squared})
end if
square += 1
end while
printf(1,"\nThe first 15 positive integers that are both a square and a cube: \n")
?sq_power(tagset(15),6)
|
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
| #MiniScript | MiniScript | s = "gHHH5YY++///\"
output = []
lastLetter = s[0]
for letter in s
if letter != lastLetter then output.push ", "
output.push letter
lastLetter = letter
end for
print output.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
| #Modula-2 | Modula-2 | MODULE CharacterChange;
FROM Terminal IMPORT Write,WriteString,WriteLn,ReadChar;
PROCEDURE Split(str : ARRAY OF CHAR);
VAR
i : CARDINAL;
c : CHAR;
BEGIN
FOR i:=0 TO HIGH(str) DO
IF i=0 THEN
c := str[i]
ELSIF str[i]#c THEN
c := str[i];
WriteLn;
END;
Write(c)
END
END Split;
CONST EX = "gHHH5YY++///\";
BEGIN
Split(EX);
ReadChar
END CharacterChange. |
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.
| #Tcl | Tcl |
#!/usr/bin/env tclsh
#
package require generator ;# from tcllib
namespace eval stern-brocot {
proc generate {{count 100}} {
set seq {1 1}
set n 0
while {[llength $seq] < $count} {
lassign [lrange $seq $n $n+1] a b
lappend seq [expr {$a + $b}] $b
incr n
}
return $seq
}
proc genr {} {
yield [info coroutine]
set seq {1 1}
while {1} {
set seq [lassign $seq a]
set b [lindex $seq 0]
set c [expr {$a + $b}]
lappend seq $c $b
yield $a
}
}
proc Step {a b args} {
set c [expr {$a + $b}]
list $a [list $b {*}$args $c $b]
}
generator define gen {} {
set cmd [list 1 1]
while {1} {
lassign [Step {*}$cmd] a cmd
generator yield $a
}
}
namespace export {[a-z]*}
namespace ensemble create
}
interp alias {} sb {} stern-brocot
# a simple adaptation of gcd from http://wiki.tcl.tk/2891
proc coprime {a args} {
set gcd $a
foreach arg $args {
while {$arg != 0} {
set t $arg
set arg [expr {$gcd % $arg}]
set gcd $t
if {$gcd == 1} {return true}
}
}
return false
}
proc main {} {
puts "#1. First 15 members of the Stern-Brocot sequence:"
puts \t[generator to list [generator take 16 [sb gen]]]
puts "#2. First occurrences of 1 through 10:"
set first {}
set got 0
set i 0
generator foreach x [sb gen] {
incr i
if {$x>10} continue
if {[dict exists $first $x]} continue
dict set first $x $i
if {[incr got] >= 10} break
}
foreach {a b} [lsort -integer -stride 2 $first] {
puts "\tFirst $a at $b"
}
puts "#3. First occurrence of 100:"
set i 0
generator foreach x [sb gen] {
incr i
if {$x eq 100} break
}
puts "\tFirst $x at $i"
puts "#4. Check first 1k elements for common divisors:"
set prev [expr {2*3*5*7*11*13*17*19+1}] ;# a handy prime
set i 0
generator foreach x [sb gen] {
if {[incr i] >= 1000} break
if {![coprime $x $prev]} {
error "Element $i, $x is not coprime with $prev!"
}
set prev $x
}
puts "\tFirst $i elements are all pairwise coprime"
}
main
|
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
'🌑', '🌒', '🌓', '🌔', '🌕', '🌖', '🌗', '🌘'
| #ScratchScript | ScratchScript | print "|"
delay 0.25
clear
print "/"
delay 0.25
clear
print "-"
delay 0.25
clear
print "\"
delay 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
'🌑', '🌒', '🌓', '🌔', '🌕', '🌖', '🌗', '🌘'
| #SimpleCode | SimpleCode | dtxt
|
wait
0.25
ctxt
reset
dtxt
/
wait
0.25
ctxt
reset
dtxt
-
wait
0.25
ctxt
reset
dtxt
\
wait
0.25 |
http://rosettacode.org/wiki/Stack | Stack |
Data Structure
This illustrates a data structure, a means of storing data within a program.
You may see other such structures in the Data Structures category.
A stack is a container of elements with last in, first out access policy. Sometimes it also called LIFO.
The stack is accessed through its top.
The basic stack operations are:
push stores a new element onto the stack top;
pop returns the last pushed stack element, while removing it from the stack;
empty tests if the stack contains no elements.
Sometimes the last pushed stack element is made accessible for immutable access (for read) or mutable access (for write):
top (sometimes called peek to keep with the p theme) returns the topmost element without modifying the stack.
Stacks allow a very simple hardware implementation.
They are common in almost all processors.
In programming, stacks are also very popular for their way (LIFO) of resource management, usually memory.
Nested scopes of language objects are naturally implemented by a stack (sometimes by multiple stacks).
This is a classical way to implement local variables of a re-entrant or recursive subprogram. Stacks are also used to describe a formal computational framework.
See stack machine.
Many algorithms in pattern matching, compiler construction (e.g. recursive descent parsers), and machine learning (e.g. based on tree traversal) have a natural representation in terms of stacks.
Task
Create a stack supporting the basic operations: push, pop, empty.
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
| #DWScript | DWScript |
var stack: array of Integer;
stack.Push(1);
stack.Push(2);
stack.Push(3);
PrintLn(stack.Pop); // 3
PrintLn(stack.Pop); // 2
PrintLn(stack.Pop); // 1
Assert(stack.Length = 0); // assert empty
|
http://rosettacode.org/wiki/Spiral_matrix | Spiral matrix | Task
Produce a spiral array.
A spiral array is a square arrangement of the first N2 natural numbers, where the
numbers increase sequentially as you go around the edges of the array spiraling inwards.
For example, given 5, produce this array:
0 1 2 3 4
15 16 17 18 5
14 23 24 19 6
13 22 21 20 7
12 11 10 9 8
Related tasks
Zig-zag matrix
Identity_matrix
Ulam_spiral_(for_primes)
| #Arturo | Arturo | spiralMatrix: function [n][
m: new array.of: @[n,n] null
[dx, dy, x, y]: [1, 0, 0, 0]
loop 0..dec n^2 'i [
m\[y]\[x]: i
[nx,ny]: @[x+dx, y+dy]
if? and? [and? [in? nx 0..n-1][in? ny 0..n-1]][
null? m\[ny]\[nx]
][
[x,y]: @[nx, ny]
]
else [
bdx: dx
[dx, dy]: @[neg dy, bdx]
[x, y]: @[x+dx, y+dy]
]
]
return m
]
loop spiralMatrix 5 'row [
print map row 'x -> pad to :string x 4
] |
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.
| #Erlang | Erlang |
-module( special_variables ).
-export( [task/0] ).
task() -> ok.
|
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.
| #Forth | Forth | Name Type Description
---------------------------------------------
TIB integer Terminal Input Buffer address
U0 integer current user area address
>IN integer holds offset into TIB, used for parsing
BASE integer holds number conversion radix
STATE integer holds compiler state (true=compiling, false=interpreting)
DP integer holds dictionary memory pointer
'SOURCE integer[2] contains length and address of input source
LATEST integer address of last word added to dictionary
HP integer HOLD pointer, used for number formatting routines
LP integer leave-stack pointer, used by do loops
S0 integer end of parameter stack
PAD chars[80] Generic buffer. (size is implementation dependent)
L0 integer bottom of leave stack
R0 integer end of return stack |
http://rosettacode.org/wiki/Special_characters | Special characters | Special characters are symbols (single characters or sequences of characters) that have a "special" built-in meaning in the language and typically cannot be used in identifiers.
Escape sequences are methods that the language uses to remove the special meaning from the symbol, enabling it to be used as a normal character, or sequence of characters when this can be done.
Task
List the special characters and show escape sequences in the language.
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
| #360_Assembly | 360 Assembly | with Ada.Text_IO; use Ada.Text_IO;
procedure Test is
begin
Put ("Quote """ & ''' & """" & Character'Val (10));
end Test; |
http://rosettacode.org/wiki/Special_characters | Special characters | Special characters are symbols (single characters or sequences of characters) that have a "special" built-in meaning in the language and typically cannot be used in identifiers.
Escape sequences are methods that the language uses to remove the special meaning from the symbol, enabling it to be used as a normal character, or sequence of characters when this can be done.
Task
List the special characters and show escape sequences in the language.
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
| #6502_Assembly | 6502 Assembly | with Ada.Text_IO; use Ada.Text_IO;
procedure Test is
begin
Put ("Quote """ & ''' & """" & Character'Val (10));
end Test; |
http://rosettacode.org/wiki/Sparkline_in_unicode | Sparkline in unicode | A sparkline is a graph of successive values laid out horizontally
where the height of the line is proportional to the values in succession.
Task
Use the following series of Unicode characters to create a program
that takes a series of numbers separated by one or more whitespace or comma characters
and generates a sparkline-type bar graph of the values on a single line of output.
The eight characters: '▁▂▃▄▅▆▇█'
(Unicode values U+2581 through U+2588).
Use your program to show sparklines for the following input,
here on this page:
1 2 3 4 5 6 7 8 7 6 5 4 3 2 1
1.5, 0.5 3.5, 2.5 5.5, 4.5 7.5, 6.5
(note the mix of separators in this second case)!
Notes
A space is not part of the generated sparkline.
The sparkline may be accompanied by simple statistics of the data such as its range.
A suggestion emerging in later discussion (see Discussion page) is that the bounds between bins should ideally be set to yield the following results for two particular edge cases:
"0, 1, 19, 20" -> ▁▁██
(Aiming to use just two spark levels)
"0, 999, 4000, 4999, 7000, 7999" -> ▁▁▅▅██
(Aiming to use just three spark levels)
It may be helpful to include these cases in output tests.
You may find that the unicode sparklines on this page are rendered less noisily by Google Chrome than by Firefox or Safari.
| #AppleScript | AppleScript | use AppleScript version "2.4"
use framework "Foundation"
use scripting additions
on run
unlines(map(¬
compose(compose(unlines, sparkLine), readFloats), ¬
{"0, 1, 19, 20", "0, 999, 4000, 4999, 7000, 7999", ¬
"0, 1000, 4000, 5000, 7000, 8000", ¬
"1 2 3 4 5 6 7 8 7 6 5 4 3 2 1", ¬
"1.5, 0.5 3.5, 2.5 5.5, 4.5 7.5, 6.5"}))
end run
-- sparkLine :: [Float] -> [String]
on sparkLine(xs)
set ys to sort(xs)
set mn to item 1 of ys
set mx to item -1 of ys
set n to length of xs
set mid to (n div 2)
set w to (mx - mn) / 8
script bound
on |λ|(x)
mn + (w * x)
end |λ|
end script
set lbounds to map(bound, enumFromTo(1, 7))
script spark
on |λ|(x)
script flipGT
on |λ|(b)
b > x
end |λ|
end script
script indexedBlock
on |λ|(i)
item i of "▁▂▃▄▅▆▇"
end |λ|
end script
maybe("█", indexedBlock, findIndex(flipGT, lbounds))
end |λ|
end script
script str
on |λ|(x)
x as string
end |λ|
end script
{concat(map(spark, xs)), ¬
unwords(map(str, xs)), ¬
"Min " & mn as string, ¬
"Mean " & roundTo(mean(xs), 2) as string, ¬
"Median " & bool(item mid of xs, ((item mid of xs) + ¬
(item (mid + 1) of xs)) / 2, even(n)), ¬
"Max " & mx as string, ""}
end sparkLine
-- GENERIC -------------------------------------------------
-- Just :: a -> Maybe a
on Just(x)
{type:"Maybe", Nothing:false, Just:x}
end Just
-- Nothing :: Maybe a
on Nothing()
{type:"Maybe", Nothing:true}
end Nothing
-- bool :: a -> a -> Bool -> a
on bool(f, t, p)
if p then
t
else
f
end if
end bool
-- compose (<<<) :: (b -> c) -> (a -> b) -> a -> c
on compose(f, g)
script
property mf : mReturn(f)
property mg : mReturn(g)
on |λ|(x)
mf's |λ|(mg's |λ|(x))
end |λ|
end script
end compose
-- concat :: [[a]] -> [a]
-- concat :: [String] -> String
on concat(xs)
set lng to length of xs
if 0 < lng and string is class of (item 1 of xs) then
set acc to ""
else
set acc to {}
end if
repeat with i from 1 to lng
set acc to acc & item i of xs
end repeat
acc
end concat
-- enumFromTo :: Int -> Int -> [Int]
on enumFromTo(m, n)
if m ≤ n then
set lst to {}
repeat with i from m to n
set end of lst to i
end repeat
return lst
else
return {}
end if
end enumFromTo
-- even :: Int -> Bool
on even(x)
0 = x mod 2
end even
-- Takes a predicate function and a list and
-- returns Just( the 1-based index of the first
-- element ) in the list satisfying the predicate
-- or Nothing if there is no such element.
-- findIndex(isSpace, "hello world")
--> {type:"Maybe", Nothing:false, Just:6}
-- findIndex(even, [3, 5, 7, 8, 9])
--> {type:"Maybe", Nothing:false, Just:4}
-- findIndex(isUpper, "all lower case")
--> {type:"Maybe", Nothing:true}
-- findIndex :: (a -> Bool) -> [a] -> Maybe Int
on findIndex(p, xs)
tell mReturn(p)
set lng to length of xs
repeat with i from 1 to lng
if |λ|(item i of xs) then return Just(i)
end repeat
return Nothing()
end tell
end findIndex
-- foldl :: (a -> b -> a) -> a -> [b] -> a
on foldl(f, startValue, xs)
tell mReturn(f)
set v to startValue
set lng to length of xs
repeat with i from 1 to lng
set v to |λ|(v, item i of xs, i, xs)
end repeat
return v
end tell
end foldl
-- map :: (a -> b) -> [a] -> [b]
on map(f, xs)
tell mReturn(f)
set lng to length of xs
set lst to {}
repeat with i from 1 to lng
set end of lst to |λ|(item i of xs, i, xs)
end repeat
return lst
end tell
end map
-- mean :: [Num] -> Num
on mean(xs)
script
on |λ|(a, x)
a + x
end |λ|
end script
foldl(result, 0, xs) / (length of xs)
end mean
-- | The 'maybe' function takes a default value, a function, and a 'Maybe'
-- value. If the 'Maybe' value is 'Nothing', the function returns the
-- default value. Otherwise, it applies the function to the value inside
-- the 'Just' and returns the result.
-- maybe :: b -> (a -> b) -> Maybe a -> b
on maybe(v, f, mb)
if Nothing of mb then
v
else
tell mReturn(f) to |λ|(Just of mb)
end if
end maybe
-- Lift 2nd class handler function into 1s class script wrapper
-- mReturn :: First-class m => (a -> b) -> m (a -> b)
on mReturn(f)
if script is class of f then
f
else
script
property |λ| : f
end script
end if
end mReturn
-- readFloats :: String -> [Float]
on readFloats(s)
script asReal
on |λ|(n)
n as real
end |λ|
end script
map(asReal, splitRegex("[\\s,]+", s))
end readFloats
-- regexMatches :: String -> String -> [[String]]
on regexMatches(strRegex, strHay)
set ca to current application
-- NSNotFound handling and and High Sierra workaround due to @sl1974
set NSNotFound to a reference to 9.22337203685477E+18 + 5807
set oRgx to ca's NSRegularExpression's regularExpressionWithPattern:strRegex ¬
options:((ca's NSRegularExpressionAnchorsMatchLines as integer)) ¬
|error|:(missing value)
set oString to ca's NSString's stringWithString:strHay
script matchString
on |λ|(m)
script rangeMatched
on |λ|(i)
tell (m's rangeAtIndex:i)
set intFrom to its location
if NSNotFound ≠ intFrom then
text (intFrom + 1) thru (intFrom + (its |length|)) of strHay
else
missing value
end if
end tell
end |λ|
end script
end |λ|
end script
script asRange
on |λ|(x)
range() of x
end |λ|
end script
map(asRange, (oRgx's matchesInString:oString ¬
options:0 range:{location:0, |length|:oString's |length|()}) as list)
end regexMatches
-- roundTo :: Float -> Int -> Float
on roundTo(x, n)
set d to 10 ^ n
(round (x * d)) / d
end roundTo
-- sort :: Ord a => [a] -> [a]
on sort(xs)
((current application's NSArray's arrayWithArray:xs)'s ¬
sortedArrayUsingSelector:"compare:") as list
end sort
-- splitRegex :: Regex -> String -> [String]
on splitRegex(strRegex, str)
set lstMatches to regexMatches(strRegex, str)
if length of lstMatches > 0 then
script preceding
on |λ|(a, x)
set iFrom to start of a
set iLocn to (location of x)
if iLocn > iFrom then
set strPart to text (iFrom + 1) thru iLocn of str
else
set strPart to ""
end if
{parts:parts of a & strPart, start:iLocn + (length of x) - 1}
end |λ|
end script
set recLast to foldl(preceding, {parts:[], start:0}, lstMatches)
set iFinal to start of recLast
if iFinal < length of str then
parts of recLast & text (iFinal + 1) thru -1 of str
else
parts of recLast & ""
end if
else
{str}
end if
end splitRegex
-- unlines :: [String] -> String
on unlines(xs)
set {dlm, my text item delimiters} to ¬
{my text item delimiters, linefeed}
set str to xs as text
set my text item delimiters to dlm
str
end unlines
-- unwords :: [String] -> String
on unwords(xs)
set {dlm, my text item delimiters} to ¬
{my text item delimiters, space}
set s to xs as text
set my text item delimiters to dlm
return s
end unwords |
http://rosettacode.org/wiki/Sorting_algorithms/Strand_sort | Sorting algorithms/Strand sort |
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
O(n2) sorts
Bubble sort |
Cocktail sort |
Cocktail sort with shifting bounds |
Comb sort |
Cycle sort |
Gnome sort |
Insertion sort |
Selection sort |
Strand sort
other sorts
Bead sort |
Bogo sort |
Common sorted list |
Composite structures sort |
Custom comparator sort |
Counting sort |
Disjoint sublist sort |
External sort |
Jort sort |
Lexicographical sort |
Natural sorting |
Order by pair comparisons |
Order disjoint list items |
Order two numerical lists |
Object identifier (OID) sort |
Pancake sort |
Quickselect |
Permutation sort |
Radix sort |
Ranking methods |
Remove duplicate elements |
Sleep sort |
Stooge sort |
[Sort letters of a string] |
Three variable sort |
Topological sort |
Tree sort
This page uses content from Wikipedia. The original article was at Strand sort. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Task
Implement the Strand sort.
This is a way of sorting numbers by extracting shorter sequences of already sorted numbers from an unsorted list.
| #AutoHotkey | AutoHotkey | string =
(
-2 0 -2 5 5 3 -1 -3 5 5 0 2 -4 4 2
)
string2 := string
Loop
{
loop, parse, string, %A_space%
{
list := 1 = A_index ? A_loopfield : list
StringSplit, k, list, %A_space%
if ( k%k0% <= A_loopfield ) && ( l != "" ) && ( A_index != 1 )
list := list . " " . A_loopfield
if ( k%k0% > A_loopfield )
list := A_loopfield . " " . list , index++
l := A_loopfield
}
if ( index = 0 )
{
MsgBox % "unsorted:" string2 "`n Sorted:" list
exitapp
}
string := list, list = "", index := 0
}
esc::ExitApp |
http://rosettacode.org/wiki/Stable_marriage_problem | Stable marriage problem | Solve the Stable marriage problem using the Gale/Shapley algorithm.
Problem description
Given an equal number of men and women to be paired for marriage, each man ranks all the women in order of his preference and each woman ranks all the men in order of her preference.
A stable set of engagements for marriage is one where no man prefers a woman over the one he is engaged to, where that other woman also prefers that man over the one she is engaged to. I.e. with consulting marriages, there would be no reason for the engagements between the people to change.
Gale and Shapley proved that there is a stable set of engagements for any set of preferences and the first link above gives their algorithm for finding a set of stable engagements.
Task Specifics
Given ten males:
abe, bob, col, dan, ed, fred, gav, hal, ian, jon
And ten females:
abi, bea, cath, dee, eve, fay, gay, hope, ivy, jan
And a complete list of ranked preferences, where the most liked is to the left:
abe: abi, eve, cath, ivy, jan, dee, fay, bea, hope, gay
bob: cath, hope, abi, dee, eve, fay, bea, jan, ivy, gay
col: hope, eve, abi, dee, bea, fay, ivy, gay, cath, jan
dan: ivy, fay, dee, gay, hope, eve, jan, bea, cath, abi
ed: jan, dee, bea, cath, fay, eve, abi, ivy, hope, gay
fred: bea, abi, dee, gay, eve, ivy, cath, jan, hope, fay
gav: gay, eve, ivy, bea, cath, abi, dee, hope, jan, fay
hal: abi, eve, hope, fay, ivy, cath, jan, bea, gay, dee
ian: hope, cath, dee, gay, bea, abi, fay, ivy, jan, eve
jon: abi, fay, jan, gay, eve, bea, dee, cath, ivy, hope
abi: bob, fred, jon, gav, ian, abe, dan, ed, col, hal
bea: bob, abe, col, fred, gav, dan, ian, ed, jon, hal
cath: fred, bob, ed, gav, hal, col, ian, abe, dan, jon
dee: fred, jon, col, abe, ian, hal, gav, dan, bob, ed
eve: jon, hal, fred, dan, abe, gav, col, ed, ian, bob
fay: bob, abe, ed, ian, jon, dan, fred, gav, col, hal
gay: jon, gav, hal, fred, bob, abe, col, ed, dan, ian
hope: gav, jon, bob, abe, ian, dan, hal, ed, col, fred
ivy: ian, col, hal, gav, fred, bob, abe, ed, jon, dan
jan: ed, hal, gav, abe, bob, jon, col, ian, fred, dan
Use the Gale Shapley algorithm to find a stable set of engagements
Perturb this set of engagements to form an unstable set of engagements then check this new set for stability.
References
The Stable Marriage Problem. (Eloquent description and background information).
Gale-Shapley Algorithm Demonstration.
Another Gale-Shapley Algorithm Demonstration.
Stable Marriage Problem - Numberphile (Video).
Stable Marriage Problem (the math bit) (Video).
The Stable Marriage Problem and School Choice. (Excellent exposition)
| #ColdFusion | ColdFusion |
PERSON.CFC
component displayName="Person" accessors="true" {
property name="Name" type="string";
property name="MrOrMrsGoodEnough" type="Person";
property name="UnrealisticExpectations" type="array";
property name="PersonalHistory" type="array";
public Person function init( required String name ) {
setName( arguments.name );
setPersonalHistory([ getName() & " is on the market." ]);
this.HotnessScale = 0;
return this;
}
public Boolean function hasSettled() {
// if we have settled, return true;
return isInstanceOf( getMrOrMrsGoodEnough(), "Person" );
}
public Person function getBestOfWhatIsLeft() {
// increment the hotness scale...1 is best, 10 is...well...VERY settling.
this.HotnessScale++;
// get the match from the current rung in the barrel
var bestChoice = getUnrealisticExpectations()[ this.HotnessScale ];
return bestChoice;
}
public Boolean function wouldRatherBeWith( required Person person ) {
// only compare if we've already settled on a potential mate
if( isInstanceOf( this.getMrOrMrsGoodEnough(), "Person" ) ) {
// if the new person's hotness is greater (numerically smaller) than our current beau...
return getHotness( this, arguments.person ) < getHotness( this, this.getMrOrMrsGoodEnough() );
}
return false;
}
public Void function settle( required Person person ) {
if( person.hasSettled() ) {
// this is the match we want. Force a break up of a previous relationship (sorry!)
dumpLikeATonOfBricks( person );
}
person.setMrOrMrsGoodEnough( this );
if( hasSettled() ) {
// this is the match we want, so write a dear john to our current match
dumpLikeATonOfBricks( this );
}
logHookup( arguments.person );
// we've found the mate of our dreams!
setMrOrMrsGoodEnough( arguments.person );
}
public Void function swing( required Person person ) {
// get our spouses
var mySpouse = getMrOrMrsGoodEnough();
var notMySpouse = arguments.person.getMrOrMrsGoodEnough();
// swap em'
setMrOrMrsGoodEnough( notMySpouse );
person.setMrOrMrsGoodEnough( mySpouse );
}
public Void function dumpLikeATonOfBricks( required Person person ) {
logBreakup( arguments.person );
person.getMrOrMrsGoodEnough().setMrOrMrsGoodEnough( JavaCast( "null", "" ) );
}
public String function psychoAnalyze() {
logNuptuals();
logRegrets();
var personalJourney = "";
for( var entry in getPersonalHistory() ) {
personalJourney = personalJourney & entry & "<br />";
}
return personalJourney;
}
private Numeric function getHotness( required Person pursuer, required Person pursued ) {
var pursuersExpectations = pursuer.getUnrealisticExpectations();
var hotnessFactor = 1;
for( var hotnessFactor=1; hotnessFactor<=arrayLen( pursuersExpectations ); hotnessFactor++ ) {
if( pursuersExpectations[ hotnessFactor ].getName()==arguments.pursued.getName() ) {
return hotnessFactor;
}
}
}
private Void function logRegrets() {
var spouse = getMrOrMrsGoodEnough();
var spouseHotness = getHotness( this, spouse );
var myHotness = getHotness( spouse, this );
if( spouseHotness == 1 && myHotness == 1 ) {
arrayAppend( getPersonalHistory(), "Yes, yes, the beautiful people always find happy endings: #getName()# (her ###myHotness#), #spouse.getName()# (his ###spouseHotness#)");
}
else if( spouseHotness == myHotness ) {
arrayAppend( getPersonalHistory(), "#getName()# (her ###myHotness#) was made for #spouse.getName()# (his ###spouseHotness#). How precious.");
}
else if( spouseHotness > myHotness ) {
arrayAppend( getPersonalHistory(), "#getName()# (her ###myHotness#) could have done better than #spouse.getName()# (his ###spouseHotness#). Poor slob.");
}
else {
arrayAppend( getPersonalHistory(), "#getName()# (her ###myHotness#) is a lucky bastard to have landed #spouse.getName()# (his ###spouseHotness#).");
}
}
private Void function logNuptuals() {
arrayAppend( getPersonalHistory(), "#getName()# has settled for #getMrOrMrsGoodEnough().getName()#." );
}
private Void function logHookup( required Person person ) {
var winnerHotness = getHotness( this, arguments.person );
var myHotness = getHotness( arguments.person, this );
arrayAppend( getPersonalHistory(), "#getName()# (her ###myHotness#) is checking out #arguments.person.getName()# (his ###winnerHotness#), but wants to keep his options open.");
}
private Void function logBreakup( required Person person ) {
var scrub = person.getMrOrMrsGoodEnough();
var scrubHotness = getHotness( person, scrub );
var myHotness = getHotness( person, this );
arrayAppend( getPersonalHistory(), "#getName()# is so hot (her ###myHotness#) that #person.getName()# is dumping #scrub.getName()# (her ###scrubHotness#)");
}
}
|
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
| #REXX | REXX | /*REXX programs spells out ordinal numbers (in English, using the American system). */
numeric digits 3000 /*just in case the user uses gihugic #s*/
parse arg n /*obtain optional arguments from the CL*/
if n='' | n="," then n= 1 2 3 4 5 11 65 100 101 272 23456 8007006005004003
pgmOpts= 'ordinal quiet' /*define options needed for $SPELL#.REX*/
do j=1 for words(n) /*process each of the specified numbers*/
x=word(n, j) /*obtain a number from the input list. */
os=$spell#(x pgmOpts) /*invoke REXX routine to spell ordinal#*/
say right(x, max(20, length(x) ) ) ' spelled ordinal number ───► ' os
end /*j*/ |
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.
| #PILOT | PILOT | C :sqr=1
C :cbr=1
C :sq=1
C :cb=1
C :n=0
*square
U (sq>cb):*cube
C (sq<cb):n=n+1
T (sq<cb):#sq
C :sqr=sqr+1
C :sq=sqr*#sqr
J (n<30):*square
E :
*cube
C :cbr=cbr+1
C :cb=(cbr*#cbr)*#cbr
J (sq>cb):*cube
E : |
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.
| #PL.2FI | PL/I | squareNotCube: procedure options(main);
square: procedure(n) returns(fixed);
declare n fixed;
return(n * n);
end square;
cube: procedure(n) returns(fixed);
declare n fixed;
return(n * n * n);
end cube;
declare (ci, si, seen) fixed;
ci = 1;
do si = 1 repeat(si + 1) while(seen < 30);
do while(cube(ci) < square(si));
ci = ci + 1;
end;
if square(si) ^= cube(ci) then do;
put edit(square(si)) (F(5));
seen = seen + 1;
if mod(seen,10) = 0 then put skip;
end;
end;
end squareNotCube; |
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
| #Nim | Nim | proc splitOnDiff(str: string): string =
result = ""
if str.len < 1: return result
var prevChar: char = str[0]
for idx in 0 ..< str.len:
if str[idx] != prevChar:
result &= ", "
prevChar = str[idx]
result &= str[idx]
assert splitOnDiff("""X""") == """X"""
assert splitOnDiff("""XX""") == """XX"""
assert splitOnDiff("""XY""") == """X, Y"""
assert splitOnDiff("""gHHH5YY++///\""") == """g, HHH, 5, YY, ++, ///, \"""
echo splitOnDiff("""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
| #ooRexx | ooRexx | Parse Arg str . /*obtain optional arguments from the CL*/
If str=='' Then str= 'gHHH5YY++///\' /*Not specified? Then use the default.*/
i=1
ol=''
Do Forever
j=verify(str,substr(str,i,1),'N',i,99) /* find first character that's different */
If j=0 Then Do /* End of strin reached */
ol=ol||substr(str,i) /* the final substring */
Leave
End
ol=ol||substr(str,i,j-i)', ' /* add substring and delimiter */
i=j
End
Say ol |
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.
| #VBScript | VBScript | sb = Array(1,1)
i = 1 'considered
j = 2 'precedent
n = 0 'loop counter
Do
ReDim Preserve sb(UBound(sb) + 1)
sb(UBound(sb)) = sb(UBound(sb) - i) + sb(UBound(sb) - j)
ReDim Preserve sb(UBound(sb) + 1)
sb(UBound(sb)) = sb(UBound(sb) - j)
i = i + 1
j = j + 1
n = n + 1
Loop Until n = 2000
WScript.Echo "First 15: " & DisplayElements(15)
For k = 1 To 10
WScript.Echo "The first instance of " & k & " is in #" & ShowFirstInstance(k) & "."
Next
WScript.Echo "The first instance of " & 100 & " is in #" & ShowFirstInstance(100) & "."
Function DisplayElements(n)
For i = 0 To n - 1
If i < n - 1 Then
DisplayElements = DisplayElements & sb(i) & ", "
Else
DisplayElements = DisplayElements & sb(i)
End If
Next
End Function
Function ShowFirstInstance(n)
For i = 0 To UBound(sb)
If sb(i) = n Then
ShowFirstInstance = i + 1
Exit For
End If
Next
End Function |
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
'🌑', '🌒', '🌓', '🌔', '🌕', '🌖', '🌗', '🌘'
| #Wee_Basic | Wee Basic | let loop=1
sub delay:
for i=1 to 10000
next
cls 1
return
while loop=1
print 1 "l"
gosub delay:
print 1 "/"
gosub delay:
print 1 "-"
gosub delay:
print 1 "\"
gosub delay:
wend
end |
http://rosettacode.org/wiki/Spinning_rod_animation/Text | Spinning rod animation/Text | Task
An animation with the following frames in the following order (if certain characters aren't available or can't be used correctly in the programming language, alternate characters can replace any of these frames) must animate with a delay of 0.25 seconds between each frame, with the previous frame being cleared before the next frame appears:
|
/
- or ─
\
A stand-alone version that loops and/or a version that doesn't loop can be made. These examples can also be converted into a system used in game development which is called on a HUD or GUI element requiring it to be called each frame to output the text, and advance the frame when the frame delay has passed. You can also use alternate text such as the . animation ( . | .. | ... | .. | repeat from . ) or the logic can be updated to include a ping/pong style where the frames advance forward, reach the end and then play backwards and when they reach the beginning they start over ( technically, you'd stop one frame prior to prevent the first frame playing twice, or write it another way ).
There are many different ways you can incorporate text animations. Here are a few text ideas - each frame is in quotes. If you can think of any, add them to this page! There are 2 examples for several of these; the first is the base animation with only unique sets of characters. The second consists of the primary set from a - n and doubled, minus the first and last element ie: We only want the center. This way an animation can play forwards, and then in reverse ( ping ponging ) without having to code that feature. For the animations with 3 elements, we only add 1, the center. with 4, it becomes 6. with 10, it becomes 18.
We don't need the second option for some of the animations if they connect smoothly, when animated, back to the first element. ... doesn't connect with . cleanly - there is a large leap. The rotating pipe meets the first perfectly so it isn't necessary, etc..
Dots - Option A requires ping / pong enabled script. Option B just adds the elements in the center.
'.', '..', '...'
'.', '..', '...', '..'
Pipe - This has the uniform sideways pipe instead of a hyphen to prevent non-uniform sizing.
'|', '/', '─', '\'
Stars - Option A requires ping / pong enabled script. Option B just adds the elements from the center.
'⁎', '⁑', '⁂'
'⁎', '⁑', '⁂', '⁑'
Clock - These need to be ordered. I haven't done this yet as the application I was testing the system in doesn't support these wingdings / icons. But this would look quite nice and you could set it up to go forward, or backward during an undo process, etc..
'🕛', '🕧', '🕐', '🕜', '🕑', '🕝', '🕒', '🕞', '🕓', '🕟', '🕔', '🕠', '🕕', '🕖', '🕗', '🕘', '🕙', '🕚', '🕡', '🕢', '🕣', '🕤', '🕥', '🕦'
Arrows:
'⬍', '⬈', '➞', '⬊', '⬍', '⬋', '⬅', '⬉'
Bird - This looks decent but may be missing something.
'︷', '︵', '︹', '︺', '︶', '︸'
'︷', '︵', '︹', '︺', '︶', '︸', '︶', '︺', '︹', '︵'
Plants - This isn't quite complete
'☘', '❀', '❁'
'☘', '❀', '❁', '❀'
Eclipse - From Raku Throbber post author
'🌑', '🌒', '🌓', '🌔', '🌕', '🌖', '🌗', '🌘'
| #Wren | Wren | import "io" for Stdout
import "timer" for Timer
var ESC = "\u001b"
var a = "|/-\\"
System.write("%(ESC)[?25l") // hide the cursor
var start = System.clock
var asleep = 0
while (true) {
for (i in 0..3) {
System.write("%(ESC)[2J") // clear terminal
System.write("%(ESC)[0;0H") // place cursor at top left corner
for (j in 0..79) { // 80 character terminal width, say
System.write(a[i])
}
Stdout.flush()
Timer.sleep(250) // suspends both current fiber & System.clock
asleep = asleep + 250
}
var now = System.clock
// stop after 20 seconds, say
if (now * 1000 + asleep - start * 1000 >= 20000) break
}
System.print("%(ESC)[?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
| #Dyalect | Dyalect | type Stack() {
var xs = []
}
func Stack.IsEmpty() => this!xs.Length() == 0
func Stack.Peek() => this!xs[this!xs.Length() - 1]
func Stack.Pop() {
var e = this!xs[this!xs.Length() - 1]
this!xs.RemoveAt(this!xs.Length() - 1)
return e
}
func Stack.Push(item) => this!xs.Add(item)
var stack = Stack()
stack.Push(1)
stack.Push(2)
print(stack.Pop())
print(stack.Peek())
stack.Pop()
print(stack.IsEmpty()) |
http://rosettacode.org/wiki/Spiral_matrix | Spiral matrix | Task
Produce a spiral array.
A spiral array is a square arrangement of the first N2 natural numbers, where the
numbers increase sequentially as you go around the edges of the array spiraling inwards.
For example, given 5, produce this array:
0 1 2 3 4
15 16 17 18 5
14 23 24 19 6
13 22 21 20 7
12 11 10 9 8
Related tasks
Zig-zag matrix
Identity_matrix
Ulam_spiral_(for_primes)
| #AutoHotkey | AutoHotkey | n := 5, dx := x := y := v := 1, dy := 0
Loop % n*n {
a_%x%_%y% := v++
nx := x+dx, ny := y+dy
If (1 > nx || nx > n || 1 > ny || ny > n || a_%nx%_%ny%)
t := dx, dx := -dy, dy := t
x := x+dx, y := y+dy
}
Loop %n% { ; generate printout
y := A_Index ; for each row
Loop %n% ; and for each column
s .= a_%A_Index%_%y% "`t" ; attach stored index
s .= "`n" ; row is complete
}
MsgBox %s% ; show output
/*
---------------------------
1 2 3 4 5
16 17 18 19 6
15 24 25 20 7
14 23 22 21 8
13 12 11 10 9
---------------------------
*/ |
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.
| #Fortran | Fortran | INQUIRE(FILE = FILENAME(1:L),EXIST = EXIST, !Here we go. Does the file exist?
1 ERR = 666,IOSTAT = IOSTAT) !Hopefully, named in good style, etc.
IF (EXIST) THEN !So, does the named file already exist?
...etc. |
http://rosettacode.org/wiki/Special_variables | Special variables | Special variables have a predefined meaning within a computer programming language.
Task
List the special variables used within the language.
| #Go | Go |
# &keyword # type returned(indicators) - brief description
# indicators:
# * - generates multiple values
# = - modifiable
# ? - may fail (e.g. status inquiry)
# U - Unicon
# G - Icon or Unicon with Graphics
#
&allocated # integer(*) - report memory allocated in total and by storage regions
&ascii # cset - ASCII character set
&clock # string - time of day
&col # integer(=G) - column location of pointer
&collections # integer(*) - garbage collection activity in total and by storage region
&column # integer(U) - source code column
&control # null(?G) - control key state
&cset # cset - universal character set
¤t # co-expression - current co-expression
&date # string - today's date
&dateline # string - time stamp
&digits # cset - digit characters
&dump # integer(=) - termination dump
&e # real - natural log e
&error # integer(=) - enable/disable error conversion/fail on error
&errno # integer(?) - variable containing error number from previous posix command
&errornumber # integer(?) - error number of last error converted to failure
&errortext # string(?) - error message of last error converted to failure
&errorvalue # any(?) - erroneous value of last error converted to failure
&errout # file - standard error file
&eventcode # integer(=U) - program execution event in monitored program
&eventsource # co-expression(=U) - source of events in monitoring program
&eventvalue # any(=U) - value from event in monitored program
&fail # none - always fails
&features # string(*) - identifying features in this version of Icon/Unicon
&file # string - current source file
&host # string - host machine name
&input # file - standard input file
&interval # integer(G) - time between input events
&lcase # cset - lowercase letters
&ldrag # integer(G) - left button drag
&letters # cset - letters
&level # integer - call depth
&line # integer - current source line number
&lpress # integer(G) - left button press
&lrelease # integer(G) - left button release
&main # co-expression - main task
&mdrag # integer(G) - middle button drag
&meta # null(?G) - meta key state
&mpress # integer(G) - middle button press
&mrelease # integer(G) - middle button release
&now # integer(U) - current time
&null # null - null value
&output # file - standard output file
&pick # string (U) - variable containing the result of 3D selection
&phi # real - golden ratio
&pos # integer(=) - string scanning position
&progname # string(=) - program name
&random # integer(=) - random number seed
&rdrag # integer(G) - right button drag
®ions # integer(*) - region sizes
&resize # integer(G) - window resize
&row # integer(=G) - row location of pointer
&rpress # integer(G) - right button press
&rrelease # integer(G) - right button release
&shift # null(?G) - shift key state
&source # co-expression - invoking co-expression
&storage # integer(*) - memory in use in each region
&subject # string - string scanning subject
&syserr # integer - halt on system error
&time # integer(=) - elapsed time in milliseconds
&trace # integer(=) - trace program
&ucase # cset - upper case letters
&version # string - version
&window # window(=G) - the current graphics rendering window
&x # integer(=G) - pointer horizontal position
&y # integer(=G) - pointer vertical position
# keywords may also fail if the corresponding feature is not present.
# Other variants of Icon (e.g. MT-Icon) will have different mixes of keywords. |
http://rosettacode.org/wiki/Special_characters | Special characters | Special characters are symbols (single characters or sequences of characters) that have a "special" built-in meaning in the language and typically cannot be used in identifiers.
Escape sequences are methods that the language uses to remove the special meaning from the symbol, enabling it to be used as a normal character, or sequence of characters when this can be done.
Task
List the special characters and show escape sequences in the language.
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
| #ActionScript | ActionScript | with Ada.Text_IO; use Ada.Text_IO;
procedure Test is
begin
Put ("Quote """ & ''' & """" & Character'Val (10));
end Test; |
http://rosettacode.org/wiki/Special_characters | Special characters | Special characters are symbols (single characters or sequences of characters) that have a "special" built-in meaning in the language and typically cannot be used in identifiers.
Escape sequences are methods that the language uses to remove the special meaning from the symbol, enabling it to be used as a normal character, or sequence of characters when this can be done.
Task
List the special characters and show escape sequences in the language.
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
| #Ada | Ada | with Ada.Text_IO; use Ada.Text_IO;
procedure Test is
begin
Put ("Quote """ & ''' & """" & Character'Val (10));
end Test; |
http://rosettacode.org/wiki/Sparkline_in_unicode | Sparkline in unicode | A sparkline is a graph of successive values laid out horizontally
where the height of the line is proportional to the values in succession.
Task
Use the following series of Unicode characters to create a program
that takes a series of numbers separated by one or more whitespace or comma characters
and generates a sparkline-type bar graph of the values on a single line of output.
The eight characters: '▁▂▃▄▅▆▇█'
(Unicode values U+2581 through U+2588).
Use your program to show sparklines for the following input,
here on this page:
1 2 3 4 5 6 7 8 7 6 5 4 3 2 1
1.5, 0.5 3.5, 2.5 5.5, 4.5 7.5, 6.5
(note the mix of separators in this second case)!
Notes
A space is not part of the generated sparkline.
The sparkline may be accompanied by simple statistics of the data such as its range.
A suggestion emerging in later discussion (see Discussion page) is that the bounds between bins should ideally be set to yield the following results for two particular edge cases:
"0, 1, 19, 20" -> ▁▁██
(Aiming to use just two spark levels)
"0, 999, 4000, 4999, 7000, 7999" -> ▁▁▅▅██
(Aiming to use just three spark levels)
It may be helpful to include these cases in output tests.
You may find that the unicode sparklines on this page are rendered less noisily by Google Chrome than by Firefox or Safari.
| #Arturo | Arturo | bar: "▁▂▃▄▅▆▇█"
barcount: to :floating dec size bar
while ø [
line: input "Numbers separated by spaces: "
numbers: to [:floating] split.words line
mn: min numbers
mx: max numbers
extent: mx-mn
sparkLine: new ""
loop numbers 'n [
i: to :integer barcount*(n-mn)//extent
'sparkLine ++ bar\[i]
]
print ["min:" round.to:1 mn "max:" round.to:1 mx]
print sparkLine
print ""
] |
http://rosettacode.org/wiki/Sparkline_in_unicode | Sparkline in unicode | A sparkline is a graph of successive values laid out horizontally
where the height of the line is proportional to the values in succession.
Task
Use the following series of Unicode characters to create a program
that takes a series of numbers separated by one or more whitespace or comma characters
and generates a sparkline-type bar graph of the values on a single line of output.
The eight characters: '▁▂▃▄▅▆▇█'
(Unicode values U+2581 through U+2588).
Use your program to show sparklines for the following input,
here on this page:
1 2 3 4 5 6 7 8 7 6 5 4 3 2 1
1.5, 0.5 3.5, 2.5 5.5, 4.5 7.5, 6.5
(note the mix of separators in this second case)!
Notes
A space is not part of the generated sparkline.
The sparkline may be accompanied by simple statistics of the data such as its range.
A suggestion emerging in later discussion (see Discussion page) is that the bounds between bins should ideally be set to yield the following results for two particular edge cases:
"0, 1, 19, 20" -> ▁▁██
(Aiming to use just two spark levels)
"0, 999, 4000, 4999, 7000, 7999" -> ▁▁▅▅██
(Aiming to use just three spark levels)
It may be helpful to include these cases in output tests.
You may find that the unicode sparklines on this page are rendered less noisily by Google Chrome than by Firefox or Safari.
| #AutoHotkey | AutoHotkey | SetFormat, FloatFast, 0.1
strings := ["1 2 3 4 5 6 7 8 7 6 5 4 3 2 1"
, "1.5, 0.5 3.5, 2.5 5.5, 4.5 7.5, 6.5"]
Loop, % strings.MaxIndex()
{
SL := Sparklines(strings[A_Index])
MsgBox, % "Min: " SL["Min"] ", Max: " SL["Max"] ", Range: " SL["Rng"] "`n" SL["Chars"]
}
Sparklines(s)
{
s := RegexReplace(s, "[^\d\.]+", ",")
Loop, Parse, s, `,
{
Max := A_LoopField > Max ? A_LoopField : Max
Min := !Min ? Max : A_LoopField < Min ? A_LoopField : Min
}
Rng := Max - Min
Loop, Parse, s, `,
Chars .= Chr(0x2581 + Round(7 * (A_LoopField - Min) / Rng))
return, {"Min": Min, "Max": Max, "Rng": Rng, "Chars": Chars}
} |
http://rosettacode.org/wiki/Sorting_algorithms/Strand_sort | Sorting algorithms/Strand sort |
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
O(n2) sorts
Bubble sort |
Cocktail sort |
Cocktail sort with shifting bounds |
Comb sort |
Cycle sort |
Gnome sort |
Insertion sort |
Selection sort |
Strand sort
other sorts
Bead sort |
Bogo sort |
Common sorted list |
Composite structures sort |
Custom comparator sort |
Counting sort |
Disjoint sublist sort |
External sort |
Jort sort |
Lexicographical sort |
Natural sorting |
Order by pair comparisons |
Order disjoint list items |
Order two numerical lists |
Object identifier (OID) sort |
Pancake sort |
Quickselect |
Permutation sort |
Radix sort |
Ranking methods |
Remove duplicate elements |
Sleep sort |
Stooge sort |
[Sort letters of a string] |
Three variable sort |
Topological sort |
Tree sort
This page uses content from Wikipedia. The original article was at Strand sort. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Task
Implement the Strand sort.
This is a way of sorting numbers by extracting shorter sequences of already sorted numbers from an unsorted list.
| #C | C | #include <stdio.h>
typedef struct node_t *node, node_t;
struct node_t { int v; node next; };
typedef struct { node head, tail; } slist;
void push(slist *l, node e) {
if (!l->head) l->head = e;
if (l->tail) l->tail->next = e;
l->tail = e;
}
node removehead(slist *l) {
node e = l->head;
if (e) {
l->head = e->next;
e->next = 0;
}
return e;
}
void join(slist *a, slist *b) {
push(a, b->head);
a->tail = b->tail;
}
void merge(slist *a, slist *b) {
slist r = {0};
while (a->head && b->head)
push(&r, removehead(a->head->v <= b->head->v ? a : b));
join(&r, a->head ? a : b);
*a = r;
b->head = b->tail = 0;
}
void sort(int *ar, int len)
{
node_t all[len];
// array to list
for (int i = 0; i < len; i++)
all[i].v = ar[i], all[i].next = i < len - 1 ? all + i + 1 : 0;
slist list = {all, all + len - 1}, rem, strand = {0}, res = {0};
for (node e = 0; list.head; list = rem) {
rem.head = rem.tail = 0;
while ((e = removehead(&list)))
push((!strand.head || e->v >= strand.tail->v) ? &strand : &rem, e);
merge(&res, &strand);
}
// list to array
for (int i = 0; res.head; i++, res.head = res.head->next)
ar[i] = res.head->v;
}
void show(const char *title, int *x, int len)
{
printf("%s ", title);
for (int i = 0; i < len; i++)
printf("%3d ", x[i]);
putchar('\n');
}
int main(void)
{
int x[] = {-2,0,-2,5,5,3,-1,-3,5,5,0,2,-4,4,2};
# define SIZE sizeof(x)/sizeof(int)
show("before sort:", x, SIZE);
sort(x, sizeof(x)/sizeof(int));
show("after sort: ", x, SIZE);
return 0;
} |
http://rosettacode.org/wiki/Stable_marriage_problem | Stable marriage problem | Solve the Stable marriage problem using the Gale/Shapley algorithm.
Problem description
Given an equal number of men and women to be paired for marriage, each man ranks all the women in order of his preference and each woman ranks all the men in order of her preference.
A stable set of engagements for marriage is one where no man prefers a woman over the one he is engaged to, where that other woman also prefers that man over the one she is engaged to. I.e. with consulting marriages, there would be no reason for the engagements between the people to change.
Gale and Shapley proved that there is a stable set of engagements for any set of preferences and the first link above gives their algorithm for finding a set of stable engagements.
Task Specifics
Given ten males:
abe, bob, col, dan, ed, fred, gav, hal, ian, jon
And ten females:
abi, bea, cath, dee, eve, fay, gay, hope, ivy, jan
And a complete list of ranked preferences, where the most liked is to the left:
abe: abi, eve, cath, ivy, jan, dee, fay, bea, hope, gay
bob: cath, hope, abi, dee, eve, fay, bea, jan, ivy, gay
col: hope, eve, abi, dee, bea, fay, ivy, gay, cath, jan
dan: ivy, fay, dee, gay, hope, eve, jan, bea, cath, abi
ed: jan, dee, bea, cath, fay, eve, abi, ivy, hope, gay
fred: bea, abi, dee, gay, eve, ivy, cath, jan, hope, fay
gav: gay, eve, ivy, bea, cath, abi, dee, hope, jan, fay
hal: abi, eve, hope, fay, ivy, cath, jan, bea, gay, dee
ian: hope, cath, dee, gay, bea, abi, fay, ivy, jan, eve
jon: abi, fay, jan, gay, eve, bea, dee, cath, ivy, hope
abi: bob, fred, jon, gav, ian, abe, dan, ed, col, hal
bea: bob, abe, col, fred, gav, dan, ian, ed, jon, hal
cath: fred, bob, ed, gav, hal, col, ian, abe, dan, jon
dee: fred, jon, col, abe, ian, hal, gav, dan, bob, ed
eve: jon, hal, fred, dan, abe, gav, col, ed, ian, bob
fay: bob, abe, ed, ian, jon, dan, fred, gav, col, hal
gay: jon, gav, hal, fred, bob, abe, col, ed, dan, ian
hope: gav, jon, bob, abe, ian, dan, hal, ed, col, fred
ivy: ian, col, hal, gav, fred, bob, abe, ed, jon, dan
jan: ed, hal, gav, abe, bob, jon, col, ian, fred, dan
Use the Gale Shapley algorithm to find a stable set of engagements
Perturb this set of engagements to form an unstable set of engagements then check this new set for stability.
References
The Stable Marriage Problem. (Eloquent description and background information).
Gale-Shapley Algorithm Demonstration.
Another Gale-Shapley Algorithm Demonstration.
Stable Marriage Problem - Numberphile (Video).
Stable Marriage Problem (the math bit) (Video).
The Stable Marriage Problem and School Choice. (Excellent exposition)
| #D | D | import std.stdio, std.array, std.algorithm, std.string;
string[string] matchmaker(string[][string] guyPrefers,
string[][string] girlPrefers) /*@safe*/ {
string[string] engagedTo;
string[] freeGuys = guyPrefers.keys;
while (freeGuys.length) {
const string thisGuy = freeGuys[0];
freeGuys.popFront();
const auto thisGuyPrefers = guyPrefers[thisGuy];
foreach (girl; thisGuyPrefers) {
if (girl !in engagedTo) { // girl is free
engagedTo[girl] = thisGuy;
break;
} else {
string otherGuy = engagedTo[girl];
string[] thisGirlPrefers = girlPrefers[girl];
if (thisGirlPrefers.countUntil(thisGuy) <
thisGirlPrefers.countUntil(otherGuy)) {
// this girl prefers this guy to
// the guy she's engagedTo to.
engagedTo[girl] = thisGuy;
freeGuys ~= otherGuy;
break;
}
// else no change, keep looking for this guy
}
}
}
return engagedTo;
}
bool check(bool doPrint=false)(string[string] engagedTo,
string[][string] guyPrefers,
string[][string] galPrefers) @safe {
enum MSG = "%s likes %s better than %s and %s " ~
"likes %s better than their current partner";
string[string] inverseEngaged;
foreach (k, v; engagedTo)
inverseEngaged[v] = k;
foreach (she, he; engagedTo) {
auto sheLikes = galPrefers[she];
auto sheLikesBetter = sheLikes[0 .. sheLikes.countUntil(he)];
auto heLikes = guyPrefers[he];
auto heLikesBetter = heLikes[0 .. heLikes.countUntil(she)];
foreach (guy; sheLikesBetter) {
auto guysGirl = inverseEngaged[guy];
auto guyLikes = guyPrefers[guy];
if (guyLikes.countUntil(guysGirl) >
guyLikes.countUntil(she)) {
static if (doPrint)
writefln(MSG, she, guy, he, guy, she);
return false;
}
}
foreach (gal; heLikesBetter) {
auto girlsGuy = engagedTo[gal];
auto galLikes = galPrefers[gal];
if (galLikes.countUntil(girlsGuy) >
galLikes.countUntil(he)) {
static if (doPrint)
writefln(MSG, he, gal, she, gal, he);
return false;
}
}
}
return true;
}
void main() /*@safe*/ {
auto guyData = "abe abi eve cath ivy jan dee fay bea hope gay
bob cath hope abi dee eve fay bea jan ivy gay
col hope eve abi dee bea fay ivy gay cath jan
dan ivy fay dee gay hope eve jan bea cath abi
ed jan dee bea cath fay eve abi ivy hope gay
fred bea abi dee gay eve ivy cath jan hope fay
gav gay eve ivy bea cath abi dee hope jan fay
hal abi eve hope fay ivy cath jan bea gay dee
ian hope cath dee gay bea abi fay ivy jan eve
jon abi fay jan gay eve bea dee cath ivy hope";
auto galData = "abi bob fred jon gav ian abe dan ed col hal
bea bob abe col fred gav dan ian ed jon hal
cath fred bob ed gav hal col ian abe dan jon
dee fred jon col abe ian hal gav dan bob ed
eve jon hal fred dan abe gav col ed ian bob
fay bob abe ed ian jon dan fred gav col hal
gay jon gav hal fred bob abe col ed dan ian
hope gav jon bob abe ian dan hal ed col fred
ivy ian col hal gav fred bob abe ed jon dan
jan ed hal gav abe bob jon col ian fred dan";
string[][string] guyPrefers, galPrefers;
foreach (line; guyData.splitLines())
guyPrefers[split(line)[0]] = split(line)[1..$];
foreach (line; galData.splitLines())
galPrefers[split(line)[0]] = split(line)[1..$];
writeln("Engagements:");
auto engagedTo = matchmaker(guyPrefers, galPrefers);
writeln("\nCouples:");
string[] parts;
foreach (k; engagedTo.keys.sort())
writefln("%s is engagedTo to %s", k, engagedTo[k]);
writeln();
bool c = check!(true)(engagedTo, guyPrefers, galPrefers);
writeln("Marriages are ", c ? "stable" : "unstable");
writeln("\n\nSwapping two fiances to introduce an error");
auto gals = galPrefers.keys.sort();
swap(engagedTo[gals[0]], engagedTo[gals[1]]);
foreach (gal; gals[0 .. 2])
writefln(" %s is now engagedTo to %s", gal, engagedTo[gal]);
writeln();
c = check!(true)(engagedTo, guyPrefers, galPrefers);
writeln("Marriages are ", c ? "stable" : "unstable");
} |
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
| #Rust | Rust | struct NumberNames {
cardinal: &'static str,
ordinal: &'static str,
}
impl NumberNames {
fn get_name(&self, ordinal: bool) -> &'static str {
if ordinal {
return self.ordinal;
}
self.cardinal
}
}
const SMALL_NAMES: [NumberNames; 20] = [
NumberNames {
cardinal: "zero",
ordinal: "zeroth",
},
NumberNames {
cardinal: "one",
ordinal: "first",
},
NumberNames {
cardinal: "two",
ordinal: "second",
},
NumberNames {
cardinal: "three",
ordinal: "third",
},
NumberNames {
cardinal: "four",
ordinal: "fourth",
},
NumberNames {
cardinal: "five",
ordinal: "fifth",
},
NumberNames {
cardinal: "six",
ordinal: "sixth",
},
NumberNames {
cardinal: "seven",
ordinal: "seventh",
},
NumberNames {
cardinal: "eight",
ordinal: "eighth",
},
NumberNames {
cardinal: "nine",
ordinal: "ninth",
},
NumberNames {
cardinal: "ten",
ordinal: "tenth",
},
NumberNames {
cardinal: "eleven",
ordinal: "eleventh",
},
NumberNames {
cardinal: "twelve",
ordinal: "twelfth",
},
NumberNames {
cardinal: "thirteen",
ordinal: "thirteenth",
},
NumberNames {
cardinal: "fourteen",
ordinal: "fourteenth",
},
NumberNames {
cardinal: "fifteen",
ordinal: "fifteenth",
},
NumberNames {
cardinal: "sixteen",
ordinal: "sixteenth",
},
NumberNames {
cardinal: "seventeen",
ordinal: "seventeenth",
},
NumberNames {
cardinal: "eighteen",
ordinal: "eighteenth",
},
NumberNames {
cardinal: "nineteen",
ordinal: "nineteenth",
},
];
const TENS: [NumberNames; 8] = [
NumberNames {
cardinal: "twenty",
ordinal: "twentieth",
},
NumberNames {
cardinal: "thirty",
ordinal: "thirtieth",
},
NumberNames {
cardinal: "forty",
ordinal: "fortieth",
},
NumberNames {
cardinal: "fifty",
ordinal: "fiftieth",
},
NumberNames {
cardinal: "sixty",
ordinal: "sixtieth",
},
NumberNames {
cardinal: "seventy",
ordinal: "seventieth",
},
NumberNames {
cardinal: "eighty",
ordinal: "eightieth",
},
NumberNames {
cardinal: "ninety",
ordinal: "ninetieth",
},
];
struct NamedNumber {
cardinal: &'static str,
ordinal: &'static str,
number: usize,
}
impl NamedNumber {
fn get_name(&self, ordinal: bool) -> &'static str {
if ordinal {
return self.ordinal;
}
self.cardinal
}
}
const N: usize = 7;
const NAMED_NUMBERS: [NamedNumber; N] = [
NamedNumber {
cardinal: "hundred",
ordinal: "hundredth",
number: 100,
},
NamedNumber {
cardinal: "thousand",
ordinal: "thousandth",
number: 1000,
},
NamedNumber {
cardinal: "million",
ordinal: "millionth",
number: 1000000,
},
NamedNumber {
cardinal: "billion",
ordinal: "billionth",
number: 1000000000,
},
NamedNumber {
cardinal: "trillion",
ordinal: "trillionth",
number: 1000000000000,
},
NamedNumber {
cardinal: "quadrillion",
ordinal: "quadrillionth",
number: 1000000000000000,
},
NamedNumber {
cardinal: "quintillion",
ordinal: "quintillionth",
number: 1000000000000000000,
},
];
fn big_name(n: usize) -> &'static NamedNumber {
for i in 1..N {
if n < NAMED_NUMBERS[i].number {
return &NAMED_NUMBERS[i - 1];
}
}
&NAMED_NUMBERS[N - 1]
}
fn number_name(n: usize, ordinal: bool) -> String {
if n < 20 {
return String::from(SMALL_NAMES[n].get_name(ordinal));
} else if n < 100 {
if n % 10 == 0 {
return String::from(TENS[n / 10 - 2].get_name(ordinal));
}
let s1 = TENS[n / 10 - 2].get_name(false);
let s2 = SMALL_NAMES[n % 10].get_name(ordinal);
return format!("{}-{}", s1, s2);
}
let big = big_name(n);
let mut result = number_name(n / big.number, false);
result.push(' ');
if n % big.number == 0 {
result.push_str(big.get_name(ordinal));
} else {
result.push_str(big.get_name(false));
result.push(' ');
result.push_str(&number_name(n % big.number, ordinal));
}
result
}
fn test_ordinal(n: usize) {
println!("{}: {}", n, number_name(n, true));
}
fn 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(8007006005004003);
} |
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
| #Sidef | Sidef | var lingua_en = frequire('Lingua::EN::Numbers')
var tests = [1,2,3,4,5,11,65,100,101,272,23456,8007006005004003]
tests.each {|n|
printf("%16s : %s\n", n, lingua_en.num2en_ordinal(n))
} |
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.
| #PL.2FM | PL/M | 100H: /* CP/M OUTPUT */
BDOS: PROCEDURE (FN, ARG);
DECLARE FN BYTE, ARG ADDRESS;
GO TO 5;
END BDOS;
PRINT$NUMBER: PROCEDURE (N);
DECLARE S (7) BYTE INITIAL ('..... $');
DECLARE (N, P) ADDRESS, C BASED P BYTE;
P = .S(5);
DIGIT:
P = P-1;
C = N MOD 10 + '0';
N = N/10;
IF N > 0 THEN GO TO DIGIT;
CALL BDOS(9, P);
END PRINT$NUMBER;
/* SQUARES */
SQUARE: PROCEDURE (N) ADDRESS;
DECLARE N ADDRESS;
RETURN N * N;
END SQUARE;
/* CUBES */
CUBE: PROCEDURE (N) ADDRESS;
DECLARE N ADDRESS;
RETURN N * N * N;
END CUBE;
DECLARE (CI, SI) ADDRESS INITIAL (1, 1), SEEN BYTE INITIAL (0);
DO WHILE SEEN < 30;
DO WHILE CUBE(CI) < SQUARE(SI);
CI = CI + 1;
END;
IF SQUARE(SI) <> CUBE(CI) THEN DO;
CALL PRINT$NUMBER(SQUARE(SI));
SEEN = SEEN + 1;
END;
SI = SI + 1;
END;
CALL BDOS(0,0);
EOF |
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.
| #PureBasic | PureBasic | OpenConsole()
lv=1
Repeat
s+1 : s2=s*s : Flg=#True
For i=lv To s
If s2=i*i*i
tx3$+Space(Len(tx2$)-Len(tx3$))+Str(s2)
tx2$+Space(Len(Str(s2))+1)
Flg=#False : lv=i : c-1 : Break
EndIf
Next
If Flg : tx2$+Str(s2)+" " : EndIf
c+1
Until c>=30
PrintN("s² : "+tx2$) : PrintN("s²&s³: "+tx3$)
Input() |
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
| #Pascal | Pascal | program SplitChars;
{$IFDEF FPC}
{$MODE DELPHI}{$COPERATORS ON}
{$ENDIF}
const
TestString = 'gHHH5YY++///\';
function SplitAtChars(const S: String):String;
var
i : integer;
lastChar:Char;
begin
result := '';
IF length(s) > 0 then
begin
LastChar := s[1];
result := LastChar;
For i := 2 to length(s) do
begin
if s[i] <> lastChar then
begin
lastChar := s[i];
result += ', ';
end;
result += LastChar;
end;
end;
end;
BEGIN
writeln(SplitAtChars(TestString));
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.
| #Visual_Basic_.NET | Visual Basic .NET | Imports System
Imports System.Collections.Generic
Imports System.Linq
Module Module1
Dim l As List(Of Integer) = {1, 1}.ToList()
Function gcd(ByVal a As Integer, ByVal b As Integer) As Integer
Return If(a > 0, If(a < b, gcd(b Mod a, a), gcd(a Mod b, b)), b)
End Function
Sub Main(ByVal args As String())
Dim max As Integer = 1000, take As Integer = 15, i As Integer = 1,
selection As Integer() = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 100}
Do : l.AddRange({l(i) + l(i - 1), l(i)}.ToList) : i += 1
Loop While l.Count < max OrElse l(l.Count - 2) <> selection.Last()
Console.Write("The first {0} items In the Stern-Brocot sequence: ", take)
Console.WriteLine("{0}" & vbLf, String.Join(", ", l.Take(take)))
Console.WriteLine("The locations of where the selected numbers (1-to-10, & 100) first appear:")
For Each ii As Integer In selection
Dim j As Integer = l.FindIndex(Function(x) x = ii) + 1
Console.WriteLine("{0,3}: {1:n0}", ii, j)
Next : Console.WriteLine() : Dim good As Boolean = True : For i = 1 To max
If gcd(l(i), l(i - 1)) <> 1 Then good = False : Exit For
Next
Console.WriteLine("The greatest common divisor of all the two consecutive items of the" &
" series up to the {0}th item is {1}always one.", max, If(good, "", "not "))
End Sub
End Module |
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
'🌑', '🌒', '🌓', '🌔', '🌕', '🌖', '🌗', '🌘'
| #XPL0 | XPL0 | char I, Rod;
[Rod:= "|/-\ ";
loop for I:= 0 to 3 do
[ChOut(0, Rod(I));
DelayUS(250_000);
ChOut(0, $08\BS\);
if KeyHit then quit;
];
] |
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
'🌑', '🌒', '🌓', '🌔', '🌕', '🌖', '🌗', '🌘'
| #zkl | zkl | foreach n,rod in ((1).MAX, T("|", "/", "-", "\\")){
print(" %s\r".fmt(rod));
Atomic.sleep(0.25);
} |
http://rosettacode.org/wiki/Stack | Stack |
Data Structure
This illustrates a data structure, a means of storing data within a program.
You may see other such structures in the Data Structures category.
A stack is a container of elements with last in, first out access policy. Sometimes it also called LIFO.
The stack is accessed through its top.
The basic stack operations are:
push stores a new element onto the stack top;
pop returns the last pushed stack element, while removing it from the stack;
empty tests if the stack contains no elements.
Sometimes the last pushed stack element is made accessible for immutable access (for read) or mutable access (for write):
top (sometimes called peek to keep with the p theme) returns the topmost element without modifying the stack.
Stacks allow a very simple hardware implementation.
They are common in almost all processors.
In programming, stacks are also very popular for their way (LIFO) of resource management, usually memory.
Nested scopes of language objects are naturally implemented by a stack (sometimes by multiple stacks).
This is a classical way to implement local variables of a re-entrant or recursive subprogram. Stacks are also used to describe a formal computational framework.
See stack machine.
Many algorithms in pattern matching, compiler construction (e.g. recursive descent parsers), and machine learning (e.g. based on tree traversal) have a natural representation in terms of stacks.
Task
Create a stack supporting the basic operations: push, pop, empty.
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
| #D.C3.A9j.C3.A0_Vu | Déjà Vu | local :stack [] #lists used to be stacks in DV
push-to stack 1
push-to stack 2
push-to stack 3
!. pop-from stack #prints 3
!. pop-from stack #prints 2
!. pop-from stack #prints 1
if stack: #empty lists are falsy
error #this stack should be empty now! |
http://rosettacode.org/wiki/Spiral_matrix | Spiral matrix | Task
Produce a spiral array.
A spiral array is a square arrangement of the first N2 natural numbers, where the
numbers increase sequentially as you go around the edges of the array spiraling inwards.
For example, given 5, produce this array:
0 1 2 3 4
15 16 17 18 5
14 23 24 19 6
13 22 21 20 7
12 11 10 9 8
Related tasks
Zig-zag matrix
Identity_matrix
Ulam_spiral_(for_primes)
| #AWK | AWK |
# syntax: GAWK -f SPIRAL_MATRIX.AWK [-v offset={0|1}] [size]
# converted from BBC BASIC
BEGIN {
# offset: "0" prints 0 to size^2-1 while "1" prints 1 to size^2
offset = (offset == "") ? 0 : offset
size = (ARGV[1] == "") ? 5 : ARGV[1]
if (offset !~ /^[01]$/) { exit(1) }
if (size !~ /^[0-9]+$/) { exit(1) }
bot_col = bot_row = 0
top_col = top_row = size - 1
direction = col = row = 0
for (i=0; i<=size*size-1; i++) { # build
arr[col,row] = i + offset
if (direction == 0) {
if (col < top_col) { col++ }
else { direction = 1 ; row++ ; bot_row++ }
}
else if (direction == 1) {
if (row < top_row) { row++ }
else { direction = 2 ; col-- ; top_col-- }
}
else if (direction == 2) {
if (col > bot_col) { col-- }
else { direction = 3 ; row-- ; top_row-- }
}
else if (direction == 3) {
if (row > bot_row) { row-- }
else { direction = 0 ; col++ ; bot_col++ }
}
}
width = length(size ^ 2 - 1 + offset) + 1 # column width
for (i=0; i<size; i++) { # print
for (j=0; j<size; j++) {
printf("%*d",width,arr[j,i])
}
printf("\n")
}
exit(0)
}
|
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.
| #Haskell | Haskell |
# &keyword # type returned(indicators) - brief description
# indicators:
# * - generates multiple values
# = - modifiable
# ? - may fail (e.g. status inquiry)
# U - Unicon
# G - Icon or Unicon with Graphics
#
&allocated # integer(*) - report memory allocated in total and by storage regions
&ascii # cset - ASCII character set
&clock # string - time of day
&col # integer(=G) - column location of pointer
&collections # integer(*) - garbage collection activity in total and by storage region
&column # integer(U) - source code column
&control # null(?G) - control key state
&cset # cset - universal character set
¤t # co-expression - current co-expression
&date # string - today's date
&dateline # string - time stamp
&digits # cset - digit characters
&dump # integer(=) - termination dump
&e # real - natural log e
&error # integer(=) - enable/disable error conversion/fail on error
&errno # integer(?) - variable containing error number from previous posix command
&errornumber # integer(?) - error number of last error converted to failure
&errortext # string(?) - error message of last error converted to failure
&errorvalue # any(?) - erroneous value of last error converted to failure
&errout # file - standard error file
&eventcode # integer(=U) - program execution event in monitored program
&eventsource # co-expression(=U) - source of events in monitoring program
&eventvalue # any(=U) - value from event in monitored program
&fail # none - always fails
&features # string(*) - identifying features in this version of Icon/Unicon
&file # string - current source file
&host # string - host machine name
&input # file - standard input file
&interval # integer(G) - time between input events
&lcase # cset - lowercase letters
&ldrag # integer(G) - left button drag
&letters # cset - letters
&level # integer - call depth
&line # integer - current source line number
&lpress # integer(G) - left button press
&lrelease # integer(G) - left button release
&main # co-expression - main task
&mdrag # integer(G) - middle button drag
&meta # null(?G) - meta key state
&mpress # integer(G) - middle button press
&mrelease # integer(G) - middle button release
&now # integer(U) - current time
&null # null - null value
&output # file - standard output file
&pick # string (U) - variable containing the result of 3D selection
&phi # real - golden ratio
&pos # integer(=) - string scanning position
&progname # string(=) - program name
&random # integer(=) - random number seed
&rdrag # integer(G) - right button drag
®ions # integer(*) - region sizes
&resize # integer(G) - window resize
&row # integer(=G) - row location of pointer
&rpress # integer(G) - right button press
&rrelease # integer(G) - right button release
&shift # null(?G) - shift key state
&source # co-expression - invoking co-expression
&storage # integer(*) - memory in use in each region
&subject # string - string scanning subject
&syserr # integer - halt on system error
&time # integer(=) - elapsed time in milliseconds
&trace # integer(=) - trace program
&ucase # cset - upper case letters
&version # string - version
&window # window(=G) - the current graphics rendering window
&x # integer(=G) - pointer horizontal position
&y # integer(=G) - pointer vertical position
# keywords may also fail if the corresponding feature is not present.
# Other variants of Icon (e.g. MT-Icon) will have different mixes of keywords. |
http://rosettacode.org/wiki/Special_characters | Special characters | Special characters are symbols (single characters or sequences of characters) that have a "special" built-in meaning in the language and typically cannot be used in identifiers.
Escape sequences are methods that the language uses to remove the special meaning from the symbol, enabling it to be used as a normal character, or sequence of characters when this can be done.
Task
List the special characters and show escape sequences in the language.
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
| #ALGOL_68 | ALGOL 68 | printf(($"flip:"g"!"l$,flip));
printf(($"flop:"g"!"l$,flop));
printf(($"blank:"g"!"l$,blank));
printf(($"error char:"g"!"l$,error char));
printf(($"null character:"g"!"l$,null character)) |
http://rosettacode.org/wiki/Special_characters | Special characters | Special characters are symbols (single characters or sequences of characters) that have a "special" built-in meaning in the language and typically cannot be used in identifiers.
Escape sequences are methods that the language uses to remove the special meaning from the symbol, enabling it to be used as a normal character, or sequence of characters when this can be done.
Task
List the special characters and show escape sequences in the language.
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
| #ALGOL_W | ALGOL W | ? A unary or dyadic operator giving 8 bit indirection.
! A unary or dyadic operator giving 32 bit indirection.
# As a prefix indicates a file channel number.
As a suffix indicates a 64-bit numeric variable or constant.
$ As a prefix indicates a 'fixed string' (string indirection).
As a suffix indicates a string variable.
% As a prefix indicates a binary constant e.g. %11101111.
As a suffix indicates an integer (signed 32-bit) variable.
& As a prefix indicates a hexadecimal constant e.g. &EF.
As a suffix indicates a byte (unsigned 8-bit) variable.
' Causes an additional new-line in PRINT or INPUT.
; Suppresses a forthcoming action, e.g. the new-line in PRINT.
@ A prefix character for 'system' variables.
^ A unary operator returning a pointer (address of an object).
The dyadic exponentiation (raise to the power) operator.
\ The line continuation character, to split code across lines.
[ ] Delimiters for assembler statements.
{ } Indicates a structure.
~ Causes conversion to hexadecimal, in PRINT and STR$.
| A unary operator giving floating-point indirection.
A delimiter in the VDU statement.
|
http://rosettacode.org/wiki/Sparkline_in_unicode | Sparkline in unicode | A sparkline is a graph of successive values laid out horizontally
where the height of the line is proportional to the values in succession.
Task
Use the following series of Unicode characters to create a program
that takes a series of numbers separated by one or more whitespace or comma characters
and generates a sparkline-type bar graph of the values on a single line of output.
The eight characters: '▁▂▃▄▅▆▇█'
(Unicode values U+2581 through U+2588).
Use your program to show sparklines for the following input,
here on this page:
1 2 3 4 5 6 7 8 7 6 5 4 3 2 1
1.5, 0.5 3.5, 2.5 5.5, 4.5 7.5, 6.5
(note the mix of separators in this second case)!
Notes
A space is not part of the generated sparkline.
The sparkline may be accompanied by simple statistics of the data such as its range.
A suggestion emerging in later discussion (see Discussion page) is that the bounds between bins should ideally be set to yield the following results for two particular edge cases:
"0, 1, 19, 20" -> ▁▁██
(Aiming to use just two spark levels)
"0, 999, 4000, 4999, 7000, 7999" -> ▁▁▅▅██
(Aiming to use just three spark levels)
It may be helpful to include these cases in output tests.
You may find that the unicode sparklines on this page are rendered less noisily by Google Chrome than by Firefox or Safari.
| #C | C |
#include<string.h>
#include<stdlib.h>
#include<locale.h>
#include<stdio.h>
#include<wchar.h>
#include<math.h>
int main(int argC,char* argV[])
{
double* arr,min,max;
char* str;
int i,len;
if(argC == 1)
printf("Usage : %s <data points separated by spaces or commas>",argV[0]);
else{
arr = (double*)malloc((argC-1)*sizeof(double));
for(i=1;i<argC;i++){
len = strlen(argV[i]);
if(argV[i][len-1]==','){
str = (char*)malloc(len*sizeof(char));
strncpy(str,argV[i],len-1);
arr[i-1] = atof(str);
free(str);
}
else
arr[i-1] = atof(argV[i]);
if(i==1){
min = arr[i-1];
max = arr[i-1];
}
else{
min=(min<arr[i-1]?min:arr[i-1]);
max=(max>arr[i-1]?max:arr[i-1]);
}
}
printf("\n%Max : %lf,Min : %lf,Range : %lf\n",max,min,max-min);
setlocale(LC_ALL, "");
for(i=1;i<argC;i++){
printf("%lc", (wint_t)(9601 + (int)ceil((arr[i-1]-min)/(max-min)*7)));
}
}
return 0;
}
|
http://rosettacode.org/wiki/Sorting_algorithms/Strand_sort | Sorting algorithms/Strand sort |
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
O(n2) sorts
Bubble sort |
Cocktail sort |
Cocktail sort with shifting bounds |
Comb sort |
Cycle sort |
Gnome sort |
Insertion sort |
Selection sort |
Strand sort
other sorts
Bead sort |
Bogo sort |
Common sorted list |
Composite structures sort |
Custom comparator sort |
Counting sort |
Disjoint sublist sort |
External sort |
Jort sort |
Lexicographical sort |
Natural sorting |
Order by pair comparisons |
Order disjoint list items |
Order two numerical lists |
Object identifier (OID) sort |
Pancake sort |
Quickselect |
Permutation sort |
Radix sort |
Ranking methods |
Remove duplicate elements |
Sleep sort |
Stooge sort |
[Sort letters of a string] |
Three variable sort |
Topological sort |
Tree sort
This page uses content from Wikipedia. The original article was at Strand sort. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Task
Implement the Strand sort.
This is a way of sorting numbers by extracting shorter sequences of already sorted numbers from an unsorted list.
| #C.2B.2B | C++ | #include <list>
template <typename T>
std::list<T> strandSort(std::list<T> lst) {
if (lst.size() <= 1)
return lst;
std::list<T> result;
std::list<T> sorted;
while (!lst.empty()) {
sorted.push_back(lst.front());
lst.pop_front();
for (typename std::list<T>::iterator it = lst.begin(); it != lst.end(); ) {
if (sorted.back() <= *it) {
sorted.push_back(*it);
it = lst.erase(it);
} else
it++;
}
result.merge(sorted);
}
return result;
} |
http://rosettacode.org/wiki/Sorting_algorithms/Strand_sort | Sorting algorithms/Strand sort |
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
O(n2) sorts
Bubble sort |
Cocktail sort |
Cocktail sort with shifting bounds |
Comb sort |
Cycle sort |
Gnome sort |
Insertion sort |
Selection sort |
Strand sort
other sorts
Bead sort |
Bogo sort |
Common sorted list |
Composite structures sort |
Custom comparator sort |
Counting sort |
Disjoint sublist sort |
External sort |
Jort sort |
Lexicographical sort |
Natural sorting |
Order by pair comparisons |
Order disjoint list items |
Order two numerical lists |
Object identifier (OID) sort |
Pancake sort |
Quickselect |
Permutation sort |
Radix sort |
Ranking methods |
Remove duplicate elements |
Sleep sort |
Stooge sort |
[Sort letters of a string] |
Three variable sort |
Topological sort |
Tree sort
This page uses content from Wikipedia. The original article was at Strand sort. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Task
Implement the Strand sort.
This is a way of sorting numbers by extracting shorter sequences of already sorted numbers from an unsorted list.
| #Clojure | Clojure | (ns rosettacode.strand-sort)
(defn merge-join
"Produces a globally sorted seq from two sorted seqables"
[[a & la :as all] [b & lb :as bll]]
(cond (nil? a) bll
(nil? b) all
(< a b) (cons a (lazy-seq (merge-join la bll)))
true (cons b (lazy-seq (merge-join all lb)))))
(defn unbraid
"Separates a sorted list from a sequence"
[u]
(when (seq u)
(loop [[x & xs] u
u []
s []
e x]
(if (nil? x)
[s u]
(if (>= x e)
(recur xs u (conj s x) x)
(recur xs (conj u x) s e))))))
(defn strand-sort
"http://en.wikipedia.org/wiki/Strand_sort"
[s]
(loop [[s u] (unbraid s)
m nil]
(if s
(recur (unbraid u) (merge-join m s))
m)))
(strand-sort [1, 6, 3, 2, 1, 7, 5, 3])
;;=> (1 1 2 3 3 5 6 7)
|
http://rosettacode.org/wiki/Stable_marriage_problem | Stable marriage problem | Solve the Stable marriage problem using the Gale/Shapley algorithm.
Problem description
Given an equal number of men and women to be paired for marriage, each man ranks all the women in order of his preference and each woman ranks all the men in order of her preference.
A stable set of engagements for marriage is one where no man prefers a woman over the one he is engaged to, where that other woman also prefers that man over the one she is engaged to. I.e. with consulting marriages, there would be no reason for the engagements between the people to change.
Gale and Shapley proved that there is a stable set of engagements for any set of preferences and the first link above gives their algorithm for finding a set of stable engagements.
Task Specifics
Given ten males:
abe, bob, col, dan, ed, fred, gav, hal, ian, jon
And ten females:
abi, bea, cath, dee, eve, fay, gay, hope, ivy, jan
And a complete list of ranked preferences, where the most liked is to the left:
abe: abi, eve, cath, ivy, jan, dee, fay, bea, hope, gay
bob: cath, hope, abi, dee, eve, fay, bea, jan, ivy, gay
col: hope, eve, abi, dee, bea, fay, ivy, gay, cath, jan
dan: ivy, fay, dee, gay, hope, eve, jan, bea, cath, abi
ed: jan, dee, bea, cath, fay, eve, abi, ivy, hope, gay
fred: bea, abi, dee, gay, eve, ivy, cath, jan, hope, fay
gav: gay, eve, ivy, bea, cath, abi, dee, hope, jan, fay
hal: abi, eve, hope, fay, ivy, cath, jan, bea, gay, dee
ian: hope, cath, dee, gay, bea, abi, fay, ivy, jan, eve
jon: abi, fay, jan, gay, eve, bea, dee, cath, ivy, hope
abi: bob, fred, jon, gav, ian, abe, dan, ed, col, hal
bea: bob, abe, col, fred, gav, dan, ian, ed, jon, hal
cath: fred, bob, ed, gav, hal, col, ian, abe, dan, jon
dee: fred, jon, col, abe, ian, hal, gav, dan, bob, ed
eve: jon, hal, fred, dan, abe, gav, col, ed, ian, bob
fay: bob, abe, ed, ian, jon, dan, fred, gav, col, hal
gay: jon, gav, hal, fred, bob, abe, col, ed, dan, ian
hope: gav, jon, bob, abe, ian, dan, hal, ed, col, fred
ivy: ian, col, hal, gav, fred, bob, abe, ed, jon, dan
jan: ed, hal, gav, abe, bob, jon, col, ian, fred, dan
Use the Gale Shapley algorithm to find a stable set of engagements
Perturb this set of engagements to form an unstable set of engagements then check this new set for stability.
References
The Stable Marriage Problem. (Eloquent description and background information).
Gale-Shapley Algorithm Demonstration.
Another Gale-Shapley Algorithm Demonstration.
Stable Marriage Problem - Numberphile (Video).
Stable Marriage Problem (the math bit) (Video).
The Stable Marriage Problem and School Choice. (Excellent exposition)
| #EchoLisp | EchoLisp |
(lib 'hash)
;; input data
(define M-RANKS
'(( abe abi eve cath ivy jan dee fay bea hope gay)
( bob cath hope abi dee eve fay bea jan ivy gay)
( col hope eve abi dee bea fay ivy gay cath jan)
( dan ivy fay dee gay hope eve jan bea cath abi)
( ed jan dee bea cath fay eve abi ivy hope gay)
( fred bea abi dee gay eve ivy cath jan hope fay)
( gav gay eve ivy bea cath abi dee hope jan fay)
( hal abi eve hope fay ivy cath jan bea gay dee)
( ian hope cath dee gay bea abi fay ivy jan eve)
( jon abi fay jan gay eve bea dee cath ivy hope)))
(define W-RANKS
'(( abi bob fred jon gav ian abe dan ed col hal)
( bea bob abe col fred gav dan ian ed jon hal)
( cath fred bob ed gav hal col ian abe dan jon)
( dee fred jon col abe ian hal gav dan bob ed)
( eve jon hal fred dan abe gav col ed ian bob)
( fay bob abe ed ian jon dan fred gav col hal)
( gay jon gav hal fred bob abe col ed dan ian)
( hope gav jon bob abe ian dan hal ed col fred)
( ivy ian col hal gav fred bob abe ed jon dan)
( jan ed hal gav abe bob jon col ian fred dan)))
;; build preferences hash
(define (set-prefs ranks prefs)
(for/list ((r ranks))
(hash-set prefs (first r) (rest r))
(first r)))
(define (engage m w) (hash-set ENGAGED m w) (hash-set ENGAGED w m) (writeln m w '👫 ))
(define (disengage m w) (hash-remove! ENGAGED m ) (hash-remove! ENGAGED w) (writeln '💔 m w))
(define (engaged x) (hash-ref ENGAGED x))
(define (free? x) (not (engaged x)))
(define (free-man men) (for ((man men)) #:break (free? man) => man #f))
(define (prefers? prefs x a b) (member b (member a (hash-ref prefs x))))
;; get first choice and remove it from prefs list
(define (first-choice prefs m)
(define w (first (hash-ref prefs m)))
(hash-set prefs m (rest (hash-ref prefs m)))
w)
;; sets ENGAGED couples
;; https//en.wikipedia.org/wiki/Stable_marriage_problem
(define (stableMatching (prefs (make-hash)) (m) (w))
(define-global 'ENGAGED (make-hash))
(define men (set-prefs M-RANKS prefs))
(define women (set-prefs W-RANKS prefs))
(while (setv! m (free-man men))
(set! w (first-choice prefs m))
(if (free? w)
(engage m w)
(let [(dumped (engaged w))]
(when (prefers? prefs w m dumped)
(disengage w dumped)
(engage w m)))))
(hash->list ENGAGED))
;; input : ENGAGED couples
(define (checkStable (prefs (make-hash)))
(define men (set-prefs M-RANKS prefs))
(define women (set-prefs W-RANKS prefs))
(for* [(man men) (woman women)]
#:continue (equal? woman (engaged man))
(when (and
(prefers? prefs man woman (engaged man))
(prefers? prefs woman man (engaged woman)))
(error 'not-stable (list man woman)))))
|
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
| #Swift | Swift | fileprivate class NumberNames {
let cardinal: String
let ordinal: String
init(cardinal: String, ordinal: String) {
self.cardinal = cardinal
self.ordinal = ordinal
}
func getName(_ ordinal: Bool) -> String {
return ordinal ? self.ordinal : self.cardinal
}
class func numberName(number: Int, ordinal: Bool) -> String {
guard number < 100 else {
return ""
}
if number < 20 {
return smallNames[number].getName(ordinal)
}
if number % 10 == 0 {
return tens[number/10 - 2].getName(ordinal)
}
var result = tens[number/10 - 2].getName(false)
result += "-"
result += smallNames[number % 10].getName(ordinal)
return result
}
static let smallNames = [
NumberNames(cardinal: "zero", ordinal: "zeroth"),
NumberNames(cardinal: "one", ordinal: "first"),
NumberNames(cardinal: "two", ordinal: "second"),
NumberNames(cardinal: "three", ordinal: "third"),
NumberNames(cardinal: "four", ordinal: "fourth"),
NumberNames(cardinal: "five", ordinal: "fifth"),
NumberNames(cardinal: "six", ordinal: "sixth"),
NumberNames(cardinal: "seven", ordinal: "seventh"),
NumberNames(cardinal: "eight", ordinal: "eighth"),
NumberNames(cardinal: "nine", ordinal: "ninth"),
NumberNames(cardinal: "ten", ordinal: "tenth"),
NumberNames(cardinal: "eleven", ordinal: "eleventh"),
NumberNames(cardinal: "twelve", ordinal: "twelfth"),
NumberNames(cardinal: "thirteen", ordinal: "thirteenth"),
NumberNames(cardinal: "fourteen", ordinal: "fourteenth"),
NumberNames(cardinal: "fifteen", ordinal: "fifteenth"),
NumberNames(cardinal: "sixteen", ordinal: "sixteenth"),
NumberNames(cardinal: "seventeen", ordinal: "seventeenth"),
NumberNames(cardinal: "eighteen", ordinal: "eighteenth"),
NumberNames(cardinal: "nineteen", ordinal: "nineteenth")
]
static let tens = [
NumberNames(cardinal: "twenty", ordinal: "twentieth"),
NumberNames(cardinal: "thirty", ordinal: "thirtieth"),
NumberNames(cardinal: "forty", ordinal: "fortieth"),
NumberNames(cardinal: "fifty", ordinal: "fiftieth"),
NumberNames(cardinal: "sixty", ordinal: "sixtieth"),
NumberNames(cardinal: "seventy", ordinal: "seventieth"),
NumberNames(cardinal: "eighty", ordinal: "eightieth"),
NumberNames(cardinal: "ninety", ordinal: "ninetieth")
]
}
fileprivate class NamedPower {
let cardinal: String
let ordinal: String
let number: UInt64
init(cardinal: String, ordinal: String, number: UInt64) {
self.cardinal = cardinal
self.ordinal = ordinal
self.number = number
}
func getName(_ ordinal: Bool) -> String {
return ordinal ? self.ordinal : self.cardinal
}
class func getNamedPower(_ number: UInt64) -> NamedPower {
for i in 1..<namedPowers.count {
if number < namedPowers[i].number {
return namedPowers[i - 1]
}
}
return namedPowers[namedPowers.count - 1]
}
static let namedPowers = [
NamedPower(cardinal: "hundred", ordinal: "hundredth",
number: 100),
NamedPower(cardinal: "thousand", ordinal: "thousandth",
number: 1000),
NamedPower(cardinal: "million", ordinal: "millionth",
number: 1000000),
NamedPower(cardinal: "billion", ordinal: "billionth",
number: 1000000000),
NamedPower(cardinal: "trillion", ordinal: "trillionth",
number: 1000000000000),
NamedPower(cardinal: "quadrillion", ordinal: "quadrillionth",
number: 1000000000000000),
NamedPower(cardinal: "quintillion", ordinal: "quintillionth",
number: 1000000000000000000)
]
}
public func numberName(number: UInt64, ordinal: Bool) -> String {
if number < 100 {
return NumberNames.numberName(number: Int(truncatingIfNeeded: number),
ordinal: ordinal)
}
let p = NamedPower.getNamedPower(number)
var result = numberName(number: number/p.number, ordinal: false)
result += " "
if number % p.number == 0 {
result += p.getName(ordinal)
} else {
result += p.getName(false)
result += " "
result += numberName(number: number % p.number, ordinal: ordinal)
}
return result
}
func printOrdinal(_ number: UInt64) {
print("\(number): \(numberName(number: number, ordinal: true))")
}
printOrdinal(1)
printOrdinal(2)
printOrdinal(3)
printOrdinal(4)
printOrdinal(5)
printOrdinal(11)
printOrdinal(15)
printOrdinal(21)
printOrdinal(42)
printOrdinal(65)
printOrdinal(98)
printOrdinal(100)
printOrdinal(101)
printOrdinal(272)
printOrdinal(300)
printOrdinal(750)
printOrdinal(23456)
printOrdinal(7891233)
printOrdinal(8007006005004003) |
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
| #VBA | VBA | Private Function ordinal(s As String) As String
Dim irregs As New Collection
irregs.Add "first", "one"
irregs.Add "second", "two"
irregs.Add "third", "three"
irregs.Add "fifth", "five"
irregs.Add "eighth", "eight"
irregs.Add "ninth", "nine"
irregs.Add "twelfth", "twelve"
Dim i As Integer
For i = Len(s) To 1 Step -1
ch = Mid(s, i, 1)
If ch = " " Or ch = "-" Then Exit For
Next i
On Error GoTo 1
ord = irregs(Right(s, Len(s) - i))
ordinal = Left(s, i) & ord
Exit Function
1:
If Right(s, 1) = "y" Then
s = Left(s, Len(s) - 1) & "ieth"
Else
s = s & "th"
End If
ordinal = s
End Function
Public Sub ordinals()
tests = [{1, 2, 3, 4, 5, 11, 65, 100, 101, 272, 23456, 8007006005004003, 123, 00123.0, 1.23E2}]
init
For i = 1 To UBound(tests)
Debug.Print ordinal(spell(tests(i)))
Next i
End Sub |
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.
| #Python | Python | # nonCubeSquares :: Int -> [(Int, Bool)]
def nonCubeSquares(n):
upto = enumFromTo(1)
ns = upto(n)
setCubes = set(x ** 3 for x in ns)
ms = upto(n + len(set(x * x for x in ns).intersection(
setCubes
)))
return list(tuple([x * x, x in setCubes]) for x in ms)
# squareListing :: [(Int, Bool)] -> [String]
def squareListing(xs):
justifyIdx = justifyRight(len(str(1 + len(xs))))(' ')
justifySqr = justifyRight(1 + len(str(xs[-1][0])))(' ')
return list(
'(' + str(1 + idx) + '^2 = ' + str(n) +
' = ' + str(round(n ** (1 / 3))) + '^3)' if bln else (
justifyIdx(1 + idx) + ' ->' +
justifySqr(n)
)
for idx, (n, bln) in enumerate(xs)
)
def main():
print(
unlines(
squareListing(
nonCubeSquares(30)
)
)
)
# GENERIC ------------------------------------------------------------------
# enumFromTo :: Int -> Int -> [Int]
def enumFromTo(m):
return lambda n: list(range(m, 1 + n))
# justifyRight :: Int -> Char -> String -> String
def justifyRight(n):
return lambda cFiller: lambda a: (
((n * cFiller) + str(a))[-n:]
)
# unlines :: [String] -> String
def unlines(xs):
return '\n'.join(xs)
main() |
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
| #Perl | Perl | use strict;
use warnings;
use feature 'say';
use utf8;
binmode(STDOUT, ':utf8');
for my $string (q[gHHH5YY++///\\], q[fffn⃗n⃗n⃗»»» ℵℵ☄☄☃☃̂☃🤔🇺🇸🤦♂️👨👩👧👦]) {
my @S;
my $last = '';
while ($string =~ /(\X)/g) {
if ($last eq $1) { $S[-1] .= $1 } else { push @S, $1 }
$last = $1;
}
say "Orginal: $string\n Split: 「" . join('」, 「', @S) . "」\n";
} |
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
| #Phix | Phix | function split_on_change(string s)
string res = ""
if length(s) then
integer prev = s[1]
for i=1 to length(s) do
integer ch = s[i]
if ch!=prev then
res &= ", "
prev = ch
end if
res &= ch
end for
end if
return res
end function
puts(1,split_on_change(`gHHH5YY++///\`))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.