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/Temperature_conversion | Temperature conversion | There are quite a number of temperature scales. For this task we will concentrate on four of the perhaps best-known ones:
Kelvin, Celsius, Fahrenheit, and Rankine.
The Celsius and Kelvin scales have the same magnitude, but different null points.
0 degrees Celsius corresponds to 273.15 kelvin.
0 kelvin is absolute zero.
The Fahrenheit and Rankine scales also have the same magnitude, but different null points.
0 degrees Fahrenheit corresponds to 459.67 degrees Rankine.
0 degrees Rankine is absolute zero.
The Celsius/Kelvin and Fahrenheit/Rankine scales have a ratio of 5Β : 9.
Task
Write code that accepts a value of kelvin, converts it to values of the three other scales, and prints the result.
Example
K 21.00
C -252.15
F -421.87
R 37.80
| #AutoIt | AutoIt | ; ### USAGE - TESTING PURPOSES ONLY
Β
Local Const $_KELVIN = 21
ConsoleWrite("Kelvin: " & $_KELVIN & @CRLF)
ConsoleWrite("Kelvin: " & Kelvin(21, "C") & @CRLF)
ConsoleWrite("Kelvin: " & Kelvin(21, "F") & @CRLF)
ConsoleWrite("Kelvin: " & Kelvin(21, "R") & @CRLF)
Β
; ### KELVIN TEMPERATURE CONVERSIONS
Β
Func Kelvin($degrees, $conversion)
Select
Case $conversion = "C"
Return Round($degrees - 273.15, 2)
Case $conversion = "F"
Return Round(($degrees * 1.8) - 459.67, 2)
Case $conversion = "R"
Return Round($degrees * 1.8, 2)
EndSelect
EndFunc ;==> Kelvin |
http://rosettacode.org/wiki/Tau_function | Tau function | Given a positive integer, count the number of its positive divisors.
Task
Show the result for the first Β 100 Β positive integers.
Related task
Β Tau number
| #Factor | Factor | USING: assocs formatting io kernel math math.primes.factors
math.ranges sequences sequences.extrasΒ ;
Β
ERROR: nonpositive nΒ ;
Β
: (tau) ( n -- count )
group-factors values [ 1 + ] map-productΒ ; inline
Β
: tau ( n -- count ) dup 0 > [ (tau) ] [ nonpositive ] ifΒ ;
Β
"Number of divisors for integers 1-100:" print nl
" n | tau(n)" print
"-----+-----------------------------------------" print
1 100 10 <range> [
[ "%2d |" printf ]
[ dup 10 + [a,b) [ tau "%4d" printf ] each nl ] bi
] each |
http://rosettacode.org/wiki/Tau_function | Tau function | Given a positive integer, count the number of its positive divisors.
Task
Show the result for the first Β 100 Β positive integers.
Related task
Β Tau number
| #Fermat | Fermat | Func Tau(t) =
if t<3 then Return(t) else
numdiv:=2;
for q = 2 to t\2 do
if Divides(q, t) then numdiv:=numdiv+1 fi;
od;
Return(numdiv);
fi;
.;
Β
for i = 1 to 100 do
Β !(Tau(i),' ');
od; |
http://rosettacode.org/wiki/Tau_function | Tau function | Given a positive integer, count the number of its positive divisors.
Task
Show the result for the first Β 100 Β positive integers.
Related task
Β Tau number
| #Forth | Forth | : divisor_count ( n -- n )
1 >r
begin
dup 2 mod 0=
while
r> 1+ >r
2/
repeat
3
begin
2dup dup * >=
while
1 >r
begin
2dup mod 0=
while
r> 1+ >r
tuck / swap
repeat
2r> * >r
2 +
repeat
drop 1 > if r> 2* else r> thenΒ ;
Β
: print_divisor_counts ( n -- )
." Count of divisors for the first " dup . ." positive integers:" cr
1+ 1 do
i divisor_count 2 .r
i 20 mod 0= if cr else space then
loopΒ ;
Β
100 print_divisor_counts
bye |
http://rosettacode.org/wiki/Terminal_control/Clear_the_screen | Terminal control/Clear the screen | Task
Clear the terminal window.
| #jq | jq | "\u001B[2J" |
http://rosettacode.org/wiki/Terminal_control/Clear_the_screen | Terminal control/Clear the screen | Task
Clear the terminal window.
| #Jsish | Jsish | /* Terminal Control, clear the screen, in Jsish */
function cls() { printf('\u001b[2J'); }
Β
;cls();
Β
/*
=!EXPECTSTART!=
cls() ==> ^[[2Jundefined
=!EXPECTEND!=
*/ |
http://rosettacode.org/wiki/Terminal_control/Clear_the_screen | Terminal control/Clear the screen | Task
Clear the terminal window.
| #Julia | Julia | Β
println("\33[2J")
Β |
http://rosettacode.org/wiki/Ternary_logic | Ternary logic |
This page uses content from Wikipedia. The original article was at Ternary logic. 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)
In logic, a three-valued logic (also trivalent, ternary, or trinary logic, sometimes abbreviated 3VL) is any of several many-valued logic systems in which there are three truth values indicating true, false and some indeterminate third value.
This is contrasted with the more commonly known bivalent logics (such as classical sentential or boolean logic) which provide only for true and false.
Conceptual form and basic ideas were initially created by Εukasiewicz, Lewis and Sulski.
These were then re-formulated by Grigore Moisil in an axiomatic algebraic form, and also extended to n-valued logics in 1945.
Example Ternary Logic Operators in Truth Tables:
not a
Β¬
True
False
Maybe
Maybe
False
True
a and b
β§
True
Maybe
False
True
True
Maybe
False
Maybe
Maybe
Maybe
False
False
False
False
False
a or b
β¨
True
Maybe
False
True
True
True
True
Maybe
True
Maybe
Maybe
False
True
Maybe
False
if a then b
β
True
Maybe
False
True
True
Maybe
False
Maybe
True
Maybe
Maybe
False
True
True
True
a is equivalent to b
β‘
True
Maybe
False
True
True
Maybe
False
Maybe
Maybe
Maybe
Maybe
False
False
Maybe
True
Task
Define a new type that emulates ternary logic by storing data trits.
Given all the binary logic operators of the original programming language, reimplement these operators for the new Ternary logic type trit.
Generate a sampling of results using trit variables.
Kudos for actually thinking up a test case algorithm where ternary logic is intrinsically useful, optimises the test case algorithm and is preferable to binary logic.
Note: Β Setun Β (Π‘Π΅ΡΡΠ½Ρ) was a Β balanced ternary Β computer developed in 1958 at Β Moscow State University. Β The device was built under the lead of Β Sergei Sobolev Β and Β Nikolay Brusentsov. Β It was the only modern Β ternary computer, Β using three-valued ternary logic
| #jq | jq | def ternary_nand(a; b):
if a == false or b == false then true
elif a == "maybe" or b == "maybe" then "maybe"
else false
endΒ ;
Β
def ternary_not(a): ternary_nand(a; a);
Β
def ternary_or(a; b): ternary_nand( ternary_not(a); ternary_not(b) );
Β
def ternary_nor(a; b): ternary_not( ternary_or(a;b) );
Β
def ternary_and(a; b): ternary_not( ternary_nand(a; b) );
Β
def ternary_imply(this; that):
ternary_nand(this, ternary_not(that));
Β
def ternary_equiv(this; that):
ternary_or( ternary_and(this; that); ternary_nor(this; that) );
Β
def display_and(a; b):
a as $a | b as $b
| "\($a) and \($b) is \( ternary_and($a; $b) )";
def display_equiv(a; b):
a as $a | b as $b
| "\($a) equiv \($b) is \( ternary_equiv($a; $b) )";
# etc etc
Β
# Invoke the display functions:
display_and( (false, "maybe", true ); (false, "maybe", true) ),
display_equiv( (false, "maybe", true ); (false, "maybe", true) ),
"etc etc"
Β |
http://rosettacode.org/wiki/Ternary_logic | Ternary logic |
This page uses content from Wikipedia. The original article was at Ternary logic. 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)
In logic, a three-valued logic (also trivalent, ternary, or trinary logic, sometimes abbreviated 3VL) is any of several many-valued logic systems in which there are three truth values indicating true, false and some indeterminate third value.
This is contrasted with the more commonly known bivalent logics (such as classical sentential or boolean logic) which provide only for true and false.
Conceptual form and basic ideas were initially created by Εukasiewicz, Lewis and Sulski.
These were then re-formulated by Grigore Moisil in an axiomatic algebraic form, and also extended to n-valued logics in 1945.
Example Ternary Logic Operators in Truth Tables:
not a
Β¬
True
False
Maybe
Maybe
False
True
a and b
β§
True
Maybe
False
True
True
Maybe
False
Maybe
Maybe
Maybe
False
False
False
False
False
a or b
β¨
True
Maybe
False
True
True
True
True
Maybe
True
Maybe
Maybe
False
True
Maybe
False
if a then b
β
True
Maybe
False
True
True
Maybe
False
Maybe
True
Maybe
Maybe
False
True
True
True
a is equivalent to b
β‘
True
Maybe
False
True
True
Maybe
False
Maybe
Maybe
Maybe
Maybe
False
False
Maybe
True
Task
Define a new type that emulates ternary logic by storing data trits.
Given all the binary logic operators of the original programming language, reimplement these operators for the new Ternary logic type trit.
Generate a sampling of results using trit variables.
Kudos for actually thinking up a test case algorithm where ternary logic is intrinsically useful, optimises the test case algorithm and is preferable to binary logic.
Note: Β Setun Β (Π‘Π΅ΡΡΠ½Ρ) was a Β balanced ternary Β computer developed in 1958 at Β Moscow State University. Β The device was built under the lead of Β Sergei Sobolev Β and Β Nikolay Brusentsov. Β It was the only modern Β ternary computer, Β using three-valued ternary logic
| #Julia | Julia | @enum Trit False Maybe True
const trits = (False, Maybe, True)
Β
Base.:!(a::Trit) = a == FalseΒ ? TrueΒ : a == MaybeΒ ? MaybeΒ : False
β§(a::Trit, b::Trit) = a == b == TrueΒ ? TrueΒ : (a, b) β FalseΒ ? FalseΒ : Maybe
β¨(a::Trit, b::Trit) = a == b == FalseΒ ? FalseΒ : (a, b) β TrueΒ ? TrueΒ : Maybe
β(a::Trit, b::Trit) = a == False || b == TrueΒ ? TrueΒ : (a, b) β MaybeΒ ? MaybeΒ : False
β‘(a::Trit, b::Trit) = (a, b) β MaybeΒ ? MaybeΒ : a == bΒ ? TrueΒ : False
Β
println("Not (!):")
println(join(@sprintf("%10s%s isΒ %5s", "!", t,Β !t) for t in trits))
println("And (β§):")
for a in trits
println(join(@sprintf("%10s β§Β %5s isΒ %5s", a, b, a β§ b) for b in trits))
end
println("Or (β¨):")
for a in trits
println(join(@sprintf("%10s β¨Β %5s isΒ %5s", a, b, a β¨ b) for b in trits))
end
println("If Then (β):")
for a in trits
println(join(@sprintf("%10s βΒ %5s isΒ %5s", a, b, a β b) for b in trits))
end
println("Equivalent (β‘):")
for a in trits
println(join(@sprintf("%10s β‘Β %5s isΒ %5s", a, b, a β‘ b) for b in trits))
end |
http://rosettacode.org/wiki/Text_processing/1 | Text processing/1 | This task has been flagged for clarification. Code on this page in its current state may be flagged incorrect once this task has been clarified. See this page's Talk page for discussion.
Often data is produced by one program, in the wrong format for later use by another program or person. In these situations another program can be written to parse and transform the original data into a format useful to the other. The term "Data Munging" is often used in programming circles for this task.
A request on the comp.lang.awk newsgroup led to a typical data munging task:
I have to analyse data files that have the following format:
Each row corresponds to 1 day and the field logic is: $1 is the date,
followed by 24 value/flag pairs, representing measurements at 01:00,
02:00 ... 24:00 of the respective day. In short:
<date> <val1> <flag1> <val2> <flag2> ... <val24> <flag24>
Some test data is available at:
... (nolonger available at original location)
I have to sum up the values (per day and only valid data, i.e. with
flag>0) in order to calculate the mean. That's not too difficult.
However, I also need to know what the "maximum data gap" is, i.e. the
longest period with successive invalid measurements (i.e values with
flag<=0)
The data is free to download and use and is of this format:
Data is no longer available at that link. Zipped mirror available here (offsite mirror).
1991-03-30 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1
1991-03-31 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 20.000 1 20.000 1 20.000 1 35.000 1 50.000 1 60.000 1 40.000 1 30.000 1 30.000 1 30.000 1 25.000 1 20.000 1 20.000 1 20.000 1 20.000 1 20.000 1 35.000 1
1991-03-31 40.000 1 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2
1991-04-01 0.000 -2 13.000 1 16.000 1 21.000 1 24.000 1 22.000 1 20.000 1 18.000 1 29.000 1 44.000 1 50.000 1 43.000 1 38.000 1 27.000 1 27.000 1 24.000 1 23.000 1 18.000 1 12.000 1 13.000 1 14.000 1 15.000 1 13.000 1 10.000 1
1991-04-02 8.000 1 9.000 1 11.000 1 12.000 1 12.000 1 12.000 1 27.000 1 26.000 1 27.000 1 33.000 1 32.000 1 31.000 1 29.000 1 31.000 1 25.000 1 25.000 1 24.000 1 21.000 1 17.000 1 14.000 1 15.000 1 12.000 1 12.000 1 10.000 1
1991-04-03 10.000 1 9.000 1 10.000 1 10.000 1 9.000 1 10.000 1 15.000 1 24.000 1 28.000 1 24.000 1 18.000 1 14.000 1 12.000 1 13.000 1 14.000 1 15.000 1 14.000 1 15.000 1 13.000 1 13.000 1 13.000 1 12.000 1 10.000 1 10.000 1
Only a sample of the data showing its format is given above. The full example file may be downloaded here.
Structure your program to show statistics for each line of the file, (similar to the original Python, Perl, and AWK examples below), followed by summary statistics for the file. When showing example output just show a few line statistics and the full end summary.
| #OCaml | OCaml | let input_line ic =
try Some(input_line ic)
with End_of_file -> None
Β
let fold_input f ini ic =
let rec fold ac =
match input_line ic with
| Some line -> fold (f ac line)
| None -> ac
in
fold ini
Β
let ic = open_in "readings.txt"
Β
let scan line =
Scanf.sscanf line "%s\
\t%f\t%d\t%f\t%d\t%f\t%d\t%f\t%d\t%f\t%d\t%f\t%d\
\t%f\t%d\t%f\t%d\t%f\t%d\t%f\t%d\t%f\t%d\t%f\t%d\
\t%f\t%d\t%f\t%d\t%f\t%d\t%f\t%d\t%f\t%d\t%f\t%d\
\t%f\t%d\t%f\t%d\t%f\t%d\t%f\t%d\t%f\t%d\t%f\t%d"
(fun date
v1 f1 v2 f2 v3 f3 v4 f4 v5 f5 v6 f6
v7 f7 v8 f8 v9 f9 v10 f10 v11 f11 v12 f12
v13 f13 v14 f14 v15 f15 v16 f16 v17 f17 v18 f18
v19 f19 v20 f20 v21 f21 v22 f22 v23 f23 v24 f24 ->
(date),
[ (v1, f1 ); (v2, f2 ); (v3, f3 ); (v4, f4 ); (v5, f5 ); (v6, f6 );
(v7, f7 ); (v8, f8 ); (v9, f9 ); (v10, f10); (v11, f11); (v12, f12);
(v13, f13); (v14, f14); (v15, f15); (v16, f16); (v17, f17); (v18, f18);
(v19, f19); (v20, f20); (v21, f21); (v22, f22); (v23, f23); (v24, f24); ])
Β
let tot_file, num_file, _, nodata_max, nodata_maxline =
fold_input
(fun (tot_file, num_file, nodata, nodata_max, nodata_maxline) line ->
let date, datas = scan line in
let _datas = List.filter (fun (_, flag) -> flag > 0) datas in
let ok = List.length _datas in
let tot = List.fold_left (fun ac (value, _) -> ac +. value) 0.0 _datas in
let nodata, nodata_max, nodata_maxline =
List.fold_left
(fun (nodata, nodata_max, nodata_maxline) (_, flag) ->
if flag <= 0
then (succ nodata, nodata_max, nodata_maxline)
else
if nodata_max = nodata && nodata > 0
then (0, nodata_max, date::nodata_maxline)
else if nodata_max < nodata && nodata > 0
then (0, nodata, [date])
else (0, nodata_max, nodata_maxline)
)
(nodata, nodata_max, nodata_maxline) datas in
Printf.printf "Line:Β %s" date;
Printf.printf " Reject:Β %2d Accept:Β %2d" (24 - ok) ok;
Printf.printf "\tLine_tot:Β %8.3f" tot;
Printf.printf "\tLine_avg:Β %8.3f\n" (tot /. float ok);
(tot_file +. tot, num_file + ok, nodata, nodata_max, nodata_maxline))
(0.0, 0, 0, 0, [])
ic ;;
Β
close_in ic ;;
Β
Printf.printf "Total =Β %f\n" tot_file;
Printf.printf "Readings =Β %d\n" num_file;
Printf.printf "Average =Β %f\n" (tot_file /. float num_file);
Printf.printf "Maximum run(s) ofΒ %d consecutive false readings \
ends at line starting with date(s):Β %s\n"
nodata_max (String.concat ", " nodata_maxline); |
http://rosettacode.org/wiki/The_Twelve_Days_of_Christmas | The Twelve Days of Christmas | Task
Write a program that outputs the lyrics of the Christmas carol The Twelve Days of Christmas.
The lyrics can be found here.
(You must reproduce the words in the correct order, but case, format, and punctuation are left to your discretion.)
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string Β (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff Β (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #J | J | require 'strings' NB. not necessary for versions > j6
Β
days=:Β ;:'first second third fourth fifth sixth seventh eighth ninth tenth eleventh twelfth'
Β
gifts=: <;.2 ] 0Β : 0
And a partridge in a pear tree.
Two turtle doves,
Three french hens,
Four calling birds,
Five golden rings,
Six geese a-laying,
Seven swans a-swimming,
Eight maids a-milking,
Nine ladies dancing,
Ten lords a-leaping,
Eleven pipers piping,
Twelve drummers drumming,
)
Β
firstline=: 'On the ' , ,&(' day of Christmas, my true love gave to me',LF)
Β
chgFirstVerse=: rplc&('nd a';'')&.>@{. , }.
Β
makeVerses=: [: chgFirstVerse (firstline&.> days) ,&.> [: <@;@|.\ gifts"_
Β
singCarol=: LF joinstring makeVerses |
http://rosettacode.org/wiki/The_Twelve_Days_of_Christmas | The Twelve Days of Christmas | Task
Write a program that outputs the lyrics of the Christmas carol The Twelve Days of Christmas.
The lyrics can be found here.
(You must reproduce the words in the correct order, but case, format, and punctuation are left to your discretion.)
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string Β (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff Β (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Java | Java | public class TwelveDaysOfChristmas {
Β
final static String[] gifts = {
"A partridge in a pear tree.", "Two turtle doves and",
"Three french hens", "Four calling birds",
"Five golden rings", "Six geese a-laying",
"Seven swans a-swimming", "Eight maids a-milking",
"Nine ladies dancing", "Ten lords a-leaping",
"Eleven pipers piping", "Twelve drummers drumming",
"And a partridge in a pear tree.", "Two turtle doves"
};
Β
final static String[] days = {
"first", "second", "third", "fourth", "fifth", "sixth", "seventh",
"eighth", "ninth", "tenth", "eleventh", "Twelfth"
};
Β
public static void main(String[] args) {
for (int i = 0; i < days.length; i++) {
System.out.printf("%nOn theΒ %s day of Christmas%n", days[i]);
System.out.println("My true love gave to me:");
for (int j = i; j >= 0; j--)
System.out.println(gifts[i == 11 && j < 2 ? j + 12 : j]);
}
}
} |
http://rosettacode.org/wiki/Terminal_control/Coloured_text | Terminal control/Coloured text | Task
Display a word in various colours on the terminal.
The system palette, or colours such as Red, Green, Blue, Magenta, Cyan, and Yellow can be used.
Optionally demonstrate:
How the system should determine if the terminal supports colour
Setting of the background colour
How to cause blinking or flashing (if supported by the terminal)
| #Perl | Perl | my %colors = (
red => "\e[1;31m",
green => "\e[1;32m",
yellow => "\e[1;33m",
blue => "\e[1;34m",
magenta => "\e[1;35m",
cyan => "\e[1;36m"
);
$clr = "\e[0m";
Β
print "$colors{$_}$_ text $clr\n" for sort keys %colors;
Β
# the Raku code also works
use feature 'say';
use Term::ANSIColor;
Β
say colored('RED ON WHITE', 'bold red on_white');
say colored('GREEN', 'bold green');
say colored('BLUE ON YELLOW', 'bold blue on_yellow');
say colored('MAGENTA', 'bold magenta');
say colored('CYAN ON RED', 'bold cyan on_red');
say colored('YELLOW', 'bold yellow'); |
http://rosettacode.org/wiki/Terminal_control/Coloured_text | Terminal control/Coloured text | Task
Display a word in various colours on the terminal.
The system palette, or colours such as Red, Green, Blue, Magenta, Cyan, and Yellow can be used.
Optionally demonstrate:
How the system should determine if the terminal supports colour
Setting of the background colour
How to cause blinking or flashing (if supported by the terminal)
| #Phix | Phix | --
-- demo\rosetta\Coloured_text.exw
-- ==============================
--
with javascript_semantics
text_color(GRAY)
bk_color(BLACK)
printf(1,"Background color# 00 01 02 03 04 05 06 07 08 09 10 11 12 13 14 15\n")
printf(1," -----------------------------------------------\n")
for foreground=0 to 15 do
printf(1,"Foreground color#Β %02d ",foreground)
for background=0 to 15 do
text_color(foreground)
bk_color(background)
printf(1,"%02d",foreground)
text_color(GRAY)
bk_color(BLACK)
printf(1," ")
end for
printf(1,"\n")
end for
printf(1,"\n\npress enter to exit")
{} = wait_key()
|
http://rosettacode.org/wiki/Synchronous_concurrency | Synchronous concurrency | The goal of this task is to create two concurrent activities ("Threads" or "Tasks", not processes.) that share data synchronously. Your language may provide syntax or libraries to perform concurrency. Different languages provide different implementations of concurrency, often with different names. Some languages use the term threads, others use the term tasks, while others use co-processes. This task should not be implemented using fork, spawn, or the Linux/UNIX/Win32 pipe command, as communication should be between threads, not processes.
One of the concurrent units will read from a file named "input.txt" and send the contents of that file, one line at a time, to the other concurrent unit, which will print the line it receives to standard output. The printing unit must count the number of lines it prints. After the concurrent unit reading the file sends its last line to the printing unit, the reading unit will request the number of lines printed by the printing unit. The reading unit will then print the number of lines printed by the printing unit.
This task requires two-way communication between the concurrent units. All concurrent units must cleanly terminate at the end of the program.
| #Clojure | Clojure | (use '[clojure.java.ioΒ :as io])
Β
(def writer (agent 0))
Β
(defn write-line [state line]
(println line)
(inc state)) |
http://rosettacode.org/wiki/Synchronous_concurrency | Synchronous concurrency | The goal of this task is to create two concurrent activities ("Threads" or "Tasks", not processes.) that share data synchronously. Your language may provide syntax or libraries to perform concurrency. Different languages provide different implementations of concurrency, often with different names. Some languages use the term threads, others use the term tasks, while others use co-processes. This task should not be implemented using fork, spawn, or the Linux/UNIX/Win32 pipe command, as communication should be between threads, not processes.
One of the concurrent units will read from a file named "input.txt" and send the contents of that file, one line at a time, to the other concurrent unit, which will print the line it receives to standard output. The printing unit must count the number of lines it prints. After the concurrent unit reading the file sends its last line to the printing unit, the reading unit will request the number of lines printed by the printing unit. The reading unit will then print the number of lines printed by the printing unit.
This task requires two-way communication between the concurrent units. All concurrent units must cleanly terminate at the end of the program.
| #Common_Lisp | Common Lisp | (defvar *self*)
Β
(defclass queue ()
((condition :initform (make-condition-variable)
:reader condition-of)
(mailbox :initform '()
:accessor mailbox-of)
(lock :initform (make-lock)
:reader lock-of)))
Β
(defun message (recipient name &rest message)
(with-lock-held ((lock-of recipient))
;; it would have been better to implement tail-consing or a LIFO
(setf (mailbox-of recipient)
(nconc (mailbox-of recipient)
(list (list* name message))))
(condition-notify (condition-of recipient)))
message)
Β
(defun mklist (x)
(if (listp x)
x
(list x)))
Β
(defun slurp-message ()
(with-lock-held ((lock-of *self*))
(if (not (endp (mailbox-of *self*)))
(pop (mailbox-of *self*))
(progn (condition-wait (condition-of *self*)
(lock-of *self*))
(assert (not (endp (mailbox-of *self*))))
(pop (mailbox-of *self*))))))
Β
(defmacro receive-message (&body cases)
(let ((msg-name (gensym "MESSAGE"))
(block-name (gensym "BLOCK")))
`(let ((,msg-name (slurp-message)))
(block ,block-name
,@(loop for i in cases
for ((name . case) . body) = (cons (mklist (car i))
(cdr i))
when (typep i '(or (cons (eql quote)
t)
(cons (cons (eql quote) t)
t)))
do (warn "~S is a quoted form" i)
collect `(when ,(if (null name)
't
`(eql ',name (car ,msg-name)))
(destructuring-bind ,case
(cdr ,msg-name)
(return-from ,block-name
(progn ,@body)))))
(error "Unknown message: ~S" ,msg-name)))))
Β
(defmacro receive-one-message (message &body body)
`(receive-message (,message . ,body)))
Β
(defun queue () (make-instance 'queue)) |
http://rosettacode.org/wiki/Table_creation/Postal_addresses | Table creation/Postal addresses | Task
Create a table to store addresses.
You may assume that all the addresses to be stored will be located in the USA. Β As such, you will need (in addition to a field holding a unique identifier) a field holding the street address, a field holding the city, a field holding the state code, and a field holding the zipcode. Β Choose appropriate types for each field.
For non-database languages, show how you would open a connection to a database (your choice of which) and create an address table in it. You should follow the existing models here for how you would structure the table.
| #ooRexx | ooRexx | /* REXX ***************************************************************
* 17.05.2013 Walter Pachl translated from REXX version 2
* nice try? improvements are welcome as I am rather unexperienced
* 18.05.2013 the array may contain a variety of objects!
**********************************************************************/
alist=.array~new
alist[1]=.addr~new('Boston','MA','51 Franklin Street',,'FSF Inc.',,
'02110-1301')
alist[2]='not an address at all'
alist[3]=.addr~new('Washington','DC','The Oval Office',,
'1600 Pennsylvania Avenue NW','The White House',20500)
Do i=1 To alist~items
a=alist[i]
If a~isinstanceof(.addr) Then
a~show
End
Β
::class addr
Β ::attribute city
Β ::attribute state
Β ::attribute addr
Β ::attribute addr2
Β ::attribute name
Β ::attribute zip
Β
::method init
Parse Arg self~city,,
self~state,,
self~addr,,
self~addr2,,
self~name,,
self~zip
Β
::method show
Say ' name -->' self~name
Say ' addr -->' self~addr
If self~addr2<>'' Then Say ' addr2 -->' self~addr2
Say ' city -->' self~city
Say ' state -->' self~state
Say ' zip -->' self~zip
Say copies('-',40) |
http://rosettacode.org/wiki/Table_creation/Postal_addresses | Table creation/Postal addresses | Task
Create a table to store addresses.
You may assume that all the addresses to be stored will be located in the USA. Β As such, you will need (in addition to a field holding a unique identifier) a field holding the street address, a field holding the city, a field holding the state code, and a field holding the zipcode. Β Choose appropriate types for each field.
For non-database languages, show how you would open a connection to a database (your choice of which) and create an address table in it. You should follow the existing models here for how you would structure the table.
| #Oracle | Oracle | CREATE SEQUENCE seq_address_pk START BY 100 INCREMENT BY 1
/
CREATE TABLE address (
addrID NUMBER DEFAULT seq_address_pk.NEXTVAL,
street VARCHAR2( 50 ) NOT NULL,
city VARCHAR2( 25 ) NOT NULL,
state VARCHAR2( 2 ) NOT NULL,
zip VARCHAR2( 20 ) NOT NULL,
CONSTRAINT address_pk1 PRIMARY KEY ( addrID )
)
/ |
http://rosettacode.org/wiki/Sutherland-Hodgman_polygon_clipping | Sutherland-Hodgman polygon clipping | The Β Sutherland-Hodgman clipping algorithm Β finds the polygon that is the intersection between an arbitrary polygon (the βsubject polygonβ) and a convex polygon (the βclip polygonβ).
It is used in computer graphics (especially 2D graphics) to reduce the complexity of a scene being displayed by eliminating parts of a polygon that do not need to be displayed.
Task
Take the closed polygon defined by the points:
[
(
50
,
150
)
,
(
200
,
50
)
,
(
350
,
150
)
,
(
350
,
300
)
,
(
250
,
300
)
,
(
200
,
250
)
,
(
150
,
350
)
,
(
100
,
250
)
,
(
100
,
200
)
]
{\displaystyle [(50,150),(200,50),(350,150),(350,300),(250,300),(200,250),(150,350),(100,250),(100,200)]}
and clip it by the rectangle defined by the points:
[
(
100
,
100
)
,
(
300
,
100
)
,
(
300
,
300
)
,
(
100
,
300
)
]
{\displaystyle [(100,100),(300,100),(300,300),(100,300)]}
Print the sequence of points that define the resulting clipped polygon.
Extra credit
Display all three polygons on a graphical surface, using a different color for each polygon and filling the resulting polygon.
(When displaying you may use either a north-west or a south-west origin, whichever is more convenient for your display mechanism.)
| #Ada | Ada | with Ada.Containers.Doubly_Linked_Lists;
with Ada.Text_IO;
Β
procedure Main is
package FIO is new Ada.Text_IO.Float_IO (Float);
Β
type Point is record
X, YΒ : Float;
end record;
Β
function "-" (Left, RightΒ : Point) return Point is
begin
return (Left.X - Right.X, Left.Y - Right.Y);
end "-";
Β
type Edge is array (1 .. 2) of Point;
Β
package Point_Lists is new Ada.Containers.Doubly_Linked_Lists
(Element_Type => Point);
use type Point_Lists.List;
subtype Polygon is Point_Lists.List;
Β
function Inside (PΒ : Point; EΒ : Edge) return Boolean is
begin
return (E (2).X - E (1).X) * (P.Y - E (1).Y) >
(E (2).Y - E (1).Y) * (P.X - E (1).X);
end Inside;
Β
function Intersecton (P1, P2Β : Point; EΒ : Edge) return Point is
DEΒ : PointΒ := E (1) - E (2);
DPΒ : PointΒ := P1 - P2;
N1Β : FloatΒ := E (1).X * E (2).Y - E (1).Y * E (2).X;
N2Β : FloatΒ := P1.X * P2.Y - P1.Y * P2.X;
N3Β : FloatΒ := 1.0 / (DE.X * DP.Y - DE.Y * DP.X);
begin
return ((N1 * DP.X - N2 * DE.X) * N3, (N1 * DP.Y - N2 * DE.Y) * N3);
end Intersecton;
Β
function Clip (P, CΒ : Polygon) return Polygon is
use Point_Lists;
A, B, S, EΒ : Cursor;
Inputlist Β : List;
OutputlistΒ : ListΒ := P;
AB Β : Edge;
begin
AΒ := C.First;
BΒ := C.Last;
while A /= No_Element loop
AB Β := (Element (B), Element (A));
InputlistΒ := Outputlist;
Outputlist.Clear;
SΒ := Inputlist.Last;
EΒ := Inputlist.First;
while E /= No_Element loop
if Inside (Element (E), AB) then
if not Inside (Element (S), AB) then
Outputlist.Append
(Intersecton (Element (S), Element (E), AB));
end if;
Outputlist.Append (Element (E));
elsif Inside (Element (S), AB) then
Outputlist.Append
(Intersecton (Element (S), Element (E), AB));
end if;
SΒ := E;
EΒ := Next (E);
end loop;
BΒ := A;
AΒ := Next (A);
end loop;
return Outputlist;
end Clip;
Β
procedure Print (PΒ : Polygon) is
use Point_Lists;
CΒ : CursorΒ := P.First;
begin
Ada.Text_IO.Put_Line ("{");
while C /= No_Element loop
Ada.Text_IO.Put (" (");
FIO.Put (Element (C).X, Exp => 0);
Ada.Text_IO.Put (',');
FIO.Put (Element (C).Y, Exp => 0);
Ada.Text_IO.Put (')');
CΒ := Next (C);
if C /= No_Element then
Ada.Text_IO.Put (',');
end if;
Ada.Text_IO.New_Line;
end loop;
Ada.Text_IO.Put_Line ("}");
end Print;
Β
Source Β : Polygon;
ClipperΒ : Polygon;
Result Β : Polygon;
begin
Source.Append ((50.0, 150.0));
Source.Append ((200.0, 50.0));
Source.Append ((350.0, 150.0));
Source.Append ((350.0, 300.0));
Source.Append ((250.0, 300.0));
Source.Append ((200.0, 250.0));
Source.Append ((150.0, 350.0));
Source.Append ((100.0, 250.0));
Source.Append ((100.0, 200.0));
Clipper.Append ((100.0, 100.0));
Clipper.Append ((300.0, 100.0));
Clipper.Append ((300.0, 300.0));
Clipper.Append ((100.0, 300.0));
ResultΒ := Clip (Source, Clipper);
Print (Result);
end Main; |
http://rosettacode.org/wiki/Symmetric_difference | Symmetric difference | Task
Given two sets A and B, compute
(
A
β
B
)
βͺ
(
B
β
A
)
.
{\displaystyle (A\setminus B)\cup (B\setminus A).}
That is, enumerate the items that are in A or B but not both. This set is called the symmetric difference of A and B.
In other words:
(
A
βͺ
B
)
β
(
A
β©
B
)
{\displaystyle (A\cup B)\setminus (A\cap B)}
(the set of items that are in at least one of A or B minus the set of items that are in both A and B).
Optionally, give the individual differences (
A
β
B
{\displaystyle A\setminus B}
and
B
β
A
{\displaystyle B\setminus A}
) as well.
Test cases
A = {John, Bob, Mary, Serena}
B = {Jim, Mary, John, Bob}
Notes
If your code uses lists of items to represent sets then ensure duplicate items in lists are correctly handled. For example two lists representing sets of a = ["John", "Serena", "Bob", "Mary", "Serena"] and b = ["Jim", "Mary", "John", "Jim", "Bob"] should produce the result of just two strings: ["Serena", "Jim"], in any order.
In the mathematical notation above A \ B gives the set of items in A that are not in B; A βͺ B gives the set of items in both A and B, (their union); and A β© B gives the set of items that are in both A and B (their intersection).
| #Action.21 | Action! | SET EndProg=* |
http://rosettacode.org/wiki/Symmetric_difference | Symmetric difference | Task
Given two sets A and B, compute
(
A
β
B
)
βͺ
(
B
β
A
)
.
{\displaystyle (A\setminus B)\cup (B\setminus A).}
That is, enumerate the items that are in A or B but not both. This set is called the symmetric difference of A and B.
In other words:
(
A
βͺ
B
)
β
(
A
β©
B
)
{\displaystyle (A\cup B)\setminus (A\cap B)}
(the set of items that are in at least one of A or B minus the set of items that are in both A and B).
Optionally, give the individual differences (
A
β
B
{\displaystyle A\setminus B}
and
B
β
A
{\displaystyle B\setminus A}
) as well.
Test cases
A = {John, Bob, Mary, Serena}
B = {Jim, Mary, John, Bob}
Notes
If your code uses lists of items to represent sets then ensure duplicate items in lists are correctly handled. For example two lists representing sets of a = ["John", "Serena", "Bob", "Mary", "Serena"] and b = ["Jim", "Mary", "John", "Jim", "Bob"] should produce the result of just two strings: ["Serena", "Jim"], in any order.
In the mathematical notation above A \ B gives the set of items in A that are not in B; A βͺ B gives the set of items in both A and B, (their union); and A β© B gives the set of items that are in both A and B (their intersection).
| #Ada | Ada | with Ada.Text_IO; use Ada.Text_IO;
Β
procedure Test_XOR is
type Person is (John, Bob, Mary, Serena, Jim);
type Group is array (Person) of Boolean;
procedure Put (SetΒ : Group) is
FirstΒ : BooleanΒ := True;
begin
for I in Set'Range loop
if Set (I) then
if First then
FirstΒ := False;
else
Put (',');
end if;
Put (Person'Image (I));
end if;
end loop;
end Put;
Β
AΒ : GroupΒ := (John | Bob | Mary | Serena => True, others => False);
BΒ : GroupΒ := (Jim | Mary | John | Bob => True, others => False);
begin
Put ("A xor B = "); Put (A xor B); New_Line;
Put ("A - B = "); Put (A and not B); New_Line;
Put ("B - A = "); Put (B and not A); New_Line;
end Test_XOR; |
http://rosettacode.org/wiki/Super-d_numbers | Super-d numbers | A super-d number is a positive, decimal (base ten) integer Β n Β such that Β d Γ nd Β has at least Β d Β consecutive digits Β d Β where
2 β€ d β€ 9
For instance, 753 is a super-3 number because 3 Γ 7533 = 1280873331.
Super-d Β numbers are also shown on Β MathWorldβ’ Β as Β super-d Β or Β super-d.
Task
Write a function/procedure/routine to find super-d numbers.
For Β d=2 Β through Β d=6, Β use the routine to show the first Β 10 Β super-d numbers.
Extra credit
Show the first Β 10 Β super-7, super-8, and/or super-9 numbers Β (optional).
See also
Β Wolfram MathWorld - Super-d Number.
Β OEIS: A014569 - Super-3 Numbers.
| #C.23 | C# | using System;
using System.Collections.Generic;
using BI = System.Numerics.BigInteger;
using lbi = System.Collections.Generic.List<System.Numerics.BigInteger[]>;
using static System.Console;
Β
class Program {
Β
// provides 320 bits (90 decimal digits)
struct LI { public UInt64 lo, ml, mh, hi, tp; }
Β
const UInt64 Lm = 1_000_000_000_000_000_000UL;
const string Fm = "D18";
Β
static void inc(ref LI d, LI s) { // d += s
d.lo += s.lo; while (d.lo >= Lm) { d.ml++; d.lo -= Lm; }
d.ml += s.ml; while (d.ml >= Lm) { d.mh++; d.ml -= Lm; }
d.mh += s.mh; while (d.mh >= Lm) { d.hi++; d.mh -= Lm; }
d.hi += s.hi; while (d.hi >= Lm) { d.tp++; d.hi -= Lm; }
d.tp += s.tp;
}
Β
static void set(ref LI d, UInt64 s) { // d = s
d.lo = s; d.ml = d.mh = d.hi = d.tp = 0;
}
Β
const int ls = 10;
Β
static lbi co = new lbi { new BI[] { 0 } }; // for BigInteger addition
static List<LI[]> Co = new List<LI[]> { new LI[1] }; // for UInt64 addition
Β
static Int64 ipow(Int64 bas, Int64 exp) { // Math.Pow()
Int64 res = 1; while (exp != 0) {
if ((exp & 1) != 0) res *= bas; exp >>= 1; bas *= bas;
}
return res;
}
Β
// finishes up, shows performance value
static void fin() { WriteLine("{0}s", (DateTime.Now - st).TotalSeconds.ToString().Substring(0, 5)); }
Β
static void funM(int d) { // straightforward BigInteger method, medium performance
string s = new string(d.ToString()[0], d); Write("{0}: ", d);
for (int i = 0, c = 0; c < ls; i++)
if ((BI.Pow((BI)i, d) * d).ToString().Contains(s))
Write("{0} ", i, ++c);
fin();
}
Β
static void funS(int d) { // BigInteger "mostly adding" method, low performance
BI[] m = co[d];
string s = new string(d.ToString()[0], d); Write("{0}: ", d);
for (int i = 0, c = 0; c < ls; i++) {
if ((d * m[0]).ToString().Contains(s))
Write("{0} ", i, ++c);
for (int j = d, k = d - 1; j > 0; j = k--) m[k] += m[j];
}
fin();
}
Β
static string scale(uint s, ref LI x) { // performs a small multiply and returns a string value
ulong Lo = x.lo * s, Ml = x.ml * s, Mh = x.mh * s, Hi = x.hi * s, Tp = x.tp * s;
while (Lo >= Lm) { Lo -= Lm; Ml++; }
while (Ml >= Lm) { Ml -= Lm; Mh++; }
while (Mh >= Lm) { Mh -= Lm; Hi++; }
while (Hi >= Lm) { Hi -= Lm; Tp++; }
if (Tp > 0) return Tp.ToString() + Hi.ToString(Fm) + Mh.ToString(Fm) + Ml.ToString(Fm) + Lo.ToString(Fm);
if (Hi > 0) return Hi.ToString() + Mh.ToString(Fm) + Ml.ToString(Fm) + Lo.ToString(Fm);
if (Mh > 0) return Mh.ToString() + Ml.ToString(Fm) + Lo.ToString(Fm);
if (Ml > 0) return Ml.ToString() + Lo.ToString(Fm);
return Lo.ToString();
}
Β
static void funF(int d) { // structure of UInt64 method, high performance
LI[] m = Co[d];
string s = new string(d.ToString()[0], d); Write("{0}: ", d);
for (int i = d, c = 0; c < ls; i++) {
if (scale((uint)d, ref m[0]).Contains(s))
Write("{0} ", i, ++c);
for (int j = d, k = d - 1; j > 0; j = k--)
inc(ref m[k], m[j]);
}
fin();
}
Β
static void init() { // initializes co and Co
for (int v = 1; v < 10; v++) {
BI[] res = new BI[v + 1];
long[] f = new long[v + 1], l = new long[v + 1];
for (int j = 0; j <= v; j++) {
if (j == v) {
LI[] t = new LI[v + 1];
for (int y = 0; y <= v; y++) set(ref t[y], (UInt64)f[y]);
Co.Add(t);
}
res[j] = f[j];
l[0] = f[0]; f[0] = ipow(j + 1, v);
for (int a = 0, b = 1; b <= v; a = b++) {
l[b] = f[b]; f[b] = f[a] - l[a];
}
}
for (int z = res.Length - 2; z > 0; z -= 2) res[z] *= -1;
co.Add(res);
}
}
Β
static DateTime st;
Β
static void doOne(string title, int top, Action<int> func) {
WriteLine('\n' + title); st = DateTime.Now;
for (int i = 2; i <= top; i++) func(i);
}
Β
static void Main(string[] args)
{
init(); const int top = 9;
doOne("BigInteger mostly addition:", top, funS);
doOne("BigInteger.Pow():", top, funM);
doOne("UInt64 structure mostly addition:", top, funF);
}
} |
http://rosettacode.org/wiki/Take_notes_on_the_command_line | Take notes on the command line | Take notes on the command line is part of Short Circuit's Console Program Basics selection.
Invoking NOTES without commandline arguments displays the current contents of the local NOTES.TXT if it exists.
If NOTES has arguments, the current date and time are appended to the local NOTES.TXT followed by a newline.
Then all the arguments, joined with spaces, prepended with a tab, and appended with a trailing newline, are written to NOTES.TXT.
If NOTES.TXT doesn't already exist in the current directory then a new NOTES.TXT file should be created.
| #COBOL | COBOL | IDENTIFICATION DIVISION.
PROGRAM-ID. NOTES.
Β
ENVIRONMENT DIVISION.
INPUT-OUTPUT SECTION.
FILE-CONTROL.
SELECT OPTIONAL notes ASSIGN TO "NOTES.TXT"
ORGANIZATION LINE SEQUENTIAL
FILE STATUS note-status.
Β
DATA DIVISION.
FILE SECTION.
FD notes.
01 note-record PIC X(256).
Β
LOCAL-STORAGE SECTION.
01 note-status PIC 99.
88 notes-ok VALUE 0 THRU 9.
Β
01 date-now.
03 current-year PIC 9(4).
03 current-month PIC 99.
03 current-day PIC 99.
Β
01 time-now.
03 current-hour PIC 99.
03 current-min PIC 99.
03 current-sec PIC 99.
Β
01 args PIC X(256).
Β
PROCEDURE DIVISION.
DECLARATIVES.
note-error SECTION.
USE AFTER STANDARD ERROR PROCEDURE ON notes.
Β
DISPLAY "Error using NOTES.TXT. Error code: " note-status
.
END DECLARATIVES.
Β
main.
ACCEPT args FROM COMMAND-LINE
Β
* *> If there are no args, display contents of NOTES.TXT.
IF args = SPACES
OPEN INPUT notes
Β
PERFORM FOREVER
* *> READ has no syntax highlighting, but END-READ does.
* *> Go figure.
READ notes
AT END
EXIT PERFORM
Β
NOT AT END
DISPLAY FUNCTION TRIM(note-record)
END-READ
END-PERFORM
ELSE
OPEN EXTEND notes
Β
* *> Write date and time to file.
ACCEPT date-now FROM DATE YYYYMMDD
ACCEPT time-now FROM TIME
STRING current-year "-" current-month "-" current-day
" " current-hour ":" current-min ":" current-sec
INTO note-record
WRITE note-record
Β
* *> Write arguments to file as they were passed.
STRING X"09", args INTO note-record
WRITE note-record
END-IF
Β
CLOSE notes
Β
GOBACK
. |
http://rosettacode.org/wiki/Superellipse | Superellipse | A superellipse is a geometric figure defined as the set of all points (x, y) with
|
x
a
|
n
+
|
y
b
|
n
=
1
,
{\displaystyle \left|{\frac {x}{a}}\right|^{n}\!+\left|{\frac {y}{b}}\right|^{n}\!=1,}
where n, a, and b are positive numbers.
Task
Draw a superellipse with n = 2.5, and a = b = 200
| #Action.21 | Action! | INCLUDE "D2:REAL.ACT"Β ;from the Action! Tool Kit
Β
PROC Superellipse(INT x0 BYTE y0 REAL POINTER n BYTE a)
INT ARRAY f(100)
REAL ar,xr,tmp1,tmp2,tmp3,one,invn
INT x
Β
IntToReal(1,one)
RealDiv(one,n,invn)Β ;1/n
IntToReal(a,ar)
Power(ar,n,tmp1)Β ;a^n
Β
Plot(x0,y0-a)
FOR x=0 TO a
DO
IntToReal(x,xr)
Power(xr,n,tmp2)Β ;x^n
RealSub(tmp1,tmp2,tmp3)Β ;a^n-x^n
Power(tmp3,invn,tmp2)Β ;(a^n-x^n)^(1/n)
f(x)=RealToInt(tmp2)
DrawTo(x0+x,y0-f(x))
OD
Β
x=a
WHILE x>=0
DO
DrawTo(x0+x,y0+f(x))
x==-1
OD
Β
FOR x=0 TO a
DO
DrawTo(x0-x,y0+f(x))
OD
Β
x=a
WHILE x>=0
DO
DrawTo(x0-x,y0-f(x))
x==-1
OD
RETURN
Β
PROC Main()
BYTE CH=$02FC,COLOR1=$02C5,COLOR2=$02C6
REAL n
Β
Graphics(8+16)
Color=1
COLOR1=$0C
COLOR2=$02
Β
ValR("2.5",n)
Superellipse(160,96,n,80)
Β
DO UNTIL CH#$FF OD
CH=$FF
RETURN |
http://rosettacode.org/wiki/Sylvester%27s_sequence | Sylvester's sequence |
This page uses content from Wikipedia. The original article was at Sylvester's sequence. 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)
In number theory, Sylvester's sequence is an integer sequence in which each term of the sequence is the product of the previous terms, plus one.
Its values grow doubly exponentially, and the sum of its reciprocals forms a series of unit fractions that converges to 1 more rapidly than any other series of unit fractions with the same number of terms.
Further, the sum of the first k terms of the infinite series of reciprocals provides the closest possible underestimate of 1 by any k-term Egyptian fraction.
Task
Write a routine (function, procedure, generator, whatever) to calculate Sylvester's sequence.
Use that routine to show the values of the first 10 elements in the sequence.
Show the sum of the reciprocals of the first 10 elements on the sequence, ideally as an exact fraction.
Related tasks
Egyptian fractions
Harmonic series
See also
OEIS A000058 - Sylvester's sequence
| #AWK | AWK | Β
# syntax: GAWK --bignum -f SYLVESTERS_SEQUENCE.AWK
BEGIN {
start = 1
stop = 10
for (i=start; i<=stop; i++) {
sylvester = (i == 1) ? 2 : sylvester*sylvester-sylvester+1
printf("%2d:Β %d\n",i,sylvester)
sum += 1 / sylvester
}
printf("\nSylvester sequenceΒ %d-%d: sum of reciprocalsΒ %30.28f\n",start,stop,sum)
exit(0)
}
Β |
http://rosettacode.org/wiki/Sylvester%27s_sequence | Sylvester's sequence |
This page uses content from Wikipedia. The original article was at Sylvester's sequence. 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)
In number theory, Sylvester's sequence is an integer sequence in which each term of the sequence is the product of the previous terms, plus one.
Its values grow doubly exponentially, and the sum of its reciprocals forms a series of unit fractions that converges to 1 more rapidly than any other series of unit fractions with the same number of terms.
Further, the sum of the first k terms of the infinite series of reciprocals provides the closest possible underestimate of 1 by any k-term Egyptian fraction.
Task
Write a routine (function, procedure, generator, whatever) to calculate Sylvester's sequence.
Use that routine to show the values of the first 10 elements in the sequence.
Show the sum of the reciprocals of the first 10 elements on the sequence, ideally as an exact fraction.
Related tasks
Egyptian fractions
Harmonic series
See also
OEIS A000058 - Sylvester's sequence
| #BASIC | BASIC | Β
PRINT "10 primeros tΓ©rminos de la sucesiΓ³n de sylvester:"
PRINT
Β
LET suma = 0
FOR i = 1 TO 10
IF i = 1 THEN
LET sylvester = 2
ELSE
LET sylvester = sylvester*sylvester-sylvester+1
END IF
PRINT i; ": "; sylvester
LET suma = suma + 1 / sylvester
NEXT i
Β
PRINT
PRINT "suma de sus recΓprocos: "; suma
END
Β |
http://rosettacode.org/wiki/Sylvester%27s_sequence | Sylvester's sequence |
This page uses content from Wikipedia. The original article was at Sylvester's sequence. 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)
In number theory, Sylvester's sequence is an integer sequence in which each term of the sequence is the product of the previous terms, plus one.
Its values grow doubly exponentially, and the sum of its reciprocals forms a series of unit fractions that converges to 1 more rapidly than any other series of unit fractions with the same number of terms.
Further, the sum of the first k terms of the infinite series of reciprocals provides the closest possible underestimate of 1 by any k-term Egyptian fraction.
Task
Write a routine (function, procedure, generator, whatever) to calculate Sylvester's sequence.
Use that routine to show the values of the first 10 elements in the sequence.
Show the sum of the reciprocals of the first 10 elements on the sequence, ideally as an exact fraction.
Related tasks
Egyptian fractions
Harmonic series
See also
OEIS A000058 - Sylvester's sequence
| #C.2B.2B | C++ | #include <iomanip>
#include <iostream>
#include <boost/rational.hpp>
#include <boost/multiprecision/cpp_int.hpp>
Β
using integer = boost::multiprecision::cpp_int;
using rational = boost::rational<integer>;
Β
integer sylvester_next(const integer& n) {
return n * n - n + 1;
}
Β
int main() {
std::cout << "First 10 elements in Sylvester's sequence:\n";
integer term = 2;
rational sum = 0;
for (int i = 1; i <= 10; ++i) {
std::cout << std::setw(2) << i << ": " << term << '\n';
sum += rational(1, term);
term = sylvester_next(term);
}
std::cout << "Sum of reciprocals: " << sum << '\n';
} |
http://rosettacode.org/wiki/Taxicab_numbers | Taxicab numbers |
A Β taxicab number Β (the definition that is being used here) Β is a positive integer that can be expressed as the sum of two positive cubes in more than one way.
The first taxicab number is Β 1729, Β which is:
13 Β + Β 123 Β Β Β and also
93 Β + Β 103.
Taxicab numbers are also known as:
Β taxi numbers
Β taxi-cab numbers
Β taxi cab numbers
Β Hardy-Ramanujan numbers
Task
Compute and display the lowest 25 taxicab numbers (in numeric order, and in a human-readable format).
For each of the taxicab numbers, show the number as well as it's constituent cubes.
Extra credit
Show the 2,000th taxicab number, and a half dozen more
See also
A001235: taxicab numbers on The On-Line Encyclopedia of Integer Sequences.
Hardy-Ramanujan Number on MathWorld.
taxicab number on MathWorld.
taxicab number on Wikipedia Β (includes the story on how taxi-cab numbers came to be called).
| #Go | Go | package main
Β
import (
"container/heap"
"fmt"
"strings"
)
Β
type CubeSum struct {
x, y uint16
value uint64
}
Β
func (c *CubeSum) fixvalue() { c.value = cubes[c.x] + cubes[c.y] }
Β
type CubeSumHeap []*CubeSum
Β
func (h CubeSumHeap) Len() int { return len(h) }
func (h CubeSumHeap) Less(i, j int) bool { return h[i].value < h[j].value }
func (h CubeSumHeap) Swap(i, j int) { h[i], h[j] = h[j], h[i] }
func (h *CubeSumHeap) Push(x interface{}) { (*h) = append(*h, x.(*CubeSum)) }
func (h *CubeSumHeap) Pop() interface{} {
x := (*h)[len(*h)-1]
*h = (*h)[:len(*h)-1]
return x
}
Β
type TaxicabGen struct {
n int
h CubeSumHeap
}
Β
var cubes []uint64 // cubes[i] == i*i*i
func cubesExtend(i int) {
for n := uint64(len(cubes)); n <= uint64(i); n++ {
cubes = append(cubes, n*n*n)
}
}
Β
func (g *TaxicabGen) min() CubeSum {
for len(g.h) == 0 || g.h[0].value > cubes[g.n] {
g.n++
cubesExtend(g.n)
heap.Push(&g.h, &CubeSum{uint16(g.n), 1, cubes[g.n] + 1})
}
// Note, we use g.h[0] to "peek" at the min heap entry.
c := *(g.h[0])
if c.y+1 <= c.x {
// Instead of Pop and Push we modify in place and fix.
g.h[0].y++
g.h[0].fixvalue()
heap.Fix(&g.h, 0)
} else {
heap.Pop(&g.h)
}
return c
}
Β
// Originally this was just: type Taxicab [2]CubeSum
// and we always returned two sums. Now we return all the sums.
type Taxicab []CubeSum
Β
func (t Taxicab) String() string {
var b strings.Builder
fmt.Fprintf(&b, "%12d", t[0].value)
for _, p := range t {
fmt.Fprintf(&b, " =%5dΒ³ +%5dΒ³", p.x, p.y)
}
return b.String()
}
Β
func (g *TaxicabGen) Next() Taxicab {
a, b := g.min(), g.min()
for a.value != b.value {
a, b = b, g.min()
}
//return Taxicab{a,b}
Β
// Originally this just returned Taxicab{a,b} and we didn't look
// further into the heap. Since we start by looking at the next
// pair, that is okay until the first Taxicab number with four
// ways of expressing the cube, which doesn't happen until the
// 97,235th Taxicab:
// 6963472309248 = 16630Β³ + 13322Β³ = 18072Β³ + 10200Β³
// = 18948Β³ + 5436Β³ = 19083Β³ + 2421Β³
// Now we return all ways so we need to peek into the heap.
t := Taxicab{a, b}
for g.h[0].value == b.value {
t = append(t, g.min())
}
return t
}
Β
func main() {
const (
low = 25
mid = 2e3
high = 4e4
)
var tg TaxicabGen
firstn := 3 // To show the first triple, quadruple, etc
for i := 1; i <= high+6; i++ {
t := tg.Next()
switch {
case len(t) >= firstn:
firstn++
fallthrough
case i <= low || (mid <= i && i <= mid+6) || i >= high:
//fmt.Printf("h:%-4d ", len(tg.h))
fmt.Printf("%5d:Β %v\n", i, t)
}
}
} |
http://rosettacode.org/wiki/Superpermutation_minimisation | Superpermutation minimisation | A superpermutation of N different characters is a string consisting of an arrangement of multiple copies of those N different characters in which every permutation of those characters can be found as a substring.
For example, representing the characters as A..Z, using N=2 we choose to use the first two characters 'AB'.
The permutations of 'AB' are the two, (i.e. two-factorial), strings: 'AB' and 'BA'.
A too obvious method of generating a superpermutation is to just join all the permutations together forming 'ABBA'.
A little thought will produce the shorter (in fact the shortest) superpermutation of 'ABA' - it contains 'AB' at the beginning and contains 'BA' from the middle to the end.
The "too obvious" method of creation generates a string of length N!*N. Using this as a yardstick, the task is to investigate other methods of generating superpermutations of N from 1-to-7 characters, that never generate larger superpermutations.
Show descriptions and comparisons of algorithms used here, and select the "Best" algorithm as being the one generating shorter superpermutations.
The problem of generating the shortest superpermutation for each N might be NP complete, although the minimal strings for small values of N have been found by brute -force searches.
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
Reference
The Minimal Superpermutation Problem. by Nathaniel Johnston.
oeis A180632 gives 0-5 as 0, 1, 3, 9, 33, 153. 6 is thought to be 872.
Superpermutations - Numberphile. A video
Superpermutations: the maths problem solved by 4chan - Standupmaths. A video of recent (2018) mathematical progress.
New Superpermutations Discovered! Standupmaths & Numberphile.
| #D | D | import std.stdio, std.ascii, std.algorithm, core.memory, permutations2;
Β
/** Uses greedy algorithm of adding another char (or two, or three, ...)
until an unseen perm is formed in the last n chars. */
string superpermutation(in uint n) nothrow
in {
assert(n > 0 && n < uppercase.length);
} out(result) {
// It's a superpermutation.
assert(uppercase[0 .. n].dup.permutations.all!(p => result.canFind(p)));
} body {
string result = uppercase[0 .. n];
Β
bool[const char[]] toFind;
GC.disable;
foreach (const perm; result.dup.permutations)
toFind[perm] = true;
GC.enable;
toFind.remove(result);
Β
auto trialPerm = new char[n];
auto auxAdd = new char[n];
Β
while (toFind.length) {
MIDDLE: foreach (immutable skip; 1 .. n) {
auxAdd[0 .. skip] = result[$ - n .. $ - n + skip];
foreach (const trialAdd; auxAdd[0 .. skip].permutations!false) {
trialPerm[0 .. n - skip] = result[$ + skip - n .. $];
trialPerm[n - skip .. $] = trialAdd[];
if (trialPerm in toFind) {
result ~= trialAdd;
toFind.remove(trialPerm);
break MIDDLE;
}
}
}
}
Β
return result;
}
Β
void main() {
foreach (immutable n; 1 .. 8)
n.superpermutation.length.writeln;
} |
http://rosettacode.org/wiki/Tau_number | Tau number | A Tau number is a positive integer divisible by the count of its positive divisors.
Task
Show the first Β 100 Β Tau numbers.
The numbers shall be generated during run-time (i.e. the code may not contain string literals, sets/arrays of integers, or alike).
Related task
Β Tau function
| #Nim | Nim | import math, strutils
Β
func divcount(n: Natural): Natural =
for i in 1..sqrt(n.toFloat).int:
if n mod i == 0:
inc result
if n div iΒ != i: inc result
Β
var count = 0
var n = 1
var tauNumbers: seq[Natural]
while true:
if n mod divcount(n) == 0:
tauNumbers.add n
inc count
if count == 100: break
inc n
Β
echo "First 100 tau numbers:"
for i, n in tauNumbers:
stdout.write ($n).align(5)
if i mod 20 == 19: echo() |
http://rosettacode.org/wiki/Tau_number | Tau number | A Tau number is a positive integer divisible by the count of its positive divisors.
Task
Show the first Β 100 Β Tau numbers.
The numbers shall be generated during run-time (i.e. the code may not contain string literals, sets/arrays of integers, or alike).
Related task
Β Tau function
| #Pascal | Pascal | program Tau_number;
{$IFDEF Windows} {$APPTYPE CONSOLE} {$ENDIF}
function CountDivisors(n: NativeUint): integer;
//tau function
var
q, p, cnt, divcnt: NativeUint;
begin
divCnt := 1;
if n > 1 then
begin
cnt := 1;
while not (Odd(n)) do
begin
n := n shr 1;
divCnt+= cnt;
end;
p := 3;
while p * p <= n do
begin
cnt := divCnt;
q := n div p;
while q * p = n do
begin
n := q;
q := n div p;
divCnt+= cnt;
end;
Inc(p, 2);
end;
if n <> 1 then
divCnt += divCnt;
end;
CountDivisors := divCnt;
end;
Β
const
UPPERLIMIT = 100;
var
cnt,n: NativeUint;
begin
cnt := 0;
n := 1;
repeat
if n MOD CountDivisors(n) = 0 then
Begin
write(n:5);
inc(cnt);
if cnt Mod 10 = 0 then
writeln;
end;
inc(n);
until cnt >= UPPERLIMIT;
writeln;
{$Ifdef Windows}readln;{$ENDIF}
end. |
http://rosettacode.org/wiki/Tarjan | Tarjan |
This page uses content from Wikipedia. The original article was at Graph. 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)
Tarjan's algorithm is an algorithm in graph theory for finding the strongly connected components of a graph.
It runs in linear time, matching the time bound for alternative methods including Kosaraju's algorithm and the path-based strong component algorithm.
Tarjan's Algorithm is named for its discoverer, Robert Tarjan.
References
The article on Wikipedia.
| #Wren | Wren | import "/seq" for Stack
import "/dynamic" for Tuple
Β
class Node {
construct new(n) {
_n = n
_index = -1 // -1 signifies undefined
_lowLink = -1
_onStack = false
}
Β
n { _n }
index { _index }
index=(v) { _index = v }
lowLink { _lowLink }
lowLink=(v) { _lowLink = v }
onStack { _onStack }
onStack=(v) { _onStack = v }
Β
toString { _n.toString }
}
Β
var DirectedGraph = Tuple.create("DirectedGraph", ["vs", "es"])
Β
var tarjan = Fn.new { |g|
var sccs = []
var index = 0
var s = Stack.new()
Β
var strongConnect // recursive closure
strongConnect = Fn.new { |v|
// Set the depth index for v to the smallest unused index
v.index = index
v.lowLink = index
index = index + 1
s.push(v)
v.onStack = true
Β
// consider successors of v
for (w in g.es[v.n]) {
if (w.index < 0) {
// Successor w has not yet been visited; recurse on it
strongConnect.call(w)
v.lowLink = v.lowLink.min(w.lowLink)
} else if (w.onStack) {
// Successor w is in stack s and hence in the current SCC
v.lowLink = v.lowLink.min(w.index)
}
}
Β
// If v is a root node, pop the stack and generate an SCC
if (v.lowLink == v.index) {
var scc = []
while (true) {
var w = s.pop()
w.onStack = false
scc.add(w)
if (w == v) break
}
sccs.add(scc)
}
}
Β
for (v in g.vs) if (v.index < 0) strongConnect.call(v)
return sccs
}
Β
var vs = (0..7).map { |i| Node.new(i) }.toList
var es = {
0: [vs[1]],
2: [vs[0]],
5: [vs[2], vs[6]],
6: [vs[5]],
1: [vs[2]],
3: [vs[1], vs[2], vs[4]],
4: [vs[5], vs[3]],
7: [vs[4], vs[7], vs[6]]
}
var g = DirectedGraph.new(vs, es)
var sccs = tarjan.call(g)
System.print(sccs.join("\n")) |
http://rosettacode.org/wiki/Teacup_rim_text | Teacup rim text | On a set of coasters we have, there's a picture of a teacup. Β On the rim of the teacup the word Β TEA Β appears a number of times separated by bullet characters Β (β’).
It occurred to me that if the bullet were removed and the words run together, Β you could start at any letter and still end up with a meaningful three-letter word.
So start at the Β T Β and read Β TEA. Β Start at the Β E Β and read Β EAT, Β or start at the Β A Β and read Β ATE.
That got me thinking that maybe there are other words that could be used rather that Β TEA. Β And that's just English. Β What about Italian or Greek or ... um ... Telugu.
For English, we will use the unixdict (now) located at: Β unixdict.txt.
(This will maintain continuity with other Rosetta Code tasks that also use it.)
Task
Search for a set of words that could be printed around the edge of a teacup. Β The words in each set are to be of the same length, that length being greater than two (thus precluding Β AH Β and Β HA, Β for example.)
Having listed a set, for example Β [ate tea eat], Β refrain from displaying permutations of that set, e.g.: Β [eat tea ate] Β etc.
The words should also be made of more than one letter Β (thus precluding Β III Β and Β OOO Β etc.)
The relationship between these words is (using ATE as an example) that the first letter of the first becomes the last letter of the second. Β The first letter of the second becomes the last letter of the third. Β So Β ATE Β becomes Β TEA Β and Β TEA Β becomes Β EAT.
All of the possible permutations, using this particular permutation technique, must be words in the list.
The set you generate for Β ATE Β will never included the word Β ETA Β as that cannot be reached via the first-to-last movement method.
Display one line for each set of teacup rim words.
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
| #Raku | Raku | my %*SUB-MAIN-OPTS = :named-anywhere;
Β
unit sub MAIN ( $dict = 'unixdict.txt', :$min-chars = 3, :$mono = False );
Β
my %words;
$dict.IO.slurp.words.map: { .chars < $min-chars ?? (next) !! %words{.uc.comb.sort.join}.push: .uc };
Β
my @teacups;
my %seen;
Β
for %words.values -> @these {
next if !$mono && @these < 2;
MAYBE: for @these {
my $maybe = $_;
next if %seen{$_};
my @print;
for ^$maybe.chars {
if $maybe β @these {
@print.push: $maybe;
$maybe = $maybe.comb.list.rotate.join;
} else {
@print = ();
next MAYBE
}
}
if @print.elems {
@teacups.push: @print;
%seen{$_}++ for @print;
}
}
}
Β
say .unique.join(", ") for sort @teacups; |
http://rosettacode.org/wiki/Temperature_conversion | Temperature conversion | There are quite a number of temperature scales. For this task we will concentrate on four of the perhaps best-known ones:
Kelvin, Celsius, Fahrenheit, and Rankine.
The Celsius and Kelvin scales have the same magnitude, but different null points.
0 degrees Celsius corresponds to 273.15 kelvin.
0 kelvin is absolute zero.
The Fahrenheit and Rankine scales also have the same magnitude, but different null points.
0 degrees Fahrenheit corresponds to 459.67 degrees Rankine.
0 degrees Rankine is absolute zero.
The Celsius/Kelvin and Fahrenheit/Rankine scales have a ratio of 5Β : 9.
Task
Write code that accepts a value of kelvin, converts it to values of the three other scales, and prints the result.
Example
K 21.00
C -252.15
F -421.87
R 37.80
| #AWK | AWK | # syntax: AWK -f TEMPERATURE_CONVERSION.AWK
BEGIN {
while (1) {
printf("\nKelvin degrees? ")
getline K
if (K ~ /^$/) {
break
}
if (K < 0) {
print("K must be >= 0")
continue
}
printf("K =Β %.2f\n",K)
printf("C =Β %.2f\n",K - 273.15)
printf("F =Β %.2f\n",K * 1.8 - 459.67)
printf("R =Β %.2f\n",K * 1.8)
}
exit(0)
} |
http://rosettacode.org/wiki/Tau_function | Tau function | Given a positive integer, count the number of its positive divisors.
Task
Show the result for the first Β 100 Β positive integers.
Related task
Β Tau number
| #FreeBASIC | FreeBASIC | function numdiv( n as uinteger ) as uinteger
dim as uinteger c = 1
for i as uinteger = 1 to (n+1)\2
if n mod i = 0 then c += 1
next i
if n=1 then c-=1
return c
end function
Β
for i as uinteger = 1 to 100
print numdiv(i),
if i mod 10 = 0 then print
next i |
http://rosettacode.org/wiki/Tau_function | Tau function | Given a positive integer, count the number of its positive divisors.
Task
Show the result for the first Β 100 Β positive integers.
Related task
Β Tau number
| #Go | Go | package main
Β
import "fmt"
Β
func countDivisors(n int) int {
count := 0
i := 1
k := 2
if n%2 == 0 {
k = 1
}
for i*i <= n {
if n%i == 0 {
count++
j := n / i
if j != i {
count++
}
}
i += k
}
return count
}
Β
func main() {
fmt.Println("The tau functions for the first 100 positive integers are:")
for i := 1; i <= 100; i++ {
fmt.Printf("%2d ", countDivisors(i))
if i%20 == 0 {
fmt.Println()
}
}
} |
http://rosettacode.org/wiki/Terminal_control/Clear_the_screen | Terminal control/Clear the screen | Task
Clear the terminal window.
| #Kotlin | Kotlin | // version 1.1.2
Β
fun main(args: Array<String>) {
println("\u001Bc") // Esc + c
} |
http://rosettacode.org/wiki/Terminal_control/Clear_the_screen | Terminal control/Clear the screen | Task
Clear the terminal window.
| #Lasso | Lasso | local(
esc = decode_base64('Gw==')
)
Β
stdout(#esc + '[2J') |
http://rosettacode.org/wiki/Terminal_control/Clear_the_screen | Terminal control/Clear the screen | Task
Clear the terminal window.
| #Logo | Logo | cleartext |
http://rosettacode.org/wiki/Ternary_logic | Ternary logic |
This page uses content from Wikipedia. The original article was at Ternary logic. 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)
In logic, a three-valued logic (also trivalent, ternary, or trinary logic, sometimes abbreviated 3VL) is any of several many-valued logic systems in which there are three truth values indicating true, false and some indeterminate third value.
This is contrasted with the more commonly known bivalent logics (such as classical sentential or boolean logic) which provide only for true and false.
Conceptual form and basic ideas were initially created by Εukasiewicz, Lewis and Sulski.
These were then re-formulated by Grigore Moisil in an axiomatic algebraic form, and also extended to n-valued logics in 1945.
Example Ternary Logic Operators in Truth Tables:
not a
Β¬
True
False
Maybe
Maybe
False
True
a and b
β§
True
Maybe
False
True
True
Maybe
False
Maybe
Maybe
Maybe
False
False
False
False
False
a or b
β¨
True
Maybe
False
True
True
True
True
Maybe
True
Maybe
Maybe
False
True
Maybe
False
if a then b
β
True
Maybe
False
True
True
Maybe
False
Maybe
True
Maybe
Maybe
False
True
True
True
a is equivalent to b
β‘
True
Maybe
False
True
True
Maybe
False
Maybe
Maybe
Maybe
Maybe
False
False
Maybe
True
Task
Define a new type that emulates ternary logic by storing data trits.
Given all the binary logic operators of the original programming language, reimplement these operators for the new Ternary logic type trit.
Generate a sampling of results using trit variables.
Kudos for actually thinking up a test case algorithm where ternary logic is intrinsically useful, optimises the test case algorithm and is preferable to binary logic.
Note: Β Setun Β (Π‘Π΅ΡΡΠ½Ρ) was a Β balanced ternary Β computer developed in 1958 at Β Moscow State University. Β The device was built under the lead of Β Sergei Sobolev Β and Β Nikolay Brusentsov. Β It was the only modern Β ternary computer, Β using three-valued ternary logic
| #Alternative_version | Alternative version | # built-in: true, false and missing
Β
using Printf
Β
const tril = (true, missing, false)
Β
@printf("\n%8s |Β %8s\n", "A", "Β¬A")
for A in tril
@printf("%8s |Β %8s\n", A,Β !A)
end
Β
@printf("\n%8s |Β %8s |Β %8s\n", "A", "B", "A β§ B")
for (A, B) in Iterators.product(tril, tril)
@printf("%8s |Β %8s |Β %8s\n", A, B, A & B)
end
Β
@printf("\n%8s |Β %8s |Β %8s\n", "A", "B", "A β¨ B")
for (A, B) in Iterators.product(tril, tril)
@printf("%8s |Β %8s |Β %8s\n", A, B, A | B)
end
Β
@printf("\n%8s |Β %8s |Β %8s\n", "A", "B", "A β‘ B")
for (A, B) in Iterators.product(tril, tril)
@printf("%8s |Β %8s |Β %8s\n", A, B, A == B)
end
Β
β(A, B) = B |Β !A
Β
@printf("\n%8s |Β %8s |Β %8s\n", "A", "B", "A β B")
for (A, B) in Iterators.product(tril, tril)
@printf("%8s |Β %8s |Β %8s\n", A, B, A β B)
end |
http://rosettacode.org/wiki/Text_processing/1 | Text processing/1 | This task has been flagged for clarification. Code on this page in its current state may be flagged incorrect once this task has been clarified. See this page's Talk page for discussion.
Often data is produced by one program, in the wrong format for later use by another program or person. In these situations another program can be written to parse and transform the original data into a format useful to the other. The term "Data Munging" is often used in programming circles for this task.
A request on the comp.lang.awk newsgroup led to a typical data munging task:
I have to analyse data files that have the following format:
Each row corresponds to 1 day and the field logic is: $1 is the date,
followed by 24 value/flag pairs, representing measurements at 01:00,
02:00 ... 24:00 of the respective day. In short:
<date> <val1> <flag1> <val2> <flag2> ... <val24> <flag24>
Some test data is available at:
... (nolonger available at original location)
I have to sum up the values (per day and only valid data, i.e. with
flag>0) in order to calculate the mean. That's not too difficult.
However, I also need to know what the "maximum data gap" is, i.e. the
longest period with successive invalid measurements (i.e values with
flag<=0)
The data is free to download and use and is of this format:
Data is no longer available at that link. Zipped mirror available here (offsite mirror).
1991-03-30 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1
1991-03-31 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 20.000 1 20.000 1 20.000 1 35.000 1 50.000 1 60.000 1 40.000 1 30.000 1 30.000 1 30.000 1 25.000 1 20.000 1 20.000 1 20.000 1 20.000 1 20.000 1 35.000 1
1991-03-31 40.000 1 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2
1991-04-01 0.000 -2 13.000 1 16.000 1 21.000 1 24.000 1 22.000 1 20.000 1 18.000 1 29.000 1 44.000 1 50.000 1 43.000 1 38.000 1 27.000 1 27.000 1 24.000 1 23.000 1 18.000 1 12.000 1 13.000 1 14.000 1 15.000 1 13.000 1 10.000 1
1991-04-02 8.000 1 9.000 1 11.000 1 12.000 1 12.000 1 12.000 1 27.000 1 26.000 1 27.000 1 33.000 1 32.000 1 31.000 1 29.000 1 31.000 1 25.000 1 25.000 1 24.000 1 21.000 1 17.000 1 14.000 1 15.000 1 12.000 1 12.000 1 10.000 1
1991-04-03 10.000 1 9.000 1 10.000 1 10.000 1 9.000 1 10.000 1 15.000 1 24.000 1 28.000 1 24.000 1 18.000 1 14.000 1 12.000 1 13.000 1 14.000 1 15.000 1 14.000 1 15.000 1 13.000 1 13.000 1 13.000 1 12.000 1 10.000 1 10.000 1
Only a sample of the data showing its format is given above. The full example file may be downloaded here.
Structure your program to show statistics for each line of the file, (similar to the original Python, Perl, and AWK examples below), followed by summary statistics for the file. When showing example output just show a few line statistics and the full end summary.
| #Perl | Perl | use strict;
use warnings;
Β
my $nodata = 0; # Current run of consecutive flags<0 in lines of file
my $nodata_max = -1; # Max consecutive flags<0 in lines of file
my $nodata_maxline = "!"; # ... and line number(s) where it occurs
Β
my $infiles = join ", ", @ARGV;
Β
my $tot_file = 0;
my $num_file = 0;
Β
while (<>) {
chomp;
my $tot_line = 0; # sum of line data
my $num_line = 0; # number of line data items with flag>0
my $rejects = 0;
Β
# extract field info, skipping initial date field
my ($date, @fields) = split;
while (@fields and my ($datum, $flag) = splice @fields, 0, 2) {
if ($flag+1 < 2) {
$nodata++;
$rejects++;
next;
}
Β
# check run of data-absent fields
if($nodata_max == $nodata and $nodata > 0){
$nodata_maxline = "$nodata_maxline, $date";
}
if($nodata_max < $nodata and $nodata > 0){
$nodata_max = $nodata;
$nodata_maxline = $date;
}
# re-initialise run of nodata counter
$nodata = 0;
# gather values for averaging
$tot_line += $datum;
$num_line++;
}
Β
# totals for the file so far
$tot_file += $tot_line;
$num_file += $num_line;
Β
printf "Line:Β %11s Reject:Β %2i Accept:Β %2i Line_tot:Β %10.3f Line_avg:Β %10.3f\n",
$date, $rejects, $num_line, $tot_line, ($num_line>0)? $tot_line/$num_line: 0;
Β
}
Β
printf "\n";
printf "File(s) =Β %s\n", $infiles;
printf "Total =Β %10.3f\n", $tot_file;
printf "Readings =Β %6i\n", $num_file;
printf "Average =Β %10.3f\n", $tot_file / $num_file;
Β
printf "\nMaximum run(s) ofΒ %i consecutive false readings ends at line starting with date(s):Β %s\n",
$nodata_max, $nodata_maxline; |
http://rosettacode.org/wiki/The_Twelve_Days_of_Christmas | The Twelve Days of Christmas | Task
Write a program that outputs the lyrics of the Christmas carol The Twelve Days of Christmas.
The lyrics can be found here.
(You must reproduce the words in the correct order, but case, format, and punctuation are left to your discretion.)
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string Β (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff Β (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #JavaScript | JavaScript | Β
var days = [
'first', 'second', 'third', 'fourth', 'fifth', 'sixth', 'seventh', 'eighth', 'ninth',
'tenth', 'eleventh', 'twelfth',
];
Β
var gifts = [
"A partridge in a pear tree",
"Two turtle doves",
"Three french hens",
"Four calling birds",
"Five golden rings",
"Six geese a-laying",
"Seven swans a-swimming",
"Eight maids a-milking",
"Nine ladies dancing",
"Ten lords a-leaping",
"Eleven pipers piping",
"Twelve drummers drumming"
];
Β
var lines, verses = [], song;
Β
for ( var i = 0; i < 12; i++ ) {
Β
lines = [];
lines[0] = "On the " + days[i] + " day of Christmas, my true love gave to me";
Β
var j = i + 1;
var k = 0;
while ( j-- > 0 )
lines[++k] = gifts[j];
Β
Β
verses[i] = lines.join('\n');
Β
if ( i == 0 )
gifts[0] = "And a partridge in a pear tree";
Β
}
Β
song = verses.join('\n\n');
document.write(song);
Β |
http://rosettacode.org/wiki/Terminal_control/Coloured_text | Terminal control/Coloured text | Task
Display a word in various colours on the terminal.
The system palette, or colours such as Red, Green, Blue, Magenta, Cyan, and Yellow can be used.
Optionally demonstrate:
How the system should determine if the terminal supports colour
Setting of the background colour
How to cause blinking or flashing (if supported by the terminal)
| #PicoLisp | PicoLisp | (unless (member (sys "TERM") '("linux" "xterm" "xterm-color" "xterm-256color" "rxvt"))
(quit "This application requires a colour terminal") )
Β
# Coloured text
(for X '((1 . "Red") (4 . "Blue") (3 . "Yellow"))
(call 'tput "setaf" (car X))
(prinl (cdr X)) )
Β
# Blinking
(out '(tput "-S")
(prinl "setab 1^Jsetaf 3^Jblink") )
(prin "Flashing text")
Β
(call 'tput 'sgr0) # reset
(prinl) |
http://rosettacode.org/wiki/Terminal_control/Coloured_text | Terminal control/Coloured text | Task
Display a word in various colours on the terminal.
The system palette, or colours such as Red, Green, Blue, Magenta, Cyan, and Yellow can be used.
Optionally demonstrate:
How the system should determine if the terminal supports colour
Setting of the background colour
How to cause blinking or flashing (if supported by the terminal)
| #PowerShell | PowerShell | Β
foreach ($color in [enum]::GetValues([System.ConsoleColor])) {Write-Host "$color color." -ForegroundColor $color}
Β |
http://rosettacode.org/wiki/Terminal_control/Coloured_text | Terminal control/Coloured text | Task
Display a word in various colours on the terminal.
The system palette, or colours such as Red, Green, Blue, Magenta, Cyan, and Yellow can be used.
Optionally demonstrate:
How the system should determine if the terminal supports colour
Setting of the background colour
How to cause blinking or flashing (if supported by the terminal)
| #PureBasic | PureBasic | If OpenConsole()
PrintN("Background color# 00 01 02 03 04 05 06 07 08 09 10 11 12 13 14 15")
PrintN(" -----------------------------------------------")
Define Foreground, Background
For Foreground = 0 To 15
ConsoleColor(7, 0) ;grey foreground, black background
Print("Foreground color# " + RSet(Str(Foreground), 2, "0") + " ")
For Background = 0 To 15
ConsoleColor(Foreground, Background)
Print(RSet(Str(Foreground), 2, "0"))
ConsoleColor(7, 0) ;grey foreground, black background
Print(" ")
Next
PrintN("")
Next
Β
ConsoleColor(7, 0) ;grey foreground, black background
Print(#CRLF$ + #CRLF$ + "Press ENTER to exit"): Input()
CloseConsole()
EndIf |
http://rosettacode.org/wiki/Synchronous_concurrency | Synchronous concurrency | The goal of this task is to create two concurrent activities ("Threads" or "Tasks", not processes.) that share data synchronously. Your language may provide syntax or libraries to perform concurrency. Different languages provide different implementations of concurrency, often with different names. Some languages use the term threads, others use the term tasks, while others use co-processes. This task should not be implemented using fork, spawn, or the Linux/UNIX/Win32 pipe command, as communication should be between threads, not processes.
One of the concurrent units will read from a file named "input.txt" and send the contents of that file, one line at a time, to the other concurrent unit, which will print the line it receives to standard output. The printing unit must count the number of lines it prints. After the concurrent unit reading the file sends its last line to the printing unit, the reading unit will request the number of lines printed by the printing unit. The reading unit will then print the number of lines printed by the printing unit.
This task requires two-way communication between the concurrent units. All concurrent units must cleanly terminate at the end of the program.
| #Crystal | Crystal | File.write("input.txt", "a\nb\nc")
Β
lines = Channel(String).new
Β
spawn do
File.each_line("input.txt") do |line|
lines.send(line)
end
lines.close
end
Β
while line = lines.receive?
puts line
end
Β
File.delete("input.txt") |
http://rosettacode.org/wiki/Synchronous_concurrency | Synchronous concurrency | The goal of this task is to create two concurrent activities ("Threads" or "Tasks", not processes.) that share data synchronously. Your language may provide syntax or libraries to perform concurrency. Different languages provide different implementations of concurrency, often with different names. Some languages use the term threads, others use the term tasks, while others use co-processes. This task should not be implemented using fork, spawn, or the Linux/UNIX/Win32 pipe command, as communication should be between threads, not processes.
One of the concurrent units will read from a file named "input.txt" and send the contents of that file, one line at a time, to the other concurrent unit, which will print the line it receives to standard output. The printing unit must count the number of lines it prints. After the concurrent unit reading the file sends its last line to the printing unit, the reading unit will request the number of lines printed by the printing unit. The reading unit will then print the number of lines printed by the printing unit.
This task requires two-way communication between the concurrent units. All concurrent units must cleanly terminate at the end of the program.
| #D | D | import std.algorithm, std.concurrency, std.stdio;
Β
void main() {
auto printer = spawn(&printTask, thisTid);
auto f = File("input.txt","r");
foreach (string line; lines(f))
send(printer, line);
send(printer, true); //EOF
auto n = receiveOnly!(int)();
stdout.writefln("\n%d lines printed.", n);
}
Β
void printTask(Tid reader) {
int n = 0;
for (bool eof = false; !eof;)
receive(
(string line) {stdout.write(line); n++;},
(bool) {send(reader, n); eof = true;}
);
}
Β |
http://rosettacode.org/wiki/Table_creation/Postal_addresses | Table creation/Postal addresses | Task
Create a table to store addresses.
You may assume that all the addresses to be stored will be located in the USA. Β As such, you will need (in addition to a field holding a unique identifier) a field holding the street address, a field holding the city, a field holding the state code, and a field holding the zipcode. Β Choose appropriate types for each field.
For non-database languages, show how you would open a connection to a database (your choice of which) and create an address table in it. You should follow the existing models here for how you would structure the table.
| #Oz | Oz | declare
[Sqlite] = {Module.link ['x-ozlib:/sqlite/Sqlite.ozf']}
Β
DB = {Sqlite.open 'test.db'}
in
try
Β
{Sqlite.exec DB
"CREATE TABLE address ("
#"addrID INTEGER PRIMARY KEY,"
#"addrStreet TEXT NOT NULL,"
#"addrCity TEXT NOT NULL,"
#"addrState TEXT NOT NULL,"
#"addrZIP TEXT NOT NULL"
#")" _}
Β
catch E then
{Inspector.configure widgetShowStrings true}
{Inspect E}
finally
{Sqlite.close DB}
end |
http://rosettacode.org/wiki/Table_creation/Postal_addresses | Table creation/Postal addresses | Task
Create a table to store addresses.
You may assume that all the addresses to be stored will be located in the USA. Β As such, you will need (in addition to a field holding a unique identifier) a field holding the street address, a field holding the city, a field holding the state code, and a field holding the zipcode. Β Choose appropriate types for each field.
For non-database languages, show how you would open a connection to a database (your choice of which) and create an address table in it. You should follow the existing models here for how you would structure the table.
| #Perl | Perl | use DBI;
Β
my $db = DBI->connect('DBI:mysql:database:server','login','password');
Β
my $statment = <<EOF;
CREATE TABLE `Address` (
`addrID` int(11) NOT NULL auto_increment,
`addrStreet` varchar(50) NOT NULL default '',
`addrCity` varchar(25) NOT NULL default '',
`addrState` char(2) NOT NULL default '',
`addrZIP` char(10) NOT NULL default '',
PRIMARY KEY (`addrID`)
);
EOF
Β
my $exec = $db->prepare($statment);
$exec->execute; |
http://rosettacode.org/wiki/Sutherland-Hodgman_polygon_clipping | Sutherland-Hodgman polygon clipping | The Β Sutherland-Hodgman clipping algorithm Β finds the polygon that is the intersection between an arbitrary polygon (the βsubject polygonβ) and a convex polygon (the βclip polygonβ).
It is used in computer graphics (especially 2D graphics) to reduce the complexity of a scene being displayed by eliminating parts of a polygon that do not need to be displayed.
Task
Take the closed polygon defined by the points:
[
(
50
,
150
)
,
(
200
,
50
)
,
(
350
,
150
)
,
(
350
,
300
)
,
(
250
,
300
)
,
(
200
,
250
)
,
(
150
,
350
)
,
(
100
,
250
)
,
(
100
,
200
)
]
{\displaystyle [(50,150),(200,50),(350,150),(350,300),(250,300),(200,250),(150,350),(100,250),(100,200)]}
and clip it by the rectangle defined by the points:
[
(
100
,
100
)
,
(
300
,
100
)
,
(
300
,
300
)
,
(
100
,
300
)
]
{\displaystyle [(100,100),(300,100),(300,300),(100,300)]}
Print the sequence of points that define the resulting clipped polygon.
Extra credit
Display all three polygons on a graphical surface, using a different color for each polygon and filling the resulting polygon.
(When displaying you may use either a north-west or a south-west origin, whichever is more convenient for your display mechanism.)
| #BBC_BASIC | BBC BASIC | VDU 23,22,200;200;8,16,16,128
VDU 23,23,2;0;0;0;
Β
DIM SubjPoly{(8) x, y}
DIM ClipPoly{(3) x, y}
FOR v% = 0 TO 8Β : READ SubjPoly{(v%)}.x, SubjPoly{(v%)}.yΒ : NEXT
DATA 50,150,200,50,350,150,350,300,250,300,200,250,150,350,100,250,100,200
FOR v% = 0 TO 3Β : READ ClipPoly{(v%)}.x, ClipPoly{(v%)}.yΒ : NEXT
DATA 100,100, 300,100, 300,300, 100,300
Β
GCOL 4Β : PROCplotpoly(SubjPoly{()}, 9)
GCOL 1Β : PROCplotpoly(ClipPoly{()}, 4)
nvert% = FNsutherland_hodgman(SubjPoly{()}, ClipPoly{()}, Clipped{()})
GCOL 2Β : PROCplotpoly(Clipped{()}, nvert%)
END
Β
DEF FNsutherland_hodgman(subj{()}, clip{()}, RETURN out{()})
LOCAL i%, j%, n%, o%, p1{}, p2{}, s{}, e{}, p{}, inp{()}
DIM p1{x,y}, p2{x,y}, s{x,y}, e{x,y}, p{x,y}
n% = DIM(subj{()},1) + DIM(clip{()},1)
DIM inp{(n%) x, y}, out{(n%) x,y}
FOR o% = 0 TO DIM(subj{()},1)Β : out{(o%)} = subj{(o%)}Β : NEXT
p1{} = clip{(DIM(clip{()},1))}
FOR i% = 0 TO DIM(clip{()},1)
p2{} = clip{(i%)}
FOR n% = 0 TO o% - 1Β : inp{(n%)} = out{(n%)}Β : NEXTΒ : o% = 0
IF n% >= 2 THEN
s{} = inp{(n% - 1)}
FOR j% = 0 TO n% - 1
e{} = inp{(j%)}
IF FNside(e{}, p1{}, p2{}) THEN
IF NOT FNside(s{}, p1{}, p2{}) THEN
PROCintersection(p1{}, p2{}, s{}, e{}, p{})
out{(o%)} = p{}
o% += 1
ENDIF
out{(o%)} = e{}
o% += 1
ELSE
IF FNside(s{}, p1{}, p2{}) THEN
PROCintersection(p1{}, p2{}, s{}, e{}, p{})
out{(o%)} = p{}
o% += 1
ENDIF
ENDIF
s{} = e{}
NEXT
ENDIF
p1{} = p2{}
NEXT i%
= o%
Β
REM Which side of the line p1-p2 is the point p?
DEF FNside(p{}, p1{}, p2{})
= (p2.x - p1.x) * (p.y - p1.y) > (p2.y - p1.y) * (p.x - p1.x)
Β
REM Find the intersection of two lines p1-p2 and p3-p4
DEF PROCintersection(p1{}, p2{}, p3{}, p4{}, p{})
LOCAL a{}, b{}, k, l, mΒ : DIM a{x,y}, b{x,y}
a.x = p1.x - p2.xΒ : a.y = p1.y - p2.y
b.x = p3.x - p4.xΒ : b.y = p3.y - p4.y
k = p1.x * p2.y - p1.y * p2.x
l = p3.x * p4.y - p3.y * p4.x
m = 1 / (a.x * b.y - a.y * b.x)
p.x = m * (k * b.x - l * a.x)
p.y = m * (k * b.y - l * a.y)
ENDPROC
Β
REM plot a polygon
DEF PROCplotpoly(poly{()}, n%)
LOCAL i%
MOVE poly{(0)}.x, poly{(0)}.y
FOR i% = 1 TO n%-1
DRAW poly{(i%)}.x, poly{(i%)}.y
NEXT
DRAW poly{(0)}.x, poly{(0)}.y
ENDPROC |
http://rosettacode.org/wiki/Symmetric_difference | Symmetric difference | Task
Given two sets A and B, compute
(
A
β
B
)
βͺ
(
B
β
A
)
.
{\displaystyle (A\setminus B)\cup (B\setminus A).}
That is, enumerate the items that are in A or B but not both. This set is called the symmetric difference of A and B.
In other words:
(
A
βͺ
B
)
β
(
A
β©
B
)
{\displaystyle (A\cup B)\setminus (A\cap B)}
(the set of items that are in at least one of A or B minus the set of items that are in both A and B).
Optionally, give the individual differences (
A
β
B
{\displaystyle A\setminus B}
and
B
β
A
{\displaystyle B\setminus A}
) as well.
Test cases
A = {John, Bob, Mary, Serena}
B = {Jim, Mary, John, Bob}
Notes
If your code uses lists of items to represent sets then ensure duplicate items in lists are correctly handled. For example two lists representing sets of a = ["John", "Serena", "Bob", "Mary", "Serena"] and b = ["Jim", "Mary", "John", "Jim", "Bob"] should produce the result of just two strings: ["Serena", "Jim"], in any order.
In the mathematical notation above A \ B gives the set of items in A that are not in B; A βͺ B gives the set of items in both A and B, (their union); and A β© B gives the set of items that are in both A and B (their intersection).
| #Aime | Aime | show_sdiff(record u, x)
{
record r;
text s;
Β
r.copy(u);
Β
for (s in x) {
if (r.key(s)) {
r.delete(s);
} else {
r.p_integer(s, 0);
}
}
Β
r.vcall(o_, 0, "\n");
}
Β
new_set(...)
{
record r;
Β
ucall(r_p_integer, 1, r, 0);
Β
r;
}
Β
main(void)
{
show_sdiff(new_set("John", "Bob", "Mary", "Serena"),
new_set("Jim", "Mary", "John", "Bob"));
Β
0;
} |
http://rosettacode.org/wiki/Super-d_numbers | Super-d numbers | A super-d number is a positive, decimal (base ten) integer Β n Β such that Β d Γ nd Β has at least Β d Β consecutive digits Β d Β where
2 β€ d β€ 9
For instance, 753 is a super-3 number because 3 Γ 7533 = 1280873331.
Super-d Β numbers are also shown on Β MathWorldβ’ Β as Β super-d Β or Β super-d.
Task
Write a function/procedure/routine to find super-d numbers.
For Β d=2 Β through Β d=6, Β use the routine to show the first Β 10 Β super-d numbers.
Extra credit
Show the first Β 10 Β super-7, super-8, and/or super-9 numbers Β (optional).
See also
Β Wolfram MathWorld - Super-d Number.
Β OEIS: A014569 - Super-3 Numbers.
| #C | C | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <gmp.h>
Β
int main() {
for (unsigned int d = 2; d <= 9; ++d) {
printf("First 10 super-%u numbers:\n", d);
char digits[16] = { 0 };
memset(digits, '0' + d, d);
mpz_t bignum;
mpz_init(bignum);
for (unsigned int count = 0, n = 1; count < 10; ++n) {
mpz_ui_pow_ui(bignum, n, d);
mpz_mul_ui(bignum, bignum, d);
char* str = mpz_get_str(NULL, 10, bignum);
if (strstr(str, digits)) {
printf("%u ", n);
++count;
}
free(str);
}
mpz_clear(bignum);
printf("\n");
}
return 0;
} |
http://rosettacode.org/wiki/Take_notes_on_the_command_line | Take notes on the command line | Take notes on the command line is part of Short Circuit's Console Program Basics selection.
Invoking NOTES without commandline arguments displays the current contents of the local NOTES.TXT if it exists.
If NOTES has arguments, the current date and time are appended to the local NOTES.TXT followed by a newline.
Then all the arguments, joined with spaces, prepended with a tab, and appended with a trailing newline, are written to NOTES.TXT.
If NOTES.TXT doesn't already exist in the current directory then a new NOTES.TXT file should be created.
| #Common_Lisp | Common Lisp | (defparameter *notes* "NOTES.TXT")
Β
(defun format-date-time (stream)
(multiple-value-bind (second minute hour date month year) (get-decoded-time)
(format stream "~D-~2,'0D-~2,'0D ~2,'0D:~2,'0D:~2,'0D"
year month date hour minute second)))
Β
(defun notes (args)
(if args
(with-open-file (s *notes* :direction :output
:if-exists :append
:if-does-not-exist :create)
(format-date-time s)
(format s "~&~A~{~A~^ ~}~%" #\Tab args))
(with-open-file (s *notes* :if-does-not-exist nil)
(when s
(loop for line = (read-line s nil)
while line
do (write-line line))))))
Β
(defun main ()
(notes (uiop:command-line-arguments))) |
http://rosettacode.org/wiki/Take_notes_on_the_command_line | Take notes on the command line | Take notes on the command line is part of Short Circuit's Console Program Basics selection.
Invoking NOTES without commandline arguments displays the current contents of the local NOTES.TXT if it exists.
If NOTES has arguments, the current date and time are appended to the local NOTES.TXT followed by a newline.
Then all the arguments, joined with spaces, prepended with a tab, and appended with a trailing newline, are written to NOTES.TXT.
If NOTES.TXT doesn't already exist in the current directory then a new NOTES.TXT file should be created.
| #D | D | void main(in string[] args) {
import std.stdio, std.file, std.datetime, std.range;
Β
immutable filename = "NOTES.TXT";
Β
if (args.length == 1) {
if (filename.exists && filename.isFile)
writefln("%-(%s\n%)", filename.File.byLine);
} else {
auto f = File(filename, "a+");
f.writefln("%s", cast(DateTime)Clock.currTime);
f.writefln("\t%-(%sΒ %)", args.dropOne);
}
} |
http://rosettacode.org/wiki/Superellipse | Superellipse | A superellipse is a geometric figure defined as the set of all points (x, y) with
|
x
a
|
n
+
|
y
b
|
n
=
1
,
{\displaystyle \left|{\frac {x}{a}}\right|^{n}\!+\left|{\frac {y}{b}}\right|^{n}\!=1,}
where n, a, and b are positive numbers.
Task
Draw a superellipse with n = 2.5, and a = b = 200
| #Ada | Ada | with Ada.Numerics.Elementary_Functions;
Β
with SDL.Video.Windows.Makers;
with SDL.Video.Renderers.Makers;
with SDL.Events.Events;
Β
procedure Superelipse is
Β
Width Β : constantΒ := 600;
HeightΒ : constantΒ := 600;
A Β : constantΒ := 200.0;
B Β : constantΒ := 200.0;
N Β : constantΒ := 2.5;
Β
Window Β : SDL.Video.Windows.Window;
RendererΒ : SDL.Video.Renderers.Renderer;
Event Β : SDL.Events.Events.Events;
Β
procedure Draw_Superelipse
is
use type SDL.C.int;
use Ada.Numerics.Elementary_Functions;
Xx, YyΒ : Float;
subtype Legal_Range is Float range 0.980 .. 1.020;
begin
for Y in 0 .. Height loop
for X in 0 .. Width loop
XxΒ := Float (X - Width / 2);
YyΒ := Float (Y - Height / 2);
if (abs (Xx / A)) ** N + (abs (Yy / B)) ** N in Legal_Range then
Renderer.Draw (Point => (X => Width / 2 + SDL.C.int (Xx),
Y => Height / 2 - SDL.C.int (Yy)));
end if;
Β
end loop;
end loop;
end Draw_Superelipse;
Β
procedure Wait is
use type SDL.Events.Event_Types;
begin
loop
while SDL.Events.Events.Poll (Event) loop
if Event.Common.Event_Type = SDL.Events.Quit then
return;
end if;
end loop;
delay 0.100;
end loop;
end Wait;
Β
begin
if not SDL.Initialise (Flags => SDL.Enable_Screen) then
return;
end if;
Β
SDL.Video.Windows.Makers.Create (Win => Window,
Title => "Superelipse",
Position => SDL.Natural_Coordinates'(X => 10, Y => 10),
Size => SDL.Positive_Sizes'(Width, Height),
Flags => 0);
SDL.Video.Renderers.Makers.Create (Renderer, Window.Get_Surface);
Renderer.Set_Draw_Colour ((0, 0, 0, 255));
Renderer.Fill (Rectangle => (0, 0, Width, Height));
Renderer.Set_Draw_Colour ((0, 220, 0, 255));
Β
Draw_Superelipse;
Window.Update_Surface;
Β
Wait;
Window.Finalize;
SDL.Finalise;
end Superelipse; |
http://rosettacode.org/wiki/Sylvester%27s_sequence | Sylvester's sequence |
This page uses content from Wikipedia. The original article was at Sylvester's sequence. 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)
In number theory, Sylvester's sequence is an integer sequence in which each term of the sequence is the product of the previous terms, plus one.
Its values grow doubly exponentially, and the sum of its reciprocals forms a series of unit fractions that converges to 1 more rapidly than any other series of unit fractions with the same number of terms.
Further, the sum of the first k terms of the infinite series of reciprocals provides the closest possible underestimate of 1 by any k-term Egyptian fraction.
Task
Write a routine (function, procedure, generator, whatever) to calculate Sylvester's sequence.
Use that routine to show the values of the first 10 elements in the sequence.
Show the sum of the reciprocals of the first 10 elements on the sequence, ideally as an exact fraction.
Related tasks
Egyptian fractions
Harmonic series
See also
OEIS A000058 - Sylvester's sequence
| #F.23 | F# | Β
// Sylvester's sequence: Nigel Galloway. June 7th., 2021
let S10=Seq.unfold(fun(n,g)->printfn "*%AΒ %A" n g; Some(n,(n*g+1I,n*g) ) )(2I,1I)|>Seq.take 10|>List.ofSeq
S10|>List.iteri(fun n g->printfn "%2d ->Β %A" (n+1) g)
let n,g=S10|>List.fold(fun(n,g) i->(n*i+g,g*i))(0I,1I) in printfn "\nThe sum of the reciprocals of S10 is \n%A/\n%A" n g
Β |
http://rosettacode.org/wiki/Sylvester%27s_sequence | Sylvester's sequence |
This page uses content from Wikipedia. The original article was at Sylvester's sequence. 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)
In number theory, Sylvester's sequence is an integer sequence in which each term of the sequence is the product of the previous terms, plus one.
Its values grow doubly exponentially, and the sum of its reciprocals forms a series of unit fractions that converges to 1 more rapidly than any other series of unit fractions with the same number of terms.
Further, the sum of the first k terms of the infinite series of reciprocals provides the closest possible underestimate of 1 by any k-term Egyptian fraction.
Task
Write a routine (function, procedure, generator, whatever) to calculate Sylvester's sequence.
Use that routine to show the values of the first 10 elements in the sequence.
Show the sum of the reciprocals of the first 10 elements on the sequence, ideally as an exact fraction.
Related tasks
Egyptian fractions
Harmonic series
See also
OEIS A000058 - Sylvester's sequence
| #Factor | Factor | USING: io kernel lists lists.lazy math prettyprintΒ ;
Β
: lsylvester ( -- list ) 2 [ dup sq swap - 1 + ] lfrom-byΒ ;
Β
"First 10 elements of Sylvester's sequence:" print
10 lsylvester ltake dup [ . ] leach nl
Β
"Sum of the reciprocals of first 10 elements:" print
0 [ recip + ] foldl . |
http://rosettacode.org/wiki/Sylvester%27s_sequence | Sylvester's sequence |
This page uses content from Wikipedia. The original article was at Sylvester's sequence. 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)
In number theory, Sylvester's sequence is an integer sequence in which each term of the sequence is the product of the previous terms, plus one.
Its values grow doubly exponentially, and the sum of its reciprocals forms a series of unit fractions that converges to 1 more rapidly than any other series of unit fractions with the same number of terms.
Further, the sum of the first k terms of the infinite series of reciprocals provides the closest possible underestimate of 1 by any k-term Egyptian fraction.
Task
Write a routine (function, procedure, generator, whatever) to calculate Sylvester's sequence.
Use that routine to show the values of the first 10 elements in the sequence.
Show the sum of the reciprocals of the first 10 elements on the sequence, ideally as an exact fraction.
Related tasks
Egyptian fractions
Harmonic series
See also
OEIS A000058 - Sylvester's sequence
| #Fermat | Fermat | Array syl[10];
syl[1]:=2;
for i=2 to 10 do syl[i]:=1+Prod<n=1,i-1>[syl[n]] od;
!![syl];
srec:=Sigma<i=1,10>[1/syl[i]];
!!srec; |
http://rosettacode.org/wiki/Taxicab_numbers | Taxicab numbers |
A Β taxicab number Β (the definition that is being used here) Β is a positive integer that can be expressed as the sum of two positive cubes in more than one way.
The first taxicab number is Β 1729, Β which is:
13 Β + Β 123 Β Β Β and also
93 Β + Β 103.
Taxicab numbers are also known as:
Β taxi numbers
Β taxi-cab numbers
Β taxi cab numbers
Β Hardy-Ramanujan numbers
Task
Compute and display the lowest 25 taxicab numbers (in numeric order, and in a human-readable format).
For each of the taxicab numbers, show the number as well as it's constituent cubes.
Extra credit
Show the 2,000th taxicab number, and a half dozen more
See also
A001235: taxicab numbers on The On-Line Encyclopedia of Integer Sequences.
Hardy-Ramanujan Number on MathWorld.
taxicab number on MathWorld.
taxicab number on Wikipedia Β (includes the story on how taxi-cab numbers came to be called).
| #Haskell | Haskell | import Data.List (groupBy, sortOn, tails, transpose)
import Data.Function (on)
Β
--------------------- TAXICAB NUMBERS --------------------
Β
taxis :: Int -> [[(Int, ((Int, Int), (Int, Int)))]]
taxis nCubes =
filter ((> 1) . length) $
groupBy (on (==) fst) $
sortOn fst
[ (fst x + fst y, (x, y))
| (x:t) <- tails $ ((^ 3) >>= (,)) <$> [1 .. nCubes]
, y <- t ]
Β
--------------------------- TEST -------------------------
main :: IO ()
main =
mapM_ putStrLn $
concat <$>
transpose
(((<$>) =<< flip justifyRight ' ' . maximum . (length <$>)) <$>
transpose (taxiRow <$> (take 25 xs <> take 7 (drop 1999 xs))))
where
xs = zip [1 ..] (taxis 1200)
justifyRight n c = (drop . length) <*> (replicate n c <>)
Β
------------------------- DISPLAY ------------------------
taxiRow :: (Int, [(Int, ((Int, Int), (Int, Int)))]) -> [String]
taxiRow (n, [(a, ((axc, axr), (ayc, ayr))), (b, ((bxc, bxr), (byc, byr)))]) =
concat
[ [show n, ". ", show a, " = "]
, term axr axc " + "
, term ayr ayc " or "
, term bxr bxc " + "
, term byr byc []
]
where
term r c l = ["(", show r, "^3=", show c, ")", l] |
http://rosettacode.org/wiki/Superpermutation_minimisation | Superpermutation minimisation | A superpermutation of N different characters is a string consisting of an arrangement of multiple copies of those N different characters in which every permutation of those characters can be found as a substring.
For example, representing the characters as A..Z, using N=2 we choose to use the first two characters 'AB'.
The permutations of 'AB' are the two, (i.e. two-factorial), strings: 'AB' and 'BA'.
A too obvious method of generating a superpermutation is to just join all the permutations together forming 'ABBA'.
A little thought will produce the shorter (in fact the shortest) superpermutation of 'ABA' - it contains 'AB' at the beginning and contains 'BA' from the middle to the end.
The "too obvious" method of creation generates a string of length N!*N. Using this as a yardstick, the task is to investigate other methods of generating superpermutations of N from 1-to-7 characters, that never generate larger superpermutations.
Show descriptions and comparisons of algorithms used here, and select the "Best" algorithm as being the one generating shorter superpermutations.
The problem of generating the shortest superpermutation for each N might be NP complete, although the minimal strings for small values of N have been found by brute -force searches.
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
Reference
The Minimal Superpermutation Problem. by Nathaniel Johnston.
oeis A180632 gives 0-5 as 0, 1, 3, 9, 33, 153. 6 is thought to be 872.
Superpermutations - Numberphile. A video
Superpermutations: the maths problem solved by 4chan - Standupmaths. A video of recent (2018) mathematical progress.
New Superpermutations Discovered! Standupmaths & Numberphile.
| #Delphi | Delphi | Β
program Superpermutation_minimisation;
Β
{$APPTYPE CONSOLE}
Β
uses
System.SysUtils;
Β
const
Max = 12;
Β
var
super: ansistring;
pos: Integer;
cnt: TArray<Integer>;
Β
function factSum(n: Integer): Uint64;
begin
var s: Uint64 := 0;
var f := 1;
var x := 0;
Β
while x < n do
begin
inc(x);
f := f * x;
inc(s, f);
end;
Β
Result := s;
end;
Β
function r(n: Integer): Boolean;
begin
if n = 0 then
exit(false);
Β
var c := super[pos - n];
Β
dec(cnt[n]);
Β
if cnt[n] = 0 then
begin
cnt[n] := n;
if not r(n - 1) then
exit(false);
end;
super[pos] := c;
inc(pos);
result := true;
end;
Β
procedure SuperPerm(n: Integer);
begin
var pos := n;
var le: Uint64 := factSum(n);
SetLength(super, le);
Β
for var i := 0 to n do
cnt[i] := i;
Β
for var i := 1 to n do
super[i] := ansichar(i + ord('0'));
Β
while r(n) do
;
end;
Β
begin
SetLength(cnt, max);
Β
for var n := 0 to max - 1 do
begin
write('superperm(', n: 2, ') ');
SuperPerm(n);
writeln('len = ', length(super));
end;
{$IFNDEF UNIX} readln; {$ENDIF}
end. |
http://rosettacode.org/wiki/Tau_number | Tau number | A Tau number is a positive integer divisible by the count of its positive divisors.
Task
Show the first Β 100 Β Tau numbers.
The numbers shall be generated during run-time (i.e. the code may not contain string literals, sets/arrays of integers, or alike).
Related task
Β Tau function
| #Perl | Perl | use strict;
use warnings;
use feature 'say';
use ntheory 'divisors';
Β
my(@x,$n);
Β
do { push(@x,$n) unless $n % scalar(divisors(++$n)) } until 100 == @x;
Β
say "Tau numbers - first 100:\n" .
((sprintf "@{['%5d' x 100]}", @x[0..100-1]) =~ s/(.{80})/$1\n/gr); |
http://rosettacode.org/wiki/Tau_number | Tau number | A Tau number is a positive integer divisible by the count of its positive divisors.
Task
Show the first Β 100 Β Tau numbers.
The numbers shall be generated during run-time (i.e. the code may not contain string literals, sets/arrays of integers, or alike).
Related task
Β Tau function
| #Phix | Phix | integer n = 1, found = 0
while found<100 do
if remainder(n,length(factors(n,1)))=0 then
found += 1
printf(1,"%,6d",n)
if remainder(found,10)=0 then puts(1,"\n") end if
end if
n += 1
end while
|
http://rosettacode.org/wiki/Tarjan | Tarjan |
This page uses content from Wikipedia. The original article was at Graph. 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)
Tarjan's algorithm is an algorithm in graph theory for finding the strongly connected components of a graph.
It runs in linear time, matching the time bound for alternative methods including Kosaraju's algorithm and the path-based strong component algorithm.
Tarjan's Algorithm is named for its discoverer, Robert Tarjan.
References
The article on Wikipedia.
| #zkl | zkl | class Tarjan{
// input: graph G = (V, Es)
// output: set of strongly connected components (sets of vertices)
// Ick: class holds global state for strongConnect(), otherwise inert
const INDEX=0, LOW_LINK=1, ON_STACK=2;
fcn init(graph){
var index=0, stack=List(), components=List(),
G=List.createLong(graph.len(),0);
Β
// convert graph to ( (index,lowlink,onStack),(id,links)), ...)
// sorted by id
foreach v in (graph){ G[v[0]]=T( L(Void,Void,False),v) }
Β
foreach v in (G){ if(v[0][INDEX]==Void) strongConnect(v) }
Β
println("List of strongly connected components:");
foreach c in (components){ println(c.reverse().concat(",")) }
Β
returnClass(components); // over-ride return of class instance
}
fcn strongConnect(v){ // v is ( (index,lowlink,onStack), (id,links) )
// Set the depth index for v to the smallest unused index
v0:=v[0]; v0[INDEX]=v0[LOW_LINK]=index;
index+=1;
v0[ON_STACK]=True;
stack.push(v);
Β
// Consider successors of v
foreach idx in (v[1][1,*]){ // links of v to other vs
w,w0Β := G[idx],w[0]; // well, that is pretty vile
if(w[0][INDEX]==Void){
strongConnect(w); // Successor w not yet visited; recurse on it
v0[LOW_LINK]=v0[LOW_LINK].min(w0[LOW_LINK]);
}
else if(w0[ON_STACK])
// Successor w is in stack S and hence in the current SCC
v0[LOW_LINK]=v0[LOW_LINK].min(w0[INDEX]);
}
// If v is a root node, pop the stack and generate an SCC
if(v0[LOW_LINK]==v0[INDEX]){
strong:=List(); // start a new strongly connected component
do{
w,w0Β := stack.pop(), w[0];
w0[ON_STACK]=False;
strong.append(w[1][0]); // add w to strongly connected component
}while(w.id!=v.id);
components.append(strong); // output strongly connected component
}
}
} |
http://rosettacode.org/wiki/Teacup_rim_text | Teacup rim text | On a set of coasters we have, there's a picture of a teacup. Β On the rim of the teacup the word Β TEA Β appears a number of times separated by bullet characters Β (β’).
It occurred to me that if the bullet were removed and the words run together, Β you could start at any letter and still end up with a meaningful three-letter word.
So start at the Β T Β and read Β TEA. Β Start at the Β E Β and read Β EAT, Β or start at the Β A Β and read Β ATE.
That got me thinking that maybe there are other words that could be used rather that Β TEA. Β And that's just English. Β What about Italian or Greek or ... um ... Telugu.
For English, we will use the unixdict (now) located at: Β unixdict.txt.
(This will maintain continuity with other Rosetta Code tasks that also use it.)
Task
Search for a set of words that could be printed around the edge of a teacup. Β The words in each set are to be of the same length, that length being greater than two (thus precluding Β AH Β and Β HA, Β for example.)
Having listed a set, for example Β [ate tea eat], Β refrain from displaying permutations of that set, e.g.: Β [eat tea ate] Β etc.
The words should also be made of more than one letter Β (thus precluding Β III Β and Β OOO Β etc.)
The relationship between these words is (using ATE as an example) that the first letter of the first becomes the last letter of the second. Β The first letter of the second becomes the last letter of the third. Β So Β ATE Β becomes Β TEA Β and Β TEA Β becomes Β EAT.
All of the possible permutations, using this particular permutation technique, must be words in the list.
The set you generate for Β ATE Β will never included the word Β ETA Β as that cannot be reached via the first-to-last movement method.
Display one line for each set of teacup rim words.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string Β (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff Β (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #REXX | REXX | /*REXX pgm finds circular words (length>2), using a dictionary, suppress permutations.*/
parse arg iFID L . /*obtain optional arguments from the CL*/
if iFID==''|iFID=="," then iFID= 'wordlist.10k' /*Not specified? Then use the default.*/
if L==''| L=="," then L= 3 /* " " " " " " */
#= 0 /*number of words in dictionary, Len>L.*/
@.= /*stemmed array of nonβduplicated words*/
do r=0 while lines(iFID) \== 0 /*read all lines (words) in dictionary.*/
parse upper value linein(iFID) with z . /*obtain a word from the dictionary. */
if length(z)<L | @.z\=='' then iterate /*length must be L or more, no dups.*/
if \datatype(z, 'U') then iterate /*Word contains non-letters? Then skip*/
@.z = z /*assign a word from the dictionary. */
#= # + 1; $.#= z /*bump word count; append word to list.*/
end /*r*/ /* [β] dictionary need not be sorted. */
cw= 0 /*the number of circular words (so far)*/
say "There're " r ' entries in the dictionary (of all types): ' iFID
say "There're " # ' words in the dictionary of at least length ' L
say
do j=1 for #; x= $.j; y= x /*obtain the Jth word in the list. */
if x=='' then iterate /*if a null, don't show variants. */
yy= y /*the start of a list of the variants. */
do k=1 for length(x)-1 /*"circulate" the litters in the word. */
y= substr(y, 2)left(y, 1) /*add the left letter to the right end.*/
if @.y=='' then iterate j /*if not a word, then skip this word. */
yy= yy',' y /*append to the list of the variants. */
@.y= /*nullify word to suppress permutations*/
end /*k*/
cw= cw + 1 /*bump counter of circular words found.*/
say 'circular word: ' yy /*display a circular word and variants.*/
end /*j*/
say
say cw ' circular words were found.' /*stick a fork in it, we're all done. */ |
http://rosettacode.org/wiki/Temperature_conversion | Temperature conversion | There are quite a number of temperature scales. For this task we will concentrate on four of the perhaps best-known ones:
Kelvin, Celsius, Fahrenheit, and Rankine.
The Celsius and Kelvin scales have the same magnitude, but different null points.
0 degrees Celsius corresponds to 273.15 kelvin.
0 kelvin is absolute zero.
The Fahrenheit and Rankine scales also have the same magnitude, but different null points.
0 degrees Fahrenheit corresponds to 459.67 degrees Rankine.
0 degrees Rankine is absolute zero.
The Celsius/Kelvin and Fahrenheit/Rankine scales have a ratio of 5Β : 9.
Task
Write code that accepts a value of kelvin, converts it to values of the three other scales, and prints the result.
Example
K 21.00
C -252.15
F -421.87
R 37.80
| #BASIC | BASIC | Β
10 REM TRANSLATION OF AWK VERSION
20 INPUT "KELVIN DEGREES",K
30 IF K <= 0 THEN END: REM A VALUE OF ZERO OR LESS WILL END PROGRAM
40 LET C = K - 273.15
50 LET F = K * 1.8 - 459.67
60 LET R = K * 1.8
70 PRINT K; " KELVIN IS EQUIVALENT TO"
80 PRINT C; " DEGREES CELSIUS"
90 PRINT F; " DEGREES FAHRENHEIT"
100 PRINT R; " DEGREES RANKINE"
110 GOTO 20
Β |
http://rosettacode.org/wiki/Tau_function | Tau function | Given a positive integer, count the number of its positive divisors.
Task
Show the result for the first Β 100 Β positive integers.
Related task
Β Tau number
| #GW-BASIC | GW-BASIC | 10 FOR N = 1 TO 100
20 IF N < 3 THEN T=N: GOTO 70
30 T=2
40 FOR A = 2 TO INT( (N+1)/2 )
50 IF N MOD A = 0 THEN T = T + 1
60 NEXT A
70 PRINT T;
80 IF N MOD 10 = 0 THEN PRINT
90 NEXT N |
http://rosettacode.org/wiki/Tau_function | Tau function | Given a positive integer, count the number of its positive divisors.
Task
Show the result for the first Β 100 Β positive integers.
Related task
Β Tau number
| #Haskell | Haskell | tau :: Integral a => a -> a
tau n | n <= 0 = error "Not a positive integer"
tau n = go 0 (1, 1)
where
yo i = (i, i * i)
go r (i, ii)
| n < ii = r
| n == ii = r + 1
| 0 == mod n i = go (r + 2) (yo $ i + 1)
| otherwise = go r (yo $ i + 1)
Β
main = print $ map tau [1..100] |
http://rosettacode.org/wiki/Terminal_control/Clear_the_screen | Terminal control/Clear the screen | Task
Clear the terminal window.
| #Lua | Lua | os.execute( "clear" ) |
http://rosettacode.org/wiki/Terminal_control/Clear_the_screen | Terminal control/Clear the screen | Task
Clear the terminal window.
| #M2000_Interpreter | M2000 Interpreter | Β
Module Checkit {
Pen 14 ' yellow
\\ using form we set characters by rows
\\ this clear the screen
Form 80, 40
\\ magenta for background, all form for vertical scrolling
Cls 5, 0
Print "wait... half second"
Wait 500
\\ clear using background color
Cls
\\ set the background (using html number for color), and set 4th line as top
\\ for scrolling
Cls #11bb22, 3
Print "This is in 4th line"
Wait 1000
\\ now we center the form, using 12000 twips by 8000twips as border
\\ form inside maybe smaller
\\ font size is 16pt of current font
Font "Courier New"
Window 16, 12000, 8000;
Print "This is first line"
Wait 1000
Font "Arial"
\\ set the console form to screen 0, maximized
Window 16, 0
Cls 5 ' magenta
Back {
Cls 15 ' white border
}
}
checkit
Β |
http://rosettacode.org/wiki/Terminal_control/Clear_the_screen | Terminal control/Clear the screen | Task
Clear the terminal window.
| #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | Run["clear"]; |
http://rosettacode.org/wiki/Ternary_logic | Ternary logic |
This page uses content from Wikipedia. The original article was at Ternary logic. 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)
In logic, a three-valued logic (also trivalent, ternary, or trinary logic, sometimes abbreviated 3VL) is any of several many-valued logic systems in which there are three truth values indicating true, false and some indeterminate third value.
This is contrasted with the more commonly known bivalent logics (such as classical sentential or boolean logic) which provide only for true and false.
Conceptual form and basic ideas were initially created by Εukasiewicz, Lewis and Sulski.
These were then re-formulated by Grigore Moisil in an axiomatic algebraic form, and also extended to n-valued logics in 1945.
Example Ternary Logic Operators in Truth Tables:
not a
Β¬
True
False
Maybe
Maybe
False
True
a and b
β§
True
Maybe
False
True
True
Maybe
False
Maybe
Maybe
Maybe
False
False
False
False
False
a or b
β¨
True
Maybe
False
True
True
True
True
Maybe
True
Maybe
Maybe
False
True
Maybe
False
if a then b
β
True
Maybe
False
True
True
Maybe
False
Maybe
True
Maybe
Maybe
False
True
True
True
a is equivalent to b
β‘
True
Maybe
False
True
True
Maybe
False
Maybe
Maybe
Maybe
Maybe
False
False
Maybe
True
Task
Define a new type that emulates ternary logic by storing data trits.
Given all the binary logic operators of the original programming language, reimplement these operators for the new Ternary logic type trit.
Generate a sampling of results using trit variables.
Kudos for actually thinking up a test case algorithm where ternary logic is intrinsically useful, optimises the test case algorithm and is preferable to binary logic.
Note: Β Setun Β (Π‘Π΅ΡΡΠ½Ρ) was a Β balanced ternary Β computer developed in 1958 at Β Moscow State University. Β The device was built under the lead of Β Sergei Sobolev Β and Β Nikolay Brusentsov. Β It was the only modern Β ternary computer, Β using three-valued ternary logic
| #Kotlin | Kotlin | // version 1.1.2
Β
enum class Trit {
TRUE, MAYBE, FALSE;
Β
operator fun not() = when (this) {
TRUE -> FALSE
MAYBE -> MAYBE
FALSE -> TRUE
}
Β
infix fun and(other: Trit) = when (this) {
TRUE -> other
MAYBE -> if (other == FALSE) FALSE else MAYBE
FALSE -> FALSE
}
Β
infix fun or(other: Trit) = when (this) {
TRUE -> TRUE
MAYBE -> if (other == TRUE) TRUE else MAYBE
FALSE -> other
}
Β
infix fun imp(other: Trit) = when (this) {
TRUE -> other
MAYBE -> if (other == TRUE) TRUE else MAYBE
FALSE -> TRUE
}
Β
infix fun eqv(other: Trit) = when (this) {
TRUE -> other
MAYBE -> MAYBE
FALSE -> !other
}
Β
override fun toString() = this.name[0].toString()
}
Β
fun main(args: Array<String>) {
val ta = arrayOf(Trit.TRUE, Trit.MAYBE, Trit.FALSE)
Β
// not
println("not")
println("-------")
for (t in ta) println(" $t | ${!t}")
println()
Β
// and
println("and | T M F")
println("-------------")
for (t in ta) {
print(" $t | ")
for (tt in ta) print("${t and tt} ")
println()
}
println()
Β
// or
println("or | T M F")
println("-------------")
for (t in ta) {
print(" $t | ")
for (tt in ta) print("${t or tt} ")
println()
}
println()
Β
// imp
println("imp | T M F")
println("-------------")
for (t in ta) {
print(" $t | ")
for (tt in ta) print("${t imp tt} ")
println()
}
println()
Β
// eqv
println("eqv | T M F")
println("-------------")
for (t in ta) {
print(" $t | ")
for (tt in ta) print("${t eqv tt} ")
println()
}
} |
http://rosettacode.org/wiki/Text_processing/1 | Text processing/1 | This task has been flagged for clarification. Code on this page in its current state may be flagged incorrect once this task has been clarified. See this page's Talk page for discussion.
Often data is produced by one program, in the wrong format for later use by another program or person. In these situations another program can be written to parse and transform the original data into a format useful to the other. The term "Data Munging" is often used in programming circles for this task.
A request on the comp.lang.awk newsgroup led to a typical data munging task:
I have to analyse data files that have the following format:
Each row corresponds to 1 day and the field logic is: $1 is the date,
followed by 24 value/flag pairs, representing measurements at 01:00,
02:00 ... 24:00 of the respective day. In short:
<date> <val1> <flag1> <val2> <flag2> ... <val24> <flag24>
Some test data is available at:
... (nolonger available at original location)
I have to sum up the values (per day and only valid data, i.e. with
flag>0) in order to calculate the mean. That's not too difficult.
However, I also need to know what the "maximum data gap" is, i.e. the
longest period with successive invalid measurements (i.e values with
flag<=0)
The data is free to download and use and is of this format:
Data is no longer available at that link. Zipped mirror available here (offsite mirror).
1991-03-30 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1
1991-03-31 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 20.000 1 20.000 1 20.000 1 35.000 1 50.000 1 60.000 1 40.000 1 30.000 1 30.000 1 30.000 1 25.000 1 20.000 1 20.000 1 20.000 1 20.000 1 20.000 1 35.000 1
1991-03-31 40.000 1 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2
1991-04-01 0.000 -2 13.000 1 16.000 1 21.000 1 24.000 1 22.000 1 20.000 1 18.000 1 29.000 1 44.000 1 50.000 1 43.000 1 38.000 1 27.000 1 27.000 1 24.000 1 23.000 1 18.000 1 12.000 1 13.000 1 14.000 1 15.000 1 13.000 1 10.000 1
1991-04-02 8.000 1 9.000 1 11.000 1 12.000 1 12.000 1 12.000 1 27.000 1 26.000 1 27.000 1 33.000 1 32.000 1 31.000 1 29.000 1 31.000 1 25.000 1 25.000 1 24.000 1 21.000 1 17.000 1 14.000 1 15.000 1 12.000 1 12.000 1 10.000 1
1991-04-03 10.000 1 9.000 1 10.000 1 10.000 1 9.000 1 10.000 1 15.000 1 24.000 1 28.000 1 24.000 1 18.000 1 14.000 1 12.000 1 13.000 1 14.000 1 15.000 1 14.000 1 15.000 1 13.000 1 13.000 1 13.000 1 12.000 1 10.000 1 10.000 1
Only a sample of the data showing its format is given above. The full example file may be downloaded here.
Structure your program to show statistics for each line of the file, (similar to the original Python, Perl, and AWK examples below), followed by summary statistics for the file. When showing example output just show a few line statistics and the full end summary.
| #Phix | Phix | -- demo\rosetta\TextProcessing1.exw
with javascript_semantics -- (include version/first of next three lines only)
include readings.e -- global constant lines, or:
--assert(write_lines("readings.txt",lines)!=-1) -- first run, then:
--constant lines = read_lines("readings.txt")
include builtins\timedate.e
integer count = 0,
max_count = 0,
ntot = 0
atom readtot = 0
timedate run_start, max_start
procedure end_bad_run()
if count then
if count>max_count then
max_count = count
max_start = run_start
end if
count = 0
end if
end procedure
for i=1 to length(lines) do
sequence oneline = split(lines[i],'\t'), r
if length(oneline)!=49 then
?"bad line (length!=49)"
else
r = parse_date_string(oneline[1],{"YYYY-MM-DD"})
if not timedate(r) then
?{"bad date",oneline[1]}
else
timedate td = r
integer rejects=0, accepts=0
atom readsum = 0
for j=2 to 48 by 2 do
r = scanf(oneline[j],"%f")
if length(r)!=1 then
?{"error scanning",oneline[j]}
rejects += 1
else
atom reading = r[1][1]
r = scanf(oneline[j+1],"%d")
if length(r)!=1 then
?{"error scanning",oneline[j+1]}
rejects += 1
else
integer flag = r[1][1]
if flag<=0 then
if count=0 then
run_start = td
end if
count += 1
rejects += 1
else
end_bad_run()
accepts += 1
readsum += reading
end if
end if
end if
end for
readtot += readsum
ntot += accepts
if i>=length(lines)-2 then
string average = iff(accepts=0?"N/A":sprintf("%6.3f",readsum/accepts))
printf(1,"Date:Β %s, Rejects:Β %2d, Accepts:Β %2d, Line total:Β %7.3f, AverageΒ %s\n",
{format_timedate(td,"DD/MM/YYYY"),rejects, accepts, readsum, average})
end if
end if
end if
end for
printf(1,"Average:Β %.3f (ofΒ %d readings)\n",{readtot/ntot,ntot})
end_bad_run()
if max_count then
printf(1,"Maximum run ofΒ %d consecutive false readings starting:Β %s\n",
{max_count,format_timedate(max_start,"DD/MM/YYYY")})
end if
?"done"
{} = wait_key()
|
http://rosettacode.org/wiki/The_Twelve_Days_of_Christmas | The Twelve Days of Christmas | Task
Write a program that outputs the lyrics of the Christmas carol The Twelve Days of Christmas.
The lyrics can be found here.
(You must reproduce the words in the correct order, but case, format, and punctuation are left to your discretion.)
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string Β (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff Β (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #jq | jq | [ "one", "two", "three", "four", "five", "six",
"seven", "eight", "nine", "ten", "eleven", "twelve"] as $cardinals
| [ "first", "second", "third", "fourth", "fifth", "sixth",
"seventh", "eighth", "ninth", "tenth", "eleventh", "twelfth"] as $ordinals
| [ "a partridge in a pear tree.", "turtle doves", "French hens",
"calling birds", "gold rings", "geese a-laying", "swans a-swimming",
"maids a-milking", "ladies dancing", "lords a-leaping", "pipers piping",
"drummers drumming" ] as $gifts
| range(12) | . as $i | $ordinals[$i] as $nth
| "On the " + $nth + " day of Christmas, my true love sent to me:\n" +
([[range($i+1)]|reverse[]|. as $j|$cardinals[$j] as $count|
if $j > 0 then $count else if $i > 0 then "and" else "" end end +
" " + $gifts[$j] + if $j > 0 then "," else "\n" end]
| join("\n"))
Β |
http://rosettacode.org/wiki/The_Twelve_Days_of_Christmas | The Twelve Days of Christmas | Task
Write a program that outputs the lyrics of the Christmas carol The Twelve Days of Christmas.
The lyrics can be found here.
(You must reproduce the words in the correct order, but case, format, and punctuation are left to your discretion.)
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string Β (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff Β (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Jsish | Jsish | #!/usr/bin/env jsish
"use strict";
Β
/* Twelve Days Of Christmas, in Jsish */
var days = [
'first', 'second', 'third', 'fourth', 'fifth', 'sixth', 'seventh', 'eighth', 'ninth',
'tenth', 'eleventh', 'twelfth'
];
Β
var gifts = [
"A partridge in a pear tree",
"Two turtle doves",
"Three french hens",
"Four calling birds",
"Five golden rings",
"Six geese a-laying",
"Seven swans a-swimming",
"Eight maids a-milking",
"Nine ladies dancing",
"Ten lords a-leaping",
"Eleven pipers piping",
"Twelve drummers drumming"
];
Β
var lines, verses = [], song;
Β
for ( var i = 0; i < 12; i++ ) {
lines = [];
lines[0] = "On the " + days[i] + " day of Christmas, my true love gave to me";
Β
var j = i + 1;
var k = 0;
while ( j-- > 0 )
lines[++k] = gifts[j];
Β
verses[i] = lines.join('\n');
Β
if ( i == 0 )
gifts[0] = "And a partridge in a pear tree";
}
Β
song = verses.join('\n\n');
;song;
Β
/*
=!EXPECTSTART!=
song ==> On the first day of Christmas, my true love gave to me
A partridge in a pear tree
Β
On the second day of Christmas, my true love gave to me
Two turtle doves
And a partridge in a pear tree
Β
On the third day of Christmas, my true love gave to me
Three french hens
Two turtle doves
And a partridge in a pear tree
Β
On the fourth day of Christmas, my true love gave to me
Four calling birds
Three french hens
Two turtle doves
And a partridge in a pear tree
Β
On the fifth day of Christmas, my true love gave to me
Five golden rings
Four calling birds
Three french hens
Two turtle doves
And a partridge in a pear tree
Β
On the sixth day of Christmas, my true love gave to me
Six geese a-laying
Five golden rings
Four calling birds
Three french hens
Two turtle doves
And a partridge in a pear tree
Β
On the seventh day of Christmas, my true love gave to me
Seven swans a-swimming
Six geese a-laying
Five golden rings
Four calling birds
Three french hens
Two turtle doves
And a partridge in a pear tree
Β
On the eighth day of Christmas, my true love gave to me
Eight maids a-milking
Seven swans a-swimming
Six geese a-laying
Five golden rings
Four calling birds
Three french hens
Two turtle doves
And a partridge in a pear tree
Β
On the ninth day of Christmas, my true love gave to me
Nine ladies dancing
Eight maids a-milking
Seven swans a-swimming
Six geese a-laying
Five golden rings
Four calling birds
Three french hens
Two turtle doves
And a partridge in a pear tree
Β
On the tenth day of Christmas, my true love gave to me
Ten lords a-leaping
Nine ladies dancing
Eight maids a-milking
Seven swans a-swimming
Six geese a-laying
Five golden rings
Four calling birds
Three french hens
Two turtle doves
And a partridge in a pear tree
Β
On the eleventh day of Christmas, my true love gave to me
Eleven pipers piping
Ten lords a-leaping
Nine ladies dancing
Eight maids a-milking
Seven swans a-swimming
Six geese a-laying
Five golden rings
Four calling birds
Three french hens
Two turtle doves
And a partridge in a pear tree
Β
On the twelfth day of Christmas, my true love gave to me
Twelve drummers drumming
Eleven pipers piping
Ten lords a-leaping
Nine ladies dancing
Eight maids a-milking
Seven swans a-swimming
Six geese a-laying
Five golden rings
Four calling birds
Three french hens
Two turtle doves
And a partridge in a pear tree
=!EXPECTEND!=
*/ |
http://rosettacode.org/wiki/Terminal_control/Coloured_text | Terminal control/Coloured text | Task
Display a word in various colours on the terminal.
The system palette, or colours such as Red, Green, Blue, Magenta, Cyan, and Yellow can be used.
Optionally demonstrate:
How the system should determine if the terminal supports colour
Setting of the background colour
How to cause blinking or flashing (if supported by the terminal)
| #Python | Python | Β
from colorama import init, Fore, Back, Style
init(autoreset=True)
Β
print Fore.RED + "FATAL ERROR! Cannot write to /boot/vmlinuz-3.2.0-33-generic"
print Back.BLUE + Fore.YELLOW + "What a cute console!"
print "This is anΒ %simportant%s word"Β % (Style.BRIGHT, Style.NORMAL)
print Fore.YELLOW + "Rosetta Code!"
print Fore.CYAN + "Rosetta Code!"
print Fore.GREEN + "Rosetta Code!"
print Fore.MAGENTA + "Rosetta Code!"
print Back.YELLOW + Fore.BLUE + Style.BRIGHT + " " * 40 + " == Good Bye!"
Β |
http://rosettacode.org/wiki/Terminal_control/Coloured_text | Terminal control/Coloured text | Task
Display a word in various colours on the terminal.
The system palette, or colours such as Red, Green, Blue, Magenta, Cyan, and Yellow can be used.
Optionally demonstrate:
How the system should determine if the terminal supports colour
Setting of the background colour
How to cause blinking or flashing (if supported by the terminal)
| #Racket | Racket | Β
#lang racket
Β
;; Utility interfaces to the low-level command
(define (capability? cap) (system (~a "tput "cap" > /dev/null 2>&1")))
(define (tput . xs) (system (apply ~a 'tput " " (add-between xs " "))) (void))
(define (colorterm?) (and (capability? 'setaf) (capability? 'setab)))
(define color-map '([black 0] [red 1] [green 2] [yellow 3]
[blue 4] [magenta 5] [cyan 6] [white 7]))
(define (foreground color) (tput 'setaf (cadr (assq color color-map))))
(define (background color) (tput 'setab (cadr (assq color color-map))))
(define (reset) (tput 'sgr0) (void))
Β
;; Demonstration of use
(if (colorterm?)
(begin (foreground 'blue)
(background 'yellow)
(displayln "Color output")
(reset))
(displayln "Monochrome only"))
(if (capability? 'blink)
(begin (tput 'blink)
(displayln "Blinking output")
(reset))
(displayln "Steady only"))
Β |
http://rosettacode.org/wiki/Terminal_control/Coloured_text | Terminal control/Coloured text | Task
Display a word in various colours on the terminal.
The system palette, or colours such as Red, Green, Blue, Magenta, Cyan, and Yellow can be used.
Optionally demonstrate:
How the system should determine if the terminal supports colour
Setting of the background colour
How to cause blinking or flashing (if supported by the terminal)
| #Raku | Raku | use Terminal::ANSIColor;
Β
say colored('RED ON WHITE', 'bold red on_white');
say colored('GREEN', 'bold green');
say colored('BLUE ON YELLOW', 'bold blue on_yellow');
say colored('MAGENTA', 'bold magenta');
say colored('CYAN ON RED', 'bold cyan on_red');
say colored('YELLOW', 'bold yellow'); |
http://rosettacode.org/wiki/Synchronous_concurrency | Synchronous concurrency | The goal of this task is to create two concurrent activities ("Threads" or "Tasks", not processes.) that share data synchronously. Your language may provide syntax or libraries to perform concurrency. Different languages provide different implementations of concurrency, often with different names. Some languages use the term threads, others use the term tasks, while others use co-processes. This task should not be implemented using fork, spawn, or the Linux/UNIX/Win32 pipe command, as communication should be between threads, not processes.
One of the concurrent units will read from a file named "input.txt" and send the contents of that file, one line at a time, to the other concurrent unit, which will print the line it receives to standard output. The printing unit must count the number of lines it prints. After the concurrent unit reading the file sends its last line to the printing unit, the reading unit will request the number of lines printed by the printing unit. The reading unit will then print the number of lines printed by the printing unit.
This task requires two-way communication between the concurrent units. All concurrent units must cleanly terminate at the end of the program.
| #Delphi | Delphi | Β
program Project2;
Β
{$APPTYPE CONSOLE}
Β
uses
SysUtils, Classes, Windows;
Β
type
EThreadStackFinalized = class(Exception);
Β
PLine = ^TLine;
TLine = record
Text: string;
end;
Β
TThreadQueue = class
private
FFinalized: Boolean;
FQueue: THandle;
public
constructor Create;
destructor Destroy; override;
procedure Finalize;
procedure Push(Data: Pointer);
function Pop(var Data: Pointer): Boolean;
property Finalized: Boolean read FFinalized;
end;
Β
TPrintThread = class(TThread)
private
FCount: Integer;
FTreminateEvent: THandle;
FDoneEvent: THandle;
FQueue: TThreadQueue;
public
constructor Create(aTreminateEvent, aDoneEvent: THandle; aQueue: TThreadQueue);
procedure Execute; override;
Β
property Count: Integer read FCount;
end;
Β
{ TThreadQueue }
Β
constructor TThreadQueue.Create;
begin
FQueue := CreateIOCompletionPort(INVALID_HANDLE_VALUE, 0, 0, 0);
FFinalized := False;
end;
Β
destructor TThreadQueue.Destroy;
begin
if FQueue <> 0 then
CloseHandle(FQueue);
inherited;
end;
Β
procedure TThreadQueue.Finalize;
begin
PostQueuedCompletionStatus(FQueue, 0, 0, Pointer($FFFFFFFF));
FFinalized := True;
end;
Β
function TThreadQueue.Pop(var Data: Pointer): Boolean;
var
A: Cardinal;
OL: POverLapped;
begin
Result := True;
if not FFinalized then
GetQueuedCompletionStatus(FQueue, A, Cardinal(Data), OL, INFINITE);
Β
if FFinalized or (OL = Pointer($FFFFFFFF)) then begin
Data := nil;
Result := False;
Finalize;
end;
end;
Β
procedure TThreadQueue.Push(Data: Pointer);
begin
if FFinalized then
raise EThreadStackFinalized.Create('Stack is finalized');
Β
PostQueuedCompletionStatus(FQueue, 0, Cardinal(Data), nil);
end;
Β
{ TPrintThread }
Β
constructor TPrintThread.Create(aTreminateEvent, aDoneEvent: THandle; aQueue: TThreadQueue);
begin
inherited Create(True);
FCount := 0;
FreeOnTerminate := True;
FTreminateEvent := aTreminateEvent;
FDoneEvent := aDoneEvent;
FQueue := aQueue;
end;
Β
procedure TPrintThread.Execute;
var
data: Pointer;
line: PLine;
begin
repeat
if FQueue.Pop(data) then begin
line := data;
try
Writeln(line^.Text);
if line^.Text = #0 then
SetEvent(FDoneEvent);
Inc(FCount);
finally
Dispose(line);
end;
end;
Β
until False;
WaitForSingleObject(FTreminateEvent, INFINITE);
end;
Β
var
PrintThread: TPrintThread;
Queue: TThreadQueue;
lines: TStrings;
i: Integer;
line: PLine;
TreminateEvent, DoneEvent: THandle;
begin
Queue := TThreadQueue.Create;
try
TreminateEvent := CreateEvent(nil, False, False, 'TERMINATE_EVENT');
DoneEvent := CreateEvent(nil, False, False, 'DONE_EVENT');
try
PrintThread := TPrintThread.Create(TreminateEvent, DoneEvent, Queue);
PrintThread.Start;
lines := TStringList.Create;
try
lines.LoadFromFile('input.txt');
for i := 0 to lines.Count - 1 do begin
New(line);
line^.Text := lines[i];
Queue.Push(line);
end;
Β
New(line);
line^.Text := #0;
Queue.Push(line);
Β
WaitForSingleObject(DoneEvent, INFINITE);
Β
New(line);
line^.Text := IntToStr(PrintThread.Count);
Queue.Push(line);
Β
SetEvent(TreminateEvent);
finally
lines.Free;
end;
finally
CloseHandle(TreminateEvent);
CloseHandle(DoneEvent)
end;
Β
Readln;
finally
Queue.Free;
end;
end.
Β |
http://rosettacode.org/wiki/Table_creation/Postal_addresses | Table creation/Postal addresses | Task
Create a table to store addresses.
You may assume that all the addresses to be stored will be located in the USA. Β As such, you will need (in addition to a field holding a unique identifier) a field holding the street address, a field holding the city, a field holding the state code, and a field holding the zipcode. Β Choose appropriate types for each field.
For non-database languages, show how you would open a connection to a database (your choice of which) and create an address table in it. You should follow the existing models here for how you would structure the table.
| #Phix | Phix | without js -- (file i/o)
include pSQLite.e
constant sqlcode = """
CREATE TABLE address (
addrID INTEGER PRIMARY KEY AUTOINCREMENT,
addrStreet TEXT NOT NULL,
addrCity TEXT NOT NULL,
addrState TEXT NOT NULL,
addrZIP TEXT NOT NULL)"""
sqlite3 db = sqlite3_open("address.sqlite")
integer res = sqlite3_exec(db,sqlcode)
if res=SQLITE_OK then
sqlite3_close(db)
else
-- can show eg "sqlite3_exec error: 1 [table address already exists]"
printf(1,"sqlite3_exec error:Β %d [%s]\n",{res,sqlite_last_exec_err})
end if
|
http://rosettacode.org/wiki/Table_creation/Postal_addresses | Table creation/Postal addresses | Task
Create a table to store addresses.
You may assume that all the addresses to be stored will be located in the USA. Β As such, you will need (in addition to a field holding a unique identifier) a field holding the street address, a field holding the city, a field holding the state code, and a field holding the zipcode. Β Choose appropriate types for each field.
For non-database languages, show how you would open a connection to a database (your choice of which) and create an address table in it. You should follow the existing models here for how you would structure the table.
| #PHP.2BSQLite | PHP+SQLite | <?php
$db = new SQLite3(':memory:');
$db->exec("
CREATE TABLE address (
addrID INTEGER PRIMARY KEY AUTOINCREMENT,
addrStreet TEXT NOT NULL,
addrCity TEXT NOT NULL,
addrState TEXT NOT NULL,
addrZIP TEXT NOT NULL
)
");
?> |
http://rosettacode.org/wiki/Table_creation/Postal_addresses | Table creation/Postal addresses | Task
Create a table to store addresses.
You may assume that all the addresses to be stored will be located in the USA. Β As such, you will need (in addition to a field holding a unique identifier) a field holding the street address, a field holding the city, a field holding the state code, and a field holding the zipcode. Β Choose appropriate types for each field.
For non-database languages, show how you would open a connection to a database (your choice of which) and create an address table in it. You should follow the existing models here for how you would structure the table.
| #PicoLisp | PicoLisp | (class +Adr +Entity)
(rel nm (+Sn +Idx +String)) # Name [Soundex index]
(rel str (+String)) # Street
(rel zip (+Ref +String)) # ZIP [Non-unique index]
(rel cit (+Fold +Idx +String)) # City [Folded substring index]
(rel st (+String)) # State
(rel tel (+Fold +Ref +String)) # Phone [Folded non-unique index]
(rel em (+Ref +String)) # EMail [Non-unique index]
(rel txt (+Blob)) # Memo
(rel jpg (+Blob)) # Photo
Β
(pool "address.db") # Create database |
http://rosettacode.org/wiki/Sutherland-Hodgman_polygon_clipping | Sutherland-Hodgman polygon clipping | The Β Sutherland-Hodgman clipping algorithm Β finds the polygon that is the intersection between an arbitrary polygon (the βsubject polygonβ) and a convex polygon (the βclip polygonβ).
It is used in computer graphics (especially 2D graphics) to reduce the complexity of a scene being displayed by eliminating parts of a polygon that do not need to be displayed.
Task
Take the closed polygon defined by the points:
[
(
50
,
150
)
,
(
200
,
50
)
,
(
350
,
150
)
,
(
350
,
300
)
,
(
250
,
300
)
,
(
200
,
250
)
,
(
150
,
350
)
,
(
100
,
250
)
,
(
100
,
200
)
]
{\displaystyle [(50,150),(200,50),(350,150),(350,300),(250,300),(200,250),(150,350),(100,250),(100,200)]}
and clip it by the rectangle defined by the points:
[
(
100
,
100
)
,
(
300
,
100
)
,
(
300
,
300
)
,
(
100
,
300
)
]
{\displaystyle [(100,100),(300,100),(300,300),(100,300)]}
Print the sequence of points that define the resulting clipped polygon.
Extra credit
Display all three polygons on a graphical surface, using a different color for each polygon and filling the resulting polygon.
(When displaying you may use either a north-west or a south-west origin, whichever is more convenient for your display mechanism.)
| #C | C | #include <stdio.h>
#include <stdlib.h>
#include <math.h>
Β
typedef struct { double x, y; } vec_t, *vec;
Β
inline double dot(vec a, vec b)
{
return a->x * b->x + a->y * b->y;
}
Β
inline double cross(vec a, vec b)
{
return a->x * b->y - a->y * b->x;
}
Β
inline vec vsub(vec a, vec b, vec res)
{
res->x = a->x - b->x;
res->y = a->y - b->y;
return res;
}
Β
/* tells if vec c lies on the left side of directed edge a->b
* 1 if left, -1 if right, 0 if colinear
*/
int left_of(vec a, vec b, vec c)
{
vec_t tmp1, tmp2;
double x;
vsub(b, a, &tmp1);
vsub(c, b, &tmp2);
x = cross(&tmp1, &tmp2);
return x < 0 ? -1 : x > 0;
}
Β
int line_sect(vec x0, vec x1, vec y0, vec y1, vec res)
{
vec_t dx, dy, d;
vsub(x1, x0, &dx);
vsub(y1, y0, &dy);
vsub(x0, y0, &d);
/* x0 + a dx = y0 + b dy ->
x0 X dx = y0 X dx + b dy X dx ->
b = (x0 - y0) X dx / (dy X dx) */
double dyx = cross(&dy, &dx);
if (!dyx) return 0;
dyx = cross(&d, &dx) / dyx;
if (dyx <= 0 || dyx >= 1) return 0;
Β
res->x = y0->x + dyx * dy.x;
res->y = y0->y + dyx * dy.y;
return 1;
}
Β
/* === polygon stuff === */
typedef struct { int len, alloc; vec v; } poly_t, *poly;
Β
poly poly_new()
{
return (poly)calloc(1, sizeof(poly_t));
}
Β
void poly_free(poly p)
{
free(p->v);
free(p);
}
Β
void poly_append(poly p, vec v)
{
if (p->len >= p->alloc) {
p->alloc *= 2;
if (!p->alloc) p->alloc = 4;
p->v = (vec)realloc(p->v, sizeof(vec_t) * p->alloc);
}
p->v[p->len++] = *v;
}
Β
/* this works only if all of the following are true:
* 1. poly has no colinear edges;
* 2. poly has no duplicate vertices;
* 3. poly has at least three vertices;
* 4. poly is convex (implying 3).
*/
int poly_winding(poly p)
{
return left_of(p->v, p->v + 1, p->v + 2);
}
Β
void poly_edge_clip(poly sub, vec x0, vec x1, int left, poly res)
{
int i, side0, side1;
vec_t tmp;
vec v0 = sub->v + sub->len - 1, v1;
res->len = 0;
Β
side0 = left_of(x0, x1, v0);
if (side0 != -left) poly_append(res, v0);
Β
for (i = 0; i < sub->len; i++) {
v1 = sub->v + i;
side1 = left_of(x0, x1, v1);
if (side0 + side1 == 0 && side0)
/* last point and current straddle the edge */
if (line_sect(x0, x1, v0, v1, &tmp))
poly_append(res, &tmp);
if (i == sub->len - 1) break;
if (side1 != -left) poly_append(res, v1);
v0 = v1;
side0 = side1;
}
}
Β
poly poly_clip(poly sub, poly clip)
{
int i;
poly p1 = poly_new(), p2 = poly_new(), tmp;
Β
int dir = poly_winding(clip);
poly_edge_clip(sub, clip->v + clip->len - 1, clip->v, dir, p2);
for (i = 0; i < clip->len - 1; i++) {
tmp = p2; p2 = p1; p1 = tmp;
if(p1->len == 0) {
p2->len = 0;
break;
}
poly_edge_clip(p1, clip->v + i, clip->v + i + 1, dir, p2);
}
Β
poly_free(p1);
return p2;
}
Β
int main()
{
int i;
vec_t c[] = {{100,100}, {300,100}, {300,300}, {100,300}};
//vec_t c[] = {{100,300}, {300,300}, {300,100}, {100,100}};
vec_t s[] = { {50,150}, {200,50}, {350,150},
{350,300},{250,300},{200,250},
{150,350},{100,250},{100,200}};
#define clen (sizeof(c)/sizeof(vec_t))
#define slen (sizeof(s)/sizeof(vec_t))
poly_t clipper = {clen, 0, c};
poly_t subject = {slen, 0, s};
Β
poly res = poly_clip(&subject, &clipper);
Β
for (i = 0; i < res->len; i++)
printf("%gΒ %g\n", res->v[i].x, res->v[i].y);
Β
/* long and arduous EPS printout */
FILE * eps = fopen("test.eps", "w");
fprintf(eps, "%%!PS-Adobe-3.0\n%%%%BoundingBox: 40 40 360 360\n"
"/l {lineto} def /m{moveto} def /s{setrgbcolor} def"
"/c {closepath} def /gs {fill grestore stroke} def\n");
fprintf(eps, "0 setlinewidthΒ %gΒ %g m ", c[0].x, c[0].y);
for (i = 1; i < clen; i++)
fprintf(eps, "%gΒ %g l ", c[i].x, c[i].y);
fprintf(eps, "c .5 0 0 s gsave 1 .7 .7 s gs\n");
Β
fprintf(eps, "%gΒ %g m ", s[0].x, s[0].y);
for (i = 1; i < slen; i++)
fprintf(eps, "%gΒ %g l ", s[i].x, s[i].y);
fprintf(eps, "c 0 .2 .5 s gsave .4 .7 1 s gs\n");
Β
fprintf(eps, "2 setlinewidth [10 8] 0 setdashΒ %gΒ %g m ",
res->v[0].x, res->v[0].y);
for (i = 1; i < res->len; i++)
fprintf(eps, "%gΒ %g l ", res->v[i].x, res->v[i].y);
fprintf(eps, "c .5 0 .5 s gsave .7 .3 .8 s gs\n");
Β
fprintf(eps, "%%%%EOF");
fclose(eps);
printf("test.eps written\n");
Β
return 0;
} |
http://rosettacode.org/wiki/Symmetric_difference | Symmetric difference | Task
Given two sets A and B, compute
(
A
β
B
)
βͺ
(
B
β
A
)
.
{\displaystyle (A\setminus B)\cup (B\setminus A).}
That is, enumerate the items that are in A or B but not both. This set is called the symmetric difference of A and B.
In other words:
(
A
βͺ
B
)
β
(
A
β©
B
)
{\displaystyle (A\cup B)\setminus (A\cap B)}
(the set of items that are in at least one of A or B minus the set of items that are in both A and B).
Optionally, give the individual differences (
A
β
B
{\displaystyle A\setminus B}
and
B
β
A
{\displaystyle B\setminus A}
) as well.
Test cases
A = {John, Bob, Mary, Serena}
B = {Jim, Mary, John, Bob}
Notes
If your code uses lists of items to represent sets then ensure duplicate items in lists are correctly handled. For example two lists representing sets of a = ["John", "Serena", "Bob", "Mary", "Serena"] and b = ["Jim", "Mary", "John", "Jim", "Bob"] should produce the result of just two strings: ["Serena", "Jim"], in any order.
In the mathematical notation above A \ B gives the set of items in A that are not in B; A βͺ B gives the set of items in both A and B, (their union); and A β© B gives the set of items that are in both A and B (their intersection).
| #ALGOL_68 | ALGOL 68 | # symetric difference using associative arrays to represent the sets #
# include the associative array code for string keys and values #
PR read "aArray.a68" PR
Β
# adds the elements of s to the associative array a, #
# the elements will have empty strings for values #
OP // = ( REF AARRAY a, []STRING s )REF AARRAY:
BEGIN
FOR s pos FROM LWB s TO UPB s DO
a // s[ s pos ] := ""
OD;
a
END # // # ;
# returns an AARRAY containing the elements of a that aren't in b #
OP - = ( REF AARRAY a, REF AARRAY b )REF AARRAY:
BEGIN
REF AARRAY result := INIT HEAP AARRAY;
REF AAELEMENT e := FIRST a;
WHILE e ISNT nil element DO
IF NOT ( b CONTAINSKEY key OF e ) THEN
result // key OF e := value OF e
FI;
e := NEXT a
OD;
result
END # - # ;
# returns an AARRAY containing the elements of a and those of b #
# i.e. in set terms a UNION b #
OP + = ( REF AARRAY a, REF AARRAY b )REF AARRAY:
BEGIN
REF AARRAY result := INIT HEAP AARRAY;
REF AAELEMENT e := FIRST a;
WHILE e ISNT nil element DO
result // key OF e := value OF e;
e := NEXT a
OD;
e := FIRST b;
WHILE e ISNT nil element DO
result // key OF e := value OF e;
e := NEXT b
OD;
result
END # + # ;
# construct the associative arrays for the task #
REF AARRAY a := INIT LOC AARRAY;
REF AARRAY b := INIT LOC AARRAY;
a // []STRING( "John", "Bob", "Mary", "Serena" );
b // []STRING( "Jim", "Mary", "John", "Bob" );
# find and show the symetric difference of a and b #
REF AARRAY c := ( a - b ) + ( b - a );
REF AAELEMENT e := FIRST c;
WHILE e ISNT nil element DO
print( ( " ", key OF e ) );
e := NEXT c
OD;
print( ( newline ) ) |
http://rosettacode.org/wiki/Super-d_numbers | Super-d numbers | A super-d number is a positive, decimal (base ten) integer Β n Β such that Β d Γ nd Β has at least Β d Β consecutive digits Β d Β where
2 β€ d β€ 9
For instance, 753 is a super-3 number because 3 Γ 7533 = 1280873331.
Super-d Β numbers are also shown on Β MathWorldβ’ Β as Β super-d Β or Β super-d.
Task
Write a function/procedure/routine to find super-d numbers.
For Β d=2 Β through Β d=6, Β use the routine to show the first Β 10 Β super-d numbers.
Extra credit
Show the first Β 10 Β super-7, super-8, and/or super-9 numbers Β (optional).
See also
Β Wolfram MathWorld - Super-d Number.
Β OEIS: A014569 - Super-3 Numbers.
| #C.2B.2B | C++ | #include <iostream>
#include <sstream>
#include <vector>
Β
uint64_t ipow(uint64_t base, uint64_t exp) {
uint64_t result = 1;
while (exp) {
if (exp & 1) {
result *= base;
}
exp >>= 1;
base *= base;
}
return result;
}
Β
int main() {
using namespace std;
Β
vector<string> rd{ "22", "333", "4444", "55555", "666666", "7777777", "88888888", "999999999" };
Β
for (uint64_t ii = 2; ii < 5; ii++) {
cout << "First 10 super-" << ii << " numbers:\n";
int count = 0;
Β
for (uint64_t j = 3; /* empty */; j++) {
auto k = ii * ipow(j, ii);
auto kstr = to_string(k);
auto needle = rd[(size_t)(ii - 2)];
auto res = kstr.find(needle);
if (res != string::npos) {
count++;
cout << j << ' ';
if (count == 10) {
cout << "\n\n";
break;
}
}
}
}
Β
return 0;
}
Β |
http://rosettacode.org/wiki/Take_notes_on_the_command_line | Take notes on the command line | Take notes on the command line is part of Short Circuit's Console Program Basics selection.
Invoking NOTES without commandline arguments displays the current contents of the local NOTES.TXT if it exists.
If NOTES has arguments, the current date and time are appended to the local NOTES.TXT followed by a newline.
Then all the arguments, joined with spaces, prepended with a tab, and appended with a trailing newline, are written to NOTES.TXT.
If NOTES.TXT doesn't already exist in the current directory then a new NOTES.TXT file should be created.
| #Delphi | Delphi | program notes;
Β
{$APPTYPE CONSOLE}
Β
uses
Classes,
SysUtils,
IOUtils;
Β
const
FILENAME = 'NOTES.TXT';
TAB = #9;
Β
var
sw: TStreamWriter;
i : integer;
Β
begin
if ParamCount = 0 then
begin
if TFile.Exists(FILENAME) then
write(TFile.ReadAllText(FILENAME));
end
else
begin
if TFile.Exists(FILENAME) then
sw := TFile.AppendText(FILENAME)
else
sw := TFile.CreateText(FILENAME);
Β
sw.Write(FormatDateTime('yyyy-mm-dd hh:nn',Now));
sw.Write(TAB);
for i := 1 to ParamCount do
begin
sw.Write(ParamStr(i));
if i < ParamCount then
sw.Write(' ');
end;
sw.WriteLine;
sw.Free;
end;
end. |
http://rosettacode.org/wiki/Superellipse | Superellipse | A superellipse is a geometric figure defined as the set of all points (x, y) with
|
x
a
|
n
+
|
y
b
|
n
=
1
,
{\displaystyle \left|{\frac {x}{a}}\right|^{n}\!+\left|{\frac {y}{b}}\right|^{n}\!=1,}
where n, a, and b are positive numbers.
Task
Draw a superellipse with n = 2.5, and a = b = 200
| #AutoHotkey | AutoHotkey | n := 2.5
a := 200
b := 200
SuperEllipse(n, a, b)
return
Β
SuperEllipse(n, a, b){
global
pToken := Gdip_Startup()
Ο := 3.141592653589793, oCoord := [], oX := [], oY := []
nn := 2/n
loop 361
{
t := (A_Index-1) * Ο/180
; https://en.wikipedia.org/wiki/Superellipse
x := abs(cos(t))**nn * a * sgn(cos(t))
y := abs(sin(t))**nn * b * sgn(sin(t))
oCoord[A_Index] := [x, y]
oX[Floor(x)] := true, oY[Floor(y)] := true
}
dx := 0 - oX.MinIndex() + 10
dy := 0 - oY.MinIndex() + 10
w := oX.MaxIndex()-oX.MinIndex() + 20
h := oY.MaxIndex()-oY.MinIndex() + 20
Β
Gdip1(w, h)
pPen := Gdip_CreatePen("0xFF00FF00", 2)
for i, obj in oCoord
{
x2 := obj.1+dx, y2 := obj.2+dy
if i>1
Gdip_DrawLine(G, pPen, x1, y1, x2, y2)
x1 := x2, y1 := y2
}
UpdateLayeredWindow(hwnd, hdc)
}
;----------------------------------------------------------------
sgn(n){
return (n>0?1:n<0?-1:0)
}
;----------------------------------------------------------------
Gdip1(w:=0, h:=0){
global
w := wΒ ? wΒ : A_ScreenWidth
h := hΒ ? hΒ : A_ScreenHeight
x := A_ScreenWidth/2 - w/2
y := A_ScreenHeight/2 - h/2
Gui, gdip1: -Caption +E0x80000 +LastFound +OwnDialogs +Owner +AlwaysOnTop
Gui, gdip1: Show, w%w% h%h% x%x% y%y%
hwnd := WinExist()
hbm := CreateDIBSection(w, h)
hdc := CreateCompatibleDC()
obm := SelectObject(hdc, hbm)
G := Gdip_GraphicsFromHDC(hdc)
Gdip_SetSmoothingMode(G, 4)
pBrush := Gdip_BrushCreateSolid("0xFF000000")
Gdip_FillRoundedRectangle(G, pBrush, 0, 0, w, h, 5)
Gdip_DeleteBrush(pBrush)
UpdateLayeredWindow(hwnd, hdc)
OnMessage(0x201, "WM_LBUTTONDOWN")
}
;----------------------------------------------------------------
Gdip2(){
global
SelectObject(hdc, obm)
DeleteObject(hbm)
DeleteDC(hdc)
Gdip_DeleteGraphics(G)
Gdip_Shutdown(pToken)
}
;----------------------------------------------------------------
WM_LBUTTONDOWN(){
PostMessage, 0xA1, 2
}
;----------------------------------------------------------------
Exit:
gdip2()
ExitApp
Return
;---------------------------------------------------------------- |
http://rosettacode.org/wiki/Sylvester%27s_sequence | Sylvester's sequence |
This page uses content from Wikipedia. The original article was at Sylvester's sequence. 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)
In number theory, Sylvester's sequence is an integer sequence in which each term of the sequence is the product of the previous terms, plus one.
Its values grow doubly exponentially, and the sum of its reciprocals forms a series of unit fractions that converges to 1 more rapidly than any other series of unit fractions with the same number of terms.
Further, the sum of the first k terms of the infinite series of reciprocals provides the closest possible underestimate of 1 by any k-term Egyptian fraction.
Task
Write a routine (function, procedure, generator, whatever) to calculate Sylvester's sequence.
Use that routine to show the values of the first 10 elements in the sequence.
Show the sum of the reciprocals of the first 10 elements on the sequence, ideally as an exact fraction.
Related tasks
Egyptian fractions
Harmonic series
See also
OEIS A000058 - Sylvester's sequence
| #Go | Go | package main
Β
import (
"fmt"
"math/big"
)
Β
func main() {
one := big.NewInt(1)
two := big.NewInt(2)
next := new(big.Int)
sylvester := []*big.Int{two}
prod := new(big.Int).Set(two)
count := 1
for count < 10 {
next.Add(prod, one)
sylvester = append(sylvester, new(big.Int).Set(next))
count++
prod.Mul(prod, next)
}
fmt.Println("The first 10 terms in the Sylvester sequence are:")
for i := 0; i < 10; i++ {
fmt.Println(sylvester[i])
}
Β
sumRecip := new(big.Rat)
for _, s := range sylvester {
sumRecip.Add(sumRecip, new(big.Rat).SetFrac(one, s))
}
fmt.Println("\nThe sum of their reciprocals as a rational number is:")
fmt.Println(sumRecip)
fmt.Println("\nThe sum of their reciprocals as a decimal number (to 211 places) is:")
fmt.Println(sumRecip.FloatString(211))
} |
http://rosettacode.org/wiki/Sylvester%27s_sequence | Sylvester's sequence |
This page uses content from Wikipedia. The original article was at Sylvester's sequence. 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)
In number theory, Sylvester's sequence is an integer sequence in which each term of the sequence is the product of the previous terms, plus one.
Its values grow doubly exponentially, and the sum of its reciprocals forms a series of unit fractions that converges to 1 more rapidly than any other series of unit fractions with the same number of terms.
Further, the sum of the first k terms of the infinite series of reciprocals provides the closest possible underestimate of 1 by any k-term Egyptian fraction.
Task
Write a routine (function, procedure, generator, whatever) to calculate Sylvester's sequence.
Use that routine to show the values of the first 10 elements in the sequence.
Show the sum of the reciprocals of the first 10 elements on the sequence, ideally as an exact fraction.
Related tasks
Egyptian fractions
Harmonic series
See also
OEIS A000058 - Sylvester's sequence
| #Haskell | Haskell | sylvester :: [Integer]
sylvester = map s [0 ..]
where
s 0 = 2
s n = succ $ foldr ((*) . s) 1 [0 .. pred n]
Β
main :: IO ()
main = do
putStrLn "First 10 elements of Sylvester's sequence:"
putStr $ unlines $ map show $ take 10 sylvester
Β
putStr "\nSum of reciprocals by sum over map: "
print $ sum $ map ((1 /) . fromInteger) $ take 10 sylvester
Β
putStr "Sum of reciprocals by fold: "
print $ foldr ((+) . (1 /) . fromInteger) 0 $ take 10 sylvester |
http://rosettacode.org/wiki/Taxicab_numbers | Taxicab numbers |
A Β taxicab number Β (the definition that is being used here) Β is a positive integer that can be expressed as the sum of two positive cubes in more than one way.
The first taxicab number is Β 1729, Β which is:
13 Β + Β 123 Β Β Β and also
93 Β + Β 103.
Taxicab numbers are also known as:
Β taxi numbers
Β taxi-cab numbers
Β taxi cab numbers
Β Hardy-Ramanujan numbers
Task
Compute and display the lowest 25 taxicab numbers (in numeric order, and in a human-readable format).
For each of the taxicab numbers, show the number as well as it's constituent cubes.
Extra credit
Show the 2,000th taxicab number, and a half dozen more
See also
A001235: taxicab numbers on The On-Line Encyclopedia of Integer Sequences.
Hardy-Ramanujan Number on MathWorld.
taxicab number on MathWorld.
taxicab number on Wikipedia Β (includes the story on how taxi-cab numbers came to be called).
| #J | J | cubes=: 3^~1+i.100 NB. first 100 cubes
triples=: /:~ ~. ,/ (+ , /:~@,)"0/~cubes NB. ordered pairs of cubes (each with their sum)
candidates=:Β ;({."#. <@(0&#`({.@{.(;,)<@}."1)@.(1<#))/. ])triples
Β
NB. we just want the first 25 taxicab numbers
25{.(,.~ <@>:@i.@#) candidates
ββββ¬βββββββ¬βββββββββββββ¬ββββββββββββββ
β1 β1729 β1 1728 β729 1000 β
ββββΌβββββββΌβββββββββββββΌββββββββββββββ€
β2 β4104 β8 4096 β729 3375 β
ββββΌβββββββΌβββββββββββββΌββββββββββββββ€
β3 β13832 β8 13824 β5832 8000 β
ββββΌβββββββΌβββββββββββββΌββββββββββββββ€
β4 β20683 β1000 19683 β6859 13824 β
ββββΌβββββββΌβββββββββββββΌββββββββββββββ€
β5 β32832 β64 32768 β5832 27000 β
ββββΌβββββββΌβββββββββββββΌββββββββββββββ€
β6 β39312 β8 39304 β3375 35937 β
ββββΌβββββββΌβββββββββββββΌββββββββββββββ€
β7 β40033 β729 39304 β4096 35937 β
ββββΌβββββββΌβββββββββββββΌββββββββββββββ€
β8 β46683 β27 46656 β19683 27000 β
ββββΌβββββββΌβββββββββββββΌββββββββββββββ€
β9 β64232 β4913 59319 β17576 46656 β
ββββΌβββββββΌβββββββββββββΌββββββββββββββ€
β10β65728 β1728 64000 β29791 35937 β
ββββΌβββββββΌβββββββββββββΌββββββββββββββ€
β11β110656β64 110592 β46656 64000 β
ββββΌβββββββΌβββββββββββββΌββββββββββββββ€
β12β110808β216 110592 β19683 91125 β
ββββΌβββββββΌβββββββββββββΌββββββββββββββ€
β13β134379β1728 132651 β54872 79507 β
ββββΌβββββββΌβββββββββββββΌββββββββββββββ€
β14β149389β512 148877 β24389 125000 β
ββββΌβββββββΌβββββββββββββΌββββββββββββββ€
β15β165464β8000 157464 β54872 110592 β
ββββΌβββββββΌβββββββββββββΌββββββββββββββ€
β16β171288β4913 166375 β13824 157464 β
ββββΌβββββββΌβββββββββββββΌββββββββββββββ€
β17β195841β729 195112 β10648 185193 β
ββββΌβββββββΌβββββββββββββΌββββββββββββββ€
β18β216027β27 216000 β10648 205379 β
ββββΌβββββββΌβββββββββββββΌββββββββββββββ€
β19β216125β125 216000 β91125 125000 β
ββββΌβββββββΌβββββββββββββΌββββββββββββββ€
β20β262656β512 262144 β46656 216000 β
ββββΌβββββββΌβββββββββββββΌββββββββββββββ€
β21β314496β64 314432 β27000 287496 β
ββββΌβββββββΌβββββββββββββΌββββββββββββββ€
β22β320264β5832 314432 β32768 287496 β
ββββΌβββββββΌβββββββββββββΌββββββββββββββ€
β23β327763β27000 300763β132651 195112β
ββββΌβββββββΌβββββββββββββΌββββββββββββββ€
β24β373464β216 373248 β157464 216000β
ββββΌβββββββΌβββββββββββββΌββββββββββββββ€
β25β402597β74088 328509β175616 226981β
ββββ΄βββββββ΄βββββββββββββ΄ββββββββββββββ |
http://rosettacode.org/wiki/Superpermutation_minimisation | Superpermutation minimisation | A superpermutation of N different characters is a string consisting of an arrangement of multiple copies of those N different characters in which every permutation of those characters can be found as a substring.
For example, representing the characters as A..Z, using N=2 we choose to use the first two characters 'AB'.
The permutations of 'AB' are the two, (i.e. two-factorial), strings: 'AB' and 'BA'.
A too obvious method of generating a superpermutation is to just join all the permutations together forming 'ABBA'.
A little thought will produce the shorter (in fact the shortest) superpermutation of 'ABA' - it contains 'AB' at the beginning and contains 'BA' from the middle to the end.
The "too obvious" method of creation generates a string of length N!*N. Using this as a yardstick, the task is to investigate other methods of generating superpermutations of N from 1-to-7 characters, that never generate larger superpermutations.
Show descriptions and comparisons of algorithms used here, and select the "Best" algorithm as being the one generating shorter superpermutations.
The problem of generating the shortest superpermutation for each N might be NP complete, although the minimal strings for small values of N have been found by brute -force searches.
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
Reference
The Minimal Superpermutation Problem. by Nathaniel Johnston.
oeis A180632 gives 0-5 as 0, 1, 3, 9, 33, 153. 6 is thought to be 872.
Superpermutations - Numberphile. A video
Superpermutations: the maths problem solved by 4chan - Standupmaths. A video of recent (2018) mathematical progress.
New Superpermutations Discovered! Standupmaths & Numberphile.
| #Elixir | Elixir | defmodule Superpermutation do
def minimisation(1), do: [1]
def minimisation(n) do
Enum.chunk(minimisation(n-1), n-1, 1)
|> Enum.reduce({[],nil}, fn sub,{acc,last} ->
if Enum.uniq(sub) == sub do
i = if acc==[], do: 0, else: Enum.find_index(sub, &(&1==last)) + 1
{acc ++ (Enum.drop(sub,i) ++ [n] ++ sub), List.last(sub)}
else
{acc, last}
end
end)
|> elem(0)
end
end
Β
to_s = fn list -> Enum.map_join(list, &Integer.to_string(&1,16)) end
Enum.each(1..8, fn n ->
result = Superpermutation.minimisation(n)
Β :io.format "~3w: len =~8wΒ : ", [n, length(result)]
IO.puts if n<5, do: Enum.join(result),
else: to_s.(Enum.take(result,20)) <> "...." <> to_s.(Enum.slice(result,-20..-1))
end) |
http://rosettacode.org/wiki/Superpermutation_minimisation | Superpermutation minimisation | A superpermutation of N different characters is a string consisting of an arrangement of multiple copies of those N different characters in which every permutation of those characters can be found as a substring.
For example, representing the characters as A..Z, using N=2 we choose to use the first two characters 'AB'.
The permutations of 'AB' are the two, (i.e. two-factorial), strings: 'AB' and 'BA'.
A too obvious method of generating a superpermutation is to just join all the permutations together forming 'ABBA'.
A little thought will produce the shorter (in fact the shortest) superpermutation of 'ABA' - it contains 'AB' at the beginning and contains 'BA' from the middle to the end.
The "too obvious" method of creation generates a string of length N!*N. Using this as a yardstick, the task is to investigate other methods of generating superpermutations of N from 1-to-7 characters, that never generate larger superpermutations.
Show descriptions and comparisons of algorithms used here, and select the "Best" algorithm as being the one generating shorter superpermutations.
The problem of generating the shortest superpermutation for each N might be NP complete, although the minimal strings for small values of N have been found by brute -force searches.
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
Reference
The Minimal Superpermutation Problem. by Nathaniel Johnston.
oeis A180632 gives 0-5 as 0, 1, 3, 9, 33, 153. 6 is thought to be 872.
Superpermutations - Numberphile. A video
Superpermutations: the maths problem solved by 4chan - Standupmaths. A video of recent (2018) mathematical progress.
New Superpermutations Discovered! Standupmaths & Numberphile.
| #FreeBASIC | FreeBASIC | ' version 28-06-2018
' compile with: fbc -s console
Β
Function superpermsize(n As UInteger) As UInteger
Β
Dim As UInteger x, y, sum, fac
For x = 1 To n
fac = 1
For y = 1 To x
fac *= y
Next
sum += fac
Next
Β
Function = sum
Β
End Function
Β
Function superperm(n As UInteger) As String
Β
If n = 1 Then Return "1"
Β
Dim As String sup_perm = "1", insert
Dim As String p, q()
Dim As UInteger a, b, i, l, x
Β
For x = 2 To n
insert = IIf(x < 10, Str(x), Chr(x + 55))
l = Len(sup_perm)
If l > 1 Then l = Len(sup_perm) - x +2
ReDim q(l)
For i = 1 To l
p = Mid(sup_perm, i, x -1)
If x > 2 Then
For a = 0 To Len(p) -2
For b = a+1 To Len(p) -1
If p[a] = p[b] Then Continue For, For, For
Next
Next
End If
q(i) = p + insert + p
Next
sup_perm = q(1)
For i = 2 To UBound(q)
a = x -1
Do
If Right(sup_perm, a) = Left(q(i), a) Then
sup_perm += Mid(q(i), a +1)
Exit Do
End If
a -= 1
Loop
Next
Next
Β
Function = sup_perm
Β
End Function
Β
' ------=< MAIN >=------
Β
Dim As String superpermutation
Dim As UInteger n
Β
For n = 1 To 10
superpermutation = superperm(n)
Print Using "### ######## ######## "; n; superpermsize(n); Len(superpermutation);
If n < 5 Then
Print superpermutation
Else
Print
End If
Next
Β
' empty keyboard buffer
While InKey <> ""Β : Wend
PrintΒ : Print "hit any key to end program"
Sleep
End |
http://rosettacode.org/wiki/Tau_number | Tau number | A Tau number is a positive integer divisible by the count of its positive divisors.
Task
Show the first Β 100 Β Tau numbers.
The numbers shall be generated during run-time (i.e. the code may not contain string literals, sets/arrays of integers, or alike).
Related task
Β Tau function
| #PILOT | PILOT | TΒ :1
CΒ :n=2
CΒ :seen=1
CΒ :max=100
*number
CΒ :c=1
CΒ :i=1
*divisor
C (n=i*(n/i)):c=c+1
CΒ :i=i+1
J (i<=n/2):*divisor
T (n=c*(n/c)):#n
C (n=c*(n/c)):seen=seen+1
CΒ :n=n+1
J (seen<max):*number
EΒ : |
http://rosettacode.org/wiki/Tau_number | Tau number | A Tau number is a positive integer divisible by the count of its positive divisors.
Task
Show the first Β 100 Β Tau numbers.
The numbers shall be generated during run-time (i.e. the code may not contain string literals, sets/arrays of integers, or alike).
Related task
Β Tau function
| #PL.2FM | PL/M | 100H:
BDOS: PROCEDURE (FN, ARG); DECLARE FN BYTE, ARG ADDRESS; GO TO 5; END BDOS;
EXIT: PROCEDURE; CALL BDOS(0,0); END EXIT;
PRINT: PROCEDURE (S); DECLARE S ADDRESS; CALL BDOS(9,S); END PRINT;
Β
/* PRINT NUMBER RIGHT-ALIGNED IN 7 POSITIONS */
PRINT$NUMBER: PROCEDURE (N);
DECLARE S (7) BYTE INITIAL (' .....$');
DECLARE N ADDRESS, I BYTE;
I = 6;
DIGIT:
I = I - 1;
S(I) = N MOD 10 + '0';
N = N / 10;
IF N > 0 THEN GO TO DIGIT;
DO WHILE I <> 0;
I = I - 1;
S(I) = ' ';
END;
CALL PRINT(.S);
END PRINT$NUMBER;
Β
/* COUNT AND STORE AMOUNT OF DIVISORS FOR 1..N AT VEC */
COUNT$DIVS: PROCEDURE (VEC, N);
DECLARE (VEC, N, V BASED VEC) ADDRESS;
DECLARE (I, J) ADDRESS;
Β
DO I=1 TO N;
V(I) = 1;
END;
Β
DO I=2 TO N;
J = I;
DO WHILE J <= N;
V(J) = V(J) + 1;
J = J + I;
END;
END;
END COUNT$DIVS;
Β
/* GIVEN VECTOR OF COUNT OF DIVISORS, SEE IF N IS A TAU NUMBER */
TAU: PROCEDURE (VEC, N) BYTE;
DECLARE (VEC, N, V BASED VEC) ADDRESS;
RETURN N MOD V(N) = 0;
END TAU;
Β
DECLARE AMOUNT LITERALLY '100';
DECLARE LIMIT LITERALLY '1100';
Β
DECLARE SEEN BYTE INITIAL (0);
DECLARE N ADDRESS INITIAL (1);
Β
CALL COUNT$DIVS(.MEMORY, LIMIT);
DO WHILE SEEN < AMOUNT;
IF TAU(.MEMORY, N) THEN DO;
CALL PRINT$NUMBER(N);
SEEN = SEEN + 1;
IF SEEN MOD 10 = 0 THEN CALL PRINT(.(13,10,'$'));
END;
N = N + 1;
END;
Β
CALL EXIT;
EOF |
http://rosettacode.org/wiki/Tau_number | Tau number | A Tau number is a positive integer divisible by the count of its positive divisors.
Task
Show the first Β 100 Β Tau numbers.
The numbers shall be generated during run-time (i.e. the code may not contain string literals, sets/arrays of integers, or alike).
Related task
Β Tau function
| #PureBasic | PureBasic | OpenConsole()
Β
Procedure.i numdiv(n)
c=2
For i=2 To (n+1)/2Β : If n%i=0Β : c+1Β : EndIfΒ : Next
ProcedureReturn c
EndProcedure
Β
Procedure.b istau(n)
If n=1Β : ProcedureReturn #TrueΒ : EndIf
If n%numdiv(n)=0Β : ProcedureReturn #TrueΒ : ElseΒ : ProcedureReturn #FalseΒ : EndIf
EndProcedure
Β
c=0Β : i=1
While c<100
If istau(i)Β : Print(RSet(Str(i),4)+#TAB$)Β : c+1Β : If c%10=0Β : PrintN("")Β : EndIf: EndIf
i+1
Wend
Β
Input() |
http://rosettacode.org/wiki/Teacup_rim_text | Teacup rim text | On a set of coasters we have, there's a picture of a teacup. Β On the rim of the teacup the word Β TEA Β appears a number of times separated by bullet characters Β (β’).
It occurred to me that if the bullet were removed and the words run together, Β you could start at any letter and still end up with a meaningful three-letter word.
So start at the Β T Β and read Β TEA. Β Start at the Β E Β and read Β EAT, Β or start at the Β A Β and read Β ATE.
That got me thinking that maybe there are other words that could be used rather that Β TEA. Β And that's just English. Β What about Italian or Greek or ... um ... Telugu.
For English, we will use the unixdict (now) located at: Β unixdict.txt.
(This will maintain continuity with other Rosetta Code tasks that also use it.)
Task
Search for a set of words that could be printed around the edge of a teacup. Β The words in each set are to be of the same length, that length being greater than two (thus precluding Β AH Β and Β HA, Β for example.)
Having listed a set, for example Β [ate tea eat], Β refrain from displaying permutations of that set, e.g.: Β [eat tea ate] Β etc.
The words should also be made of more than one letter Β (thus precluding Β III Β and Β OOO Β etc.)
The relationship between these words is (using ATE as an example) that the first letter of the first becomes the last letter of the second. Β The first letter of the second becomes the last letter of the third. Β So Β ATE Β becomes Β TEA Β and Β TEA Β becomes Β EAT.
All of the possible permutations, using this particular permutation technique, must be words in the list.
The set you generate for Β ATE Β will never included the word Β ETA Β as that cannot be reached via the first-to-last movement method.
Display one line for each set of teacup rim words.
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
| #Rust | Rust | use std::collections::BTreeSet;
use std::collections::HashSet;
use std::fs::File;
use std::io::{self, BufRead};
use std::iter::FromIterator;
Β
fn load_dictionary(filename: &str) -> std::io::Result<BTreeSet<String>> {
let file = File::open(filename)?;
let mut dict = BTreeSet::new();
for line in io::BufReader::new(file).lines() {
let word = line?;
dict.insert(word);
}
Ok(dict)
}
Β
fn find_teacup_words(dict: &BTreeSet<String>) {
let mut teacup_words: Vec<&String> = Vec::new();
let mut found: HashSet<&String> = HashSet::new();
for word in dict {
let len = word.len();
if len < 3 || found.contains(word) {
continue;
}
teacup_words.clear();
let mut is_teacup_word = true;
let mut chars: Vec<char> = word.chars().collect();
for _ in 1..len {
chars.rotate_left(1);
if let Some(w) = dict.get(&String::from_iter(&chars)) {
ifΒ !w.eq(word) &&Β !teacup_words.contains(&w) {
teacup_words.push(w);
}
} else {
is_teacup_word = false;
break;
}
}
ifΒ !is_teacup_word || teacup_words.is_empty() {
continue;
}
print!("{}", word);
found.insert(word);
for w in &teacup_words {
found.insert(w);
print!(" {}", w);
}
println!();
}
}
Β
fn main() {
let args: Vec<String> = std::env::args().collect();
if args.len()Β != 2 {
eprintln!("Usage: teacup dictionary");
std::process::exit(1);
}
let dict = load_dictionary(&args[1]);
match dict {
Ok(dict) => find_teacup_words(&dict),
Err(error) => eprintln!("Cannot open file {}: {}", &args[1], error),
}
} |
http://rosettacode.org/wiki/Teacup_rim_text | Teacup rim text | On a set of coasters we have, there's a picture of a teacup. Β On the rim of the teacup the word Β TEA Β appears a number of times separated by bullet characters Β (β’).
It occurred to me that if the bullet were removed and the words run together, Β you could start at any letter and still end up with a meaningful three-letter word.
So start at the Β T Β and read Β TEA. Β Start at the Β E Β and read Β EAT, Β or start at the Β A Β and read Β ATE.
That got me thinking that maybe there are other words that could be used rather that Β TEA. Β And that's just English. Β What about Italian or Greek or ... um ... Telugu.
For English, we will use the unixdict (now) located at: Β unixdict.txt.
(This will maintain continuity with other Rosetta Code tasks that also use it.)
Task
Search for a set of words that could be printed around the edge of a teacup. Β The words in each set are to be of the same length, that length being greater than two (thus precluding Β AH Β and Β HA, Β for example.)
Having listed a set, for example Β [ate tea eat], Β refrain from displaying permutations of that set, e.g.: Β [eat tea ate] Β etc.
The words should also be made of more than one letter Β (thus precluding Β III Β and Β OOO Β etc.)
The relationship between these words is (using ATE as an example) that the first letter of the first becomes the last letter of the second. Β The first letter of the second becomes the last letter of the third. Β So Β ATE Β becomes Β TEA Β and Β TEA Β becomes Β EAT.
All of the possible permutations, using this particular permutation technique, must be words in the list.
The set you generate for Β ATE Β will never included the word Β ETA Β as that cannot be reached via the first-to-last movement method.
Display one line for each set of teacup rim words.
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
| #Swift | Swift | import Foundation
Β
func loadDictionary(_ path: String) throws -> Set<String> {
let contents = try String(contentsOfFile: path, encoding: String.Encoding.ascii)
return Set<String>(contents.components(separatedBy: "\n").filter{!$0.isEmpty})
}
Β
func rotate<T>(_ array: inout [T]) {
guard array.count > 1 else {
return
}
let first = array[0]
array.replaceSubrange(0..<array.count-1, with: array[1...])
array[array.count - 1] = first
}
Β
func findTeacupWords(_ dictionary: Set<String>) {
var teacupWords: [String] = []
var found = Set<String>()
for word in dictionary {
if word.count < 3 || found.contains(word) {
continue
}
teacupWords.removeAll()
var isTeacupWord = true
var chars = Array(word)
for _ in 1..<word.count {
rotate(&chars)
let w = String(chars)
if (!dictionary.contains(w)) {
isTeacupWord = false
break
}
if wΒ != word &&Β !teacupWords.contains(w) {
teacupWords.append(w)
}
}
ifΒ !isTeacupWord || teacupWords.isEmpty {
continue
}
print(word, terminator: "")
found.insert(word)
for w in teacupWords {
found.insert(w)
print(" \(w)", terminator: "")
}
print()
}
}
Β
do {
let dictionary = try loadDictionary("unixdict.txt")
findTeacupWords(dictionary)
} catch {
print(error)
} |
http://rosettacode.org/wiki/Temperature_conversion | Temperature conversion | There are quite a number of temperature scales. For this task we will concentrate on four of the perhaps best-known ones:
Kelvin, Celsius, Fahrenheit, and Rankine.
The Celsius and Kelvin scales have the same magnitude, but different null points.
0 degrees Celsius corresponds to 273.15 kelvin.
0 kelvin is absolute zero.
The Fahrenheit and Rankine scales also have the same magnitude, but different null points.
0 degrees Fahrenheit corresponds to 459.67 degrees Rankine.
0 degrees Rankine is absolute zero.
The Celsius/Kelvin and Fahrenheit/Rankine scales have a ratio of 5Β : 9.
Task
Write code that accepts a value of kelvin, converts it to values of the three other scales, and prints the result.
Example
K 21.00
C -252.15
F -421.87
R 37.80
| #BASIC256 | BASIC256 | Β
do
print "Kelvin degrees (>=0): ";
input K
until K>=0
Β
print "K = " + string(K)
print "C = " + string(K - 273.15)
print "F = " + string(K * 1.8 - 459.67)
print "R = " + string(K * 1.8)
Β |
http://rosettacode.org/wiki/Temperature_conversion | Temperature conversion | There are quite a number of temperature scales. For this task we will concentrate on four of the perhaps best-known ones:
Kelvin, Celsius, Fahrenheit, and Rankine.
The Celsius and Kelvin scales have the same magnitude, but different null points.
0 degrees Celsius corresponds to 273.15 kelvin.
0 kelvin is absolute zero.
The Fahrenheit and Rankine scales also have the same magnitude, but different null points.
0 degrees Fahrenheit corresponds to 459.67 degrees Rankine.
0 degrees Rankine is absolute zero.
The Celsius/Kelvin and Fahrenheit/Rankine scales have a ratio of 5Β : 9.
Task
Write code that accepts a value of kelvin, converts it to values of the three other scales, and prints the result.
Example
K 21.00
C -252.15
F -421.87
R 37.80
| #BBC_BASIC | BBC BASIC | Β
REPEAT
INPUT "Kelvin degrees (>=0): " K
UNTIL K>=0
@%=&20208
PRINT '"K = " K
PRINT "C = " K - 273.15
PRINT "F = " K * 1.8 - 459.67
PRINT "R = " K * 1.8
END
Β |
http://rosettacode.org/wiki/Tau_function | Tau function | Given a positive integer, count the number of its positive divisors.
Task
Show the result for the first Β 100 Β positive integers.
Related task
Β Tau number
| #J | J | tau =: [:+/0=>:@i.|]
echo tau"0 [5 20$>:i.100
exit '' |
http://rosettacode.org/wiki/Tau_function | Tau function | Given a positive integer, count the number of its positive divisors.
Task
Show the result for the first Β 100 Β positive integers.
Related task
Β Tau number
| #Java | Java | public class TauFunction {
private static long divisorCount(long n) {
long total = 1;
// Deal with powers of 2 first
for (; (n & 1) == 0; n >>= 1) {
++total;
}
// Odd prime factors up to the square root
for (long p = 3; p * p <= n; p += 2) {
long count = 1;
for (; n % p == 0; n /= p) {
++count;
}
total *= count;
}
// If n > 1 then it's prime
if (n > 1) {
total *= 2;
}
return total;
}
Β
public static void main(String[] args) {
final int limit = 100;
System.out.printf("Count of divisors for the firstΒ %d positive integers:\n", limit);
for (long n = 1; n <= limit; ++n) {
System.out.printf("%3d", divisorCount(n));
if (n % 20 == 0) {
System.out.println();
}
}
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.