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/Terminal_control/Clear_the_screen | Terminal control/Clear the screen | Task
Clear the terminal window.
| #Nanoquery | Nanoquery | cls |
http://rosettacode.org/wiki/Terminal_control/Clear_the_screen | Terminal control/Clear the screen | Task
Clear the terminal window.
| #Nemerle | Nemerle | Console.Clear(); |
http://rosettacode.org/wiki/Terminal_control/Clear_the_screen | Terminal control/Clear the screen | Task
Clear the terminal window.
| #NewLISP | NewLISP |
(! "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
| #langur | langur | # borrowing null for "maybe"
val .trSet = [false, null, true]
val .and = f given .a, .b {
case true, null:
case null, true:
case null: null
default: .a and .b
}
val .or = f given .a, .b {
case false, null:
case null, false:
case null: null
default: .a or .b
}
val .imply = f if(.a nor .b: not? .a; .b)
# formatting function for the result values
# replacing null with "maybe"
# using left alignment of 5 code points
val .F = f $"\{nn [.r, "maybe"]:-5}"
writeln "a not a"
for .a in .trSet {
writeln $"\.a:.F; \(not? .a:.F)"
}
writeln "\na b a and b"
for .a in .trSet {
for .b in .trSet {
writeln $"\.a:.F; \.b:.F; \.and(.a, .b):.F;"
}
}
writeln "\na b a or b"
for .a in .trSet {
for .b in .trSet {
writeln $"\.a:.F; \.b:.F; \.or(.a, .b):.F;"
}
}
writeln "\na b a implies b"
for .a in .trSet {
for .b in .trSet {
writeln $"\.a:.F; \.b:.F; \.imply(.a, .b):.F;"
}
}
writeln "\na b a eq b"
for .a in .trSet {
for .b in .trSet {
writeln $"\.a:.F; \.b:.F; \.a ==? .b:.F;"
}
} |
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
| #Liberty_BASIC | Liberty BASIC |
'ternary logic
'0 1 2
'F ? T
'False Don't know True
'LB has NOT AND OR XOR, so we implement them.
'LB has no EQ, but XOR could be expressed via EQ. In 'normal' boolean at least.
global tFalse, tDontKnow, tTrue
tFalse = 0
tDontKnow = 1
tTrue = 2
print "Short and long names for ternary logic values"
for i = tFalse to tTrue
print shortName3$(i);" ";longName3$(i)
next
print
print "Single parameter functions"
print "x";" ";"=x";" ";"not(x)"
for i = tFalse to tTrue
print shortName3$(i);" ";shortName3$(i);" ";shortName3$(not3(i))
next
print
print "Double parameter fuctions"
print "x";" ";"y";" ";"x AND y";" ";"x OR y";" ";"x EQ y";" ";"x XOR y"
for a = tFalse to tTrue
for b = tFalse to tTrue
print shortName3$(a);" ";shortName3$(b);" "; _
shortName3$(and3(a,b));" "; shortName3$(or3(a,b));" "; _
shortName3$(eq3(a,b));" "; shortName3$(xor3(a,b))
next
next
function and3(a,b)
and3 = min(a,b)
end function
function or3(a,b)
or3 = max(a,b)
end function
function eq3(a,b)
select case
case a=tDontKnow or b=tDontKnow
eq3 = tDontKnow
case a=b
eq3 = tTrue
case else
eq3 = tFalse
end select
end function
function xor3(a,b)
xor3 = not3(eq3(a,b))
end function
function not3(b)
not3 = 2-b
end function
'------------------------------------------------
function shortName3$(i)
shortName3$ = word$("F ? T", i+1)
end function
function longName3$(i)
longName3$ = word$("False,Don't know,True", i+1, ",")
end function
|
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.
| #Picat | Picat | go =>
File = "readings.txt",
Total = new_map([num_readings=0,num_good_readings=0,sum_readings=0.0]),
InvalidCount = 0,
MaxInvalidCount = 0,
InvalidRunEnd = "",
Id = 0,
foreach(Line in read_file_lines(File))
Id := Id + 1,
NumReadings = 0,
NumGoodReadings = 0,
SumReadings = 0,
Fields = Line.split,
Rec = Fields.tail.map(to_float),
foreach([Reading,Flag] in chunks_of(Rec,2))
NumReadings := NumReadings + 1,
if Flag > 0 then
NumGoodReadings := NumGoodReadings + 1,
SumReadings := SumReadings + Reading,
InvalidCount := 0
else
InvalidCount := InvalidCount + 1,
if InvalidCount > MaxInvalidCount then
MaxInvalidCount := InvalidCount,
InvalidRunEnd := Fields[1]
end
end
end,
Total.put(num_readings,Total.get(num_readings) + NumReadings),
Total.put(num_good_readings,Total.get(num_good_readings) + NumGoodReadings),
Total.put(sum_readings,Total.get(sum_readings) + SumReadings),
if Id <= 3 then
printf("date:%w accept:%w reject:%w sum:%w\n", Fields[1],NumGoodReadings,
NumReadings-NumGoodReadings,
SumReadings)
end
end,
nl,
printf("readings: %d good readings: %d sum: %0.3f avg: %0.3f\n",Total.get(num_readings),
Total.get(num_good_readings),
Total.get(sum_readings),
Total.get(sum_readings) / Total.get(num_good_readings)),
nl,
println(maxInvalidCount=MaxInvalidCount),
println(invalidRunEnd=InvalidRunEnd),
nl. |
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
| #Julia | Julia | # v0.6.0
function printlyrics()
const gifts = split("""
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
""", '\n')
const days = split("""
first second third fourth fifth
sixth seventh eighth ninth tenth
eleventh twelfth""")
for (n, day) in enumerate(days)
g = gifts[n:-1:1]
print("\nOn the $day day of Christmas\nMy true love gave to me:\n")
if n == 1
print(join(g[1:end], '\n'), '\n')
else
print(join(g[1:end-1], '\n'), " and\n", g[end], '\n')
end
end
end
printlyrics() |
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
| #Kotlin | Kotlin | enum class Day {
first, second, third, fourth, fifth, sixth, seventh, eighth, ninth, tenth, eleventh, twelfth;
val header = "On the " + this + " day of Christmas, my true love sent to me\n\t"
}
fun main(x: Array<String>) {
val gifts = listOf("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")
Day.values().forEachIndexed { i, d -> println(d.header + gifts.slice(0..i).asReversed().joinToString("\n\t")) }
} |
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)
| #REXX | REXX | /*REXX program to display sixteen lines, each of a different color. */
parse arg !; if !all() then exit /*exit if documentation specified*/
if \!dos & \!os2 then exit /*if this isn't DOS, then exit. */
if \!pcrexx then exit /*if this isn't PC/REXX, exit. */
color.0 = 'black' /*┌─────────────────────────────┐*/
color.1 = 'dark blue' /*│ Normally, all programs issue│*/
color.2 = 'dark green' /*│ the (above) error messages │*/
color.3 = 'dark cyan/turquois' /*│ through another REXX program│*/
color.4 = 'dark red' /*│ ($ERR) which has more │*/
color.5 = 'dark pink/magenta' /*│ verbiage and explanations, │*/
color.6 = 'dark yellow (orange)' /*│ and issues the error text in│*/
color.7 = 'dark white' /*│ red (if color is available).│*/
color.8 = 'brite black (grey/gray)' /*└─────────────────────────────┘*/
color.9 = 'bright blue'
color.10 = 'bright green'
color.11 = 'bright cyan/turquois'
color.12 = 'bright red'
color.13 = 'bright pink/magenta'
color.14 = 'bright yellow'
color.15 = 'bright white'
do j=0 to 15 /*show all sixteen color codes. */
call scrwrite ,,'color code=['right(j,2)"]" color.j,,,j; say
end /*j*/ /*the "SAY" forces a NEWLINE. */
exit /*stick a fork in it, we're done.*/
/*══════════════════════════════════general 1-line subs═════════════════*/
!all:!!=!;!=space(!);upper !;call !fid;!nt=right(!var('OS'),2)=='NT';!cls=word('CLS VMFCLEAR CLRSCREEN',1+!cms+!tso*2);if arg(1)\==1 then return 0;if wordpos(!,'? ?SAMPLES ?AUTHOR ?FLOW')==0 then return 0;!call=']$H';call '$H' !fn !;!call=;return 1
!cal:if symbol('!CALL')\=="VAR" then !call=;return !call
!env:!env='ENVIRONMENT';if !sys=='MSDOS'|!brexx|!r4|!roo then !env='SYSTEM';if !os2 then !env='OS2'!env;!ebcdic=1=='f0'x;return
!fid:parse upper source !sys !fun !fid . 1 . . !fn !ft !fm .;call !sys;if !dos then do;_=lastpos('\',!fn);!fm=left(!fn,_);!fn=substr(!fn,_+1);parse var !fn !fn '.' !ft;end;return word(0 !fn !ft !fm,1+('0'arg(1)))
!rex:parse upper version !ver !vernum !verdate .;!brexx='BY'==!vernum;!kexx='KEXX'==!ver;!pcrexx='REXX/PERSONAL'==!ver|'REXX/PC'==!ver;!r4='REXX-R4'==!ver;!regina='REXX-REGINA'==left(!ver,11);!roo='REXX-ROO'==!ver;call !env;return
!sys:!cms=!sys=='CMS';!os2=!sys=='OS2';!tso=!sys=='TSO'|!sys=='MVS';!vse=!sys=='VSE';!dos=pos('DOS',!sys)\==0|pos('WIN',!sys)\==0|!sys=='CMD';call !rex;return
!var:call !fid;if !kexx then return space(dosenv(arg(1)));return space(value(arg(1),,!env)) |
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.
| #E | E | def printer := {
var count := 0
def printer {
to run(item) {
count += 1
println(item)
}
to getCount() {
return count
}
}
}
def sender(lines) {
switch (lines) {
match [] {
when (def count := printer <- getCount()) -> {
println(`$count lines were printed.`)
}
}
match [line] + rest {
when (printer <- run(line)) -> {
sender(rest)
}
}
}
}
# Stream IO in E is not finished yet, so this example just uses a list.
sender(<file:input.txt>.getText().split("\n")) |
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.
| #EchoLisp | EchoLisp |
(require 'sequences)
(require 'tasks)
;; inter-tasks message : (op-code . data)
(define (is-message? op message)
(and message (equal? op (first message))))
;; reader task
(define (reader infile )
(wait S)
(define message (semaphore-pop S))
(when (is-message? 'count message ) (writeln 'reader-> message) (task-stop-all))
(if (first infile) ;; not EOF
(set! message (cons 'write (next infile)))
(set! message (list 'reader-count-please)))
(semaphore-push S message)
(signal S)
infile)
(define (writer count)
(wait S)
(define message (semaphore-pop S))
(when (is-message? 'write message )
(writeln (rest message))
(set! count (1+ count))
(set! message (cons 'ack count)))
(when (is-message? 'reader-count-please message )
(set! message (cons 'count count)))
(semaphore-push S message)
(signal S)
count)
|
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.
| #PostgreSQL | PostgreSQL | CREATE SEQUENCE address_seq START 100;
CREATE TABLE address (
addrID int4 PRIMARY KEY DEFAULT NEXTVAL('address_seq'),
street VARCHAR(50) NOT NULL,
city VARCHAR(25) NOT NULL,
state VARCHAR(2) NOT NULL,
zip VARCHAR(20) 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.
| #PowerShell.2BSQLite | PowerShell+SQLite |
Import-Module -Name PSSQLite
## Create a database and a table
$dataSource = ".\Addresses.db"
$query = "CREATE TABLE SSADDRESS (Id INTEGER PRIMARY KEY AUTOINCREMENT,
LastName TEXT NOT NULL,
FirstName TEXT NOT NULL,
Address TEXT NOT NULL,
City TEXT NOT NULL,
State CHAR(2) NOT NULL,
Zip CHAR(5) NOT NULL
)"
Invoke-SqliteQuery -Query $Query -DataSource $DataSource
## Insert some data
$query = "INSERT INTO SSADDRESS ( FirstName, LastName, Address, City, State, Zip)
VALUES (@FirstName, @LastName, @Address, @City, @State, @Zip)"
Invoke-SqliteQuery -DataSource $DataSource -Query $query -SqlParameters @{
LastName = "Monster"
FirstName = "Cookie"
Address = "666 Sesame St"
City = "Holywood"
State = "CA"
Zip = "90013"
}
## View the data
Invoke-SqliteQuery -DataSource $DataSource -Query "SELECT * FROM SSADDRESS" | FormatTable -AutoSize
|
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.
| #PureBasic.2BSQLite | PureBasic+SQLite |
UseSQLiteDatabase()
Procedure CheckDatabaseUpdate(Database, Query$)
Result = DatabaseUpdate(Database, Query$)
If Result = 0
Print(DatabaseError())
EndIf
ProcedureReturn Result
EndProcedure
openconsole()
DatabaseFile$ = GetCurrentDirectory()+"/rosettadb.sdb"
If CreateFile(0, DatabaseFile$)
CloseFile(0)
If OpenDatabase(0, DatabaseFile$, "", "")
CheckDatabaseUpdate(0,"CREATE TABLE address ( addrID INTEGER PRIMARY KEY AUTOINCREMENT, addrStreet TEXT Not NULL, addrCity TEXT Not NULL, addrState TEXT Not NULL, addrZIP TEXT Not NULL)")
CloseDatabase(0)
Else
print("Can't open database !")
EndIf
Else
print("Can't create the database file !")
EndIf
closeconsole()
|
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.23 | C# | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
namespace Sutherland
{
public static class SutherlandHodgman
{
#region Class: Edge
/// <summary>
/// This represents a line segment
/// </summary>
private class Edge
{
public Edge(Point from, Point to)
{
this.From = from;
this.To = to;
}
public readonly Point From;
public readonly Point To;
}
#endregion
/// <summary>
/// This clips the subject polygon against the clip polygon (gets the intersection of the two polygons)
/// </summary>
/// <remarks>
/// Based on the psuedocode from:
/// http://en.wikipedia.org/wiki/Sutherland%E2%80%93Hodgman
/// </remarks>
/// <param name="subjectPoly">Can be concave or convex</param>
/// <param name="clipPoly">Must be convex</param>
/// <returns>The intersection of the two polygons (or null)</returns>
public static Point[] GetIntersectedPolygon(Point[] subjectPoly, Point[] clipPoly)
{
if (subjectPoly.Length < 3 || clipPoly.Length < 3)
{
throw new ArgumentException(string.Format("The polygons passed in must have at least 3 points: subject={0}, clip={1}", subjectPoly.Length.ToString(), clipPoly.Length.ToString()));
}
List<Point> outputList = subjectPoly.ToList();
// Make sure it's clockwise
if (!IsClockwise(subjectPoly))
{
outputList.Reverse();
}
// Walk around the clip polygon clockwise
foreach (Edge clipEdge in IterateEdgesClockwise(clipPoly))
{
List<Point> inputList = outputList.ToList(); // clone it
outputList.Clear();
if (inputList.Count == 0)
{
// Sometimes when the polygons don't intersect, this list goes to zero. Jump out to avoid an index out of range exception
break;
}
Point S = inputList[inputList.Count - 1];
foreach (Point E in inputList)
{
if (IsInside(clipEdge, E))
{
if (!IsInside(clipEdge, S))
{
Point? point = GetIntersect(S, E, clipEdge.From, clipEdge.To);
if (point == null)
{
throw new ApplicationException("Line segments don't intersect"); // may be colinear, or may be a bug
}
else
{
outputList.Add(point.Value);
}
}
outputList.Add(E);
}
else if (IsInside(clipEdge, S))
{
Point? point = GetIntersect(S, E, clipEdge.From, clipEdge.To);
if (point == null)
{
throw new ApplicationException("Line segments don't intersect"); // may be colinear, or may be a bug
}
else
{
outputList.Add(point.Value);
}
}
S = E;
}
}
// Exit Function
return outputList.ToArray();
}
#region Private Methods
/// <summary>
/// This iterates through the edges of the polygon, always clockwise
/// </summary>
private static IEnumerable<Edge> IterateEdgesClockwise(Point[] polygon)
{
if (IsClockwise(polygon))
{
#region Already clockwise
for (int cntr = 0; cntr < polygon.Length - 1; cntr++)
{
yield return new Edge(polygon[cntr], polygon[cntr + 1]);
}
yield return new Edge(polygon[polygon.Length - 1], polygon[0]);
#endregion
}
else
{
#region Reverse
for (int cntr = polygon.Length - 1; cntr > 0; cntr--)
{
yield return new Edge(polygon[cntr], polygon[cntr - 1]);
}
yield return new Edge(polygon[0], polygon[polygon.Length - 1]);
#endregion
}
}
/// <summary>
/// Returns the intersection of the two lines (line segments are passed in, but they are treated like infinite lines)
/// </summary>
/// <remarks>
/// Got this here:
/// http://stackoverflow.com/questions/14480124/how-do-i-detect-triangle-and-rectangle-intersection
/// </remarks>
private static Point? GetIntersect(Point line1From, Point line1To, Point line2From, Point line2To)
{
Vector direction1 = line1To - line1From;
Vector direction2 = line2To - line2From;
double dotPerp = (direction1.X * direction2.Y) - (direction1.Y * direction2.X);
// If it's 0, it means the lines are parallel so have infinite intersection points
if (IsNearZero(dotPerp))
{
return null;
}
Vector c = line2From - line1From;
double t = (c.X * direction2.Y - c.Y * direction2.X) / dotPerp;
//if (t < 0 || t > 1)
//{
// return null; // lies outside the line segment
//}
//double u = (c.X * direction1.Y - c.Y * direction1.X) / dotPerp;
//if (u < 0 || u > 1)
//{
// return null; // lies outside the line segment
//}
// Return the intersection point
return line1From + (t * direction1);
}
private static bool IsInside(Edge edge, Point test)
{
bool? isLeft = IsLeftOf(edge, test);
if (isLeft == null)
{
// Colinear points should be considered inside
return true;
}
return !isLeft.Value;
}
private static bool IsClockwise(Point[] polygon)
{
for (int cntr = 2; cntr < polygon.Length; cntr++)
{
bool? isLeft = IsLeftOf(new Edge(polygon[0], polygon[1]), polygon[cntr]);
if (isLeft != null) // some of the points may be colinear. That's ok as long as the overall is a polygon
{
return !isLeft.Value;
}
}
throw new ArgumentException("All the points in the polygon are colinear");
}
/// <summary>
/// Tells if the test point lies on the left side of the edge line
/// </summary>
private static bool? IsLeftOf(Edge edge, Point test)
{
Vector tmp1 = edge.To - edge.From;
Vector tmp2 = test - edge.To;
double x = (tmp1.X * tmp2.Y) - (tmp1.Y * tmp2.X); // dot product of perpendicular?
if (x < 0)
{
return false;
}
else if (x > 0)
{
return true;
}
else
{
// Colinear points;
return null;
}
}
private static bool IsNearZero(double testValue)
{
return Math.Abs(testValue) <= .000000001d;
}
#endregion
}
} |
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).
| #Apex | Apex | Set<String> setA = new Set<String>{'John', 'Bob', 'Mary', 'Serena'};
Set<String> setB = new Set<String>{'Jim', 'Mary', 'John', 'Bob'};
// Option 1
Set<String> notInSetA = setB.clone();
notInSetA.removeAll(setA);
Set<String> notInSetB = setA.clone();
notInSetB.removeAll(setB);
Set<String> symmetricDifference = new Set<String>();
symmetricDifference.addAll(notInSetA);
symmetricDifference.addAll(notInSetB);
// Option 2
Set<String> union = setA.clone();
union.addAll(setB);
Set<String> intersection = setA.clone();
intersection.retainAll(setB);
Set<String> symmetricDifference2 = union.clone();
symmetricDifference2.removeAll(intersection);
System.debug('Not in set A: ' + notInSetA);
System.debug('Not in set B: ' + notInSetB);
System.debug('Symmetric Difference: ' + symmetricDifference);
System.debug('Symmetric Difference 2: ' + symmetricDifference2); |
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.
| #Clojure | Clojure | (defn super [d]
(let [run (apply str (repeat d (str d)))]
(filter #(clojure.string/includes? (str (* d (Math/pow % d ))) run) (range))))
(doseq [d (range 2 9)]
(println (str d ": ") (take 10 (super d)))) |
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.
| #D | D | import std.bigint;
import std.conv;
import std.stdio;
import std.string;
void main() {
auto rd = ["22", "333", "4444", "55555", "666666", "7777777", "88888888", "999999999"];
BigInt one = 1;
BigInt nine = 9;
for (int ii = 2; ii <= 9; ii++) {
writefln("First 10 super-%d numbers:", ii);
auto count = 0;
inner:
for (BigInt j = 3; ; j++) {
auto k = ii * j ^^ ii;
auto ix = k.to!string.indexOf(rd[ii-2]);
if (ix >= 0) {
count++;
write(j, ' ');
if (count == 10) {
writeln();
writeln();
break inner;
}
}
}
}
} |
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.
| #E | E | #!/usr/bin/env rune
def f := <file:notes.txt>
def date := makeCommand("date")
switch (interp.getArgs()) {
match [] {
if (f.exists()) {
for line in f { print(line) }
}
}
match noteArgs {
def w := f.textWriter(true)
w.print(date()[0], "\t", " ".rjoin(noteArgs), "\n")
w.close()
}
} |
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.
| #Elixir | Elixir | defmodule Take_notes do
@filename "NOTES.TXT"
def main( [] ), do: display_notes
def main( arguments ), do: save_notes( arguments )
def display_notes, do: IO.puts File.read!(@filename)
def save_notes( arguments ) do
notes = "#{inspect :calendar.local_time}\n\t" <> Enum.join(arguments, " ")
File.open!(@filename, [:append], fn(file) -> IO.puts(file, notes) end)
end
end
Take_notes.main(System.argv) |
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
| #C | C |
#include<graphics.h>
#include<stdio.h>
#include<math.h>
#define pi M_PI
int main(){
double a,b,n,i,incr = 0.0001;
printf("Enter major and minor axes of the SuperEllipse : ");
scanf("%lf%lf",&a,&b);
printf("Enter n : ");
scanf("%lf",&n);
initwindow(500,500,"Superellipse");
for(i=0;i<2*pi;i+=incr){
putpixel(250 + a*pow(fabs(cos(i)),2/n)*(pi/2<i && i<3*pi/2?-1:1),250 + b*pow(fabs(sin(i)),2/n)*(pi<i && i<2*pi?-1:1),15);
}
printf("Done. %lf",i);
getch();
closegraph();
} |
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
| #jq | jq | # Generate the sylvester integers:
def sylvester:
foreach range(0; infinite) as $i ({prev: 1, product: 1};
.product *= .prev
| .prev = .product + 1;
.prev); |
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
| #Julia | Julia | sylvester(n) = (n == 1) ? big"2" : prod(sylvester, 1:n-1) + big"1"
foreach(n -> println(rpad(n, 3), " => ", sylvester(n)), 1:10)
println("Sum of reciprocals of first 10: ", sum(big"1.0" / sylvester(n) for n in 1:10))
|
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
| #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | Rest[Nest[Append[#, (Times @@ #) + 1] &, {1}, 10]]
N[Total[1/%], 250] |
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
| #Nim | Nim | import sequtils
import bignum
proc sylverster(lim: Positive): seq[Int] =
result.add(newInt(2))
for _ in 2..lim:
result.add result.foldl(a * b) + 1
let list = sylverster(10)
echo "First 10 terms of the Sylvester sequence:"
for item in list: echo item
var sum = newRat()
for item in list: sum += newRat(1, item)
echo "\nSum of the reciprocals of the first 10 terms: ", sum.toFloat |
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
| #PARI.2FGP | PARI/GP |
S=vector(10)
S[1]=2
for(i=2, 10, S[i]=prod(n=1,i-1,S[n])+1)
print(S)
print(sum(i=1,10,1/S[i])) |
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).
| #Java | Java | import java.util.PriorityQueue;
import java.util.ArrayList;
import java.util.List;
import java.util.Iterator;
class CubeSum implements Comparable<CubeSum> {
public long x, y, value;
public CubeSum(long x, long y) {
this.x = x;
this.y = y;
this.value = x*x*x + y*y*y;
}
public String toString() {
return String.format("%4d^3 + %4d^3", x, y);
}
public int compareTo(CubeSum that) {
return value < that.value ? -1 : value > that.value ? 1 : 0;
}
}
class SumIterator implements Iterator<CubeSum> {
PriorityQueue<CubeSum> pq = new PriorityQueue<CubeSum>();
long n = 0;
public boolean hasNext() { return true; }
public CubeSum next() {
while (pq.size() == 0 || pq.peek().value >= n*n*n)
pq.add(new CubeSum(++n, 1));
CubeSum s = pq.remove();
if (s.x > s.y + 1) pq.add(new CubeSum(s.x, s.y+1));
return s;
}
}
class TaxiIterator implements Iterator<List<CubeSum>> {
Iterator<CubeSum> sumIterator = new SumIterator();
CubeSum last = sumIterator.next();
public boolean hasNext() { return true; }
public List<CubeSum> next() {
CubeSum s;
List<CubeSum> train = new ArrayList<CubeSum>();
while ((s = sumIterator.next()).value != last.value)
last = s;
train.add(last);
do { train.add(s); } while ((s = sumIterator.next()).value == last.value);
last = s;
return train;
}
}
public class Taxi {
public static final void main(String[] args) {
Iterator<List<CubeSum>> taxi = new TaxiIterator();
for (int i = 1; i <= 2006; i++) {
List<CubeSum> t = taxi.next();
if (i > 25 && i < 2000) continue;
System.out.printf("%4d: %10d", i, t.get(0).value);
for (CubeSum s: t)
System.out.print(" = " + s);
System.out.println();
}
}
} |
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.
| #Go | Go | package main
import "fmt"
const max = 12
var (
super []byte
pos int
cnt [max]int
)
// 1! + 2! + ... + n!
func factSum(n int) int {
s := 0
for x, f := 0, 1; x < n; {
x++
f *= x
s += f
}
return s
}
func r(n int) bool {
if n == 0 {
return false
}
c := super[pos-n]
cnt[n]--
if cnt[n] == 0 {
cnt[n] = n
if !r(n - 1) {
return false
}
}
super[pos] = c
pos++
return true
}
func superperm(n int) {
pos = n
le := factSum(n)
super = make([]byte, le)
for i := 0; i <= n; i++ {
cnt[i] = i
}
for i := 1; i <= n; i++ {
super[i-1] = byte(i) + '0'
}
for r(n) {
}
}
func main() {
for n := 0; n < max; n++ {
fmt.Printf("superperm(%2d) ", n)
superperm(n)
fmt.Printf("len = %d\n", len(super))
}
} |
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
| #Python | Python | def tau(n):
assert(isinstance(n, int) and 0 < n)
ans, i, j = 0, 1, 1
while i*i <= n:
if 0 == n%i:
ans += 1
j = n//i
if j != i:
ans += 1
i += 1
return ans
def is_tau_number(n):
assert(isinstance(n, int))
if n <= 0:
return False
return 0 == n%tau(n)
if __name__ == "__main__":
n = 1
ans = []
while len(ans) < 100:
if is_tau_number(n):
ans.append(n)
n += 1
print(ans) |
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
| #Quackery | Quackery | [ dup factors size mod 0 = ] is taunumber ( n --> b )
[] 0
[ 1+ dup taunumber if
[ tuck join swap ]
over size 100 = until ]
drop
[] swap
witheach [ number$ nested join ]
80 wrap$ |
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
| #Wren | Wren | import "io" for File
import "/str" for Str
import "/sort" for Find
var readWords = Fn.new { |fileName|
var dict = File.read(fileName).split("\n")
return dict.where { |w| w.count >= 3 }.toList
}
var dicts = ["mit10000.txt", "unixdict.txt"]
for (dict in dicts) {
System.print("Using %(dict):\n")
var words = readWords.call(dict)
var n = words.count
var used = {}
for (word in words) {
var outer = false
var variants = [word]
var word2 = word
for (i in 0...word.count-1) {
word2 = Str.lshift(word2)
if (word == word2 || used[word2]) {
outer = true
break
}
var ix = Find.first(words, word2)
if (ix == n || words[ix] != word2) {
outer = true
break
}
variants.add(word2)
}
if (!outer) {
for (variant in variants) used[variant] = true
System.print(variants)
}
}
System.print()
} |
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
| #Befunge | Befunge | 0000>0p~>"."-:!#v_2-::0\`\9`+!#v_$1>/\:3`#v_\>\:3 \`#v_v
1#<<^0 /2++g001!<1 \+g00\+*+55\< ^+55\-1< ^*+55\+1<v_
"K"\-+**"!Y]"9:\"C"\--\**"^CIT"/5*9:\"F"\/5*9:\"R"\0\0<v
v/+55\+*86%+55: /+55\+*86%+55: \0/+55+5*-\1*2 p00:`\0:,<
>"."\>:55+% 68*v >:#,_$55+,\:!#@_^
$_^#!:/+55\+< ^\" :"_<g00*95 |
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
| #jq | jq | def count(s): reduce s as $x (0; .+1);
# For pretty-printing
def nwise($n):
def n: if length <= $n then . else .[0:$n] , (.[$n:] | n) end;
n;
def lpad($len): tostring | ($len - length) as $l | (" " * $l)[:$l] + .; |
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
| #Julia | Julia | using Primes
function numfactors(n)
f = [one(n)]
for (p, e) in factor(n)
f = reduce(vcat, [f * p^j for j in 1:e], init = f)
end
length(f)
end
for i in 1:100
print(rpad(numfactors(i), 3), i % 25 == 0 ? " \n" : " ")
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
| #Lua | Lua | function divisorCount(n)
local total = 1
-- Deal with powers of 2 first
while (n & 1) == 0 do
total = total + 1
n = math.floor(n / 2)
end
-- Odd prime factors up tot eh square root
local p = 3
while p * p <= n do
local count = 1
while n % p == 0 do
count = count + 1
n = n / p
end
total = total * count
p = p + 2
end
-- If n > 1 then it's prime
if n > 1 then
total = total * 2
end
return total
end
limit = 100
print("Count of divisors for the first " .. limit .. " positive integers:")
for n=1,limit do
io.write(string.format("%3d", divisorCount(n)))
if n % 20 == 0 then
print()
end
end |
http://rosettacode.org/wiki/Terminal_control/Clear_the_screen | Terminal control/Clear the screen | Task
Clear the terminal window.
| #Nim | Nim |
import terminal
eraseScreen() #puts cursor at down
setCursorPos(0, 0)
|
http://rosettacode.org/wiki/Terminal_control/Clear_the_screen | Terminal control/Clear the screen | Task
Clear the terminal window.
| #NS-HUBASIC | NS-HUBASIC | 10 CLS |
http://rosettacode.org/wiki/Terminal_control/Clear_the_screen | Terminal control/Clear the screen | Task
Clear the terminal window.
| #OCaml | OCaml | #load "unix.cma"
#directory "+ANSITerminal"
#load "ANSITerminal.cma"
open ANSITerminal
let () =
erase Screen |
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
| #Maple | Maple | tv := [true, false, FAIL];
NotTable := Array(1..3, i->not tv[i] );
AndTable := Array(1..3, 1..3, (i,j)->tv[i] and tv[j] );
OrTable := Array(1..3, 1..3, (i,j)->tv[i] or tv[j] );
XorTable := Array(1..3, 1..3, (i,j)->tv[i] xor tv[j] );
ImpliesTable := Array(1..3, 1..3, (i,j)->tv[i] implies tv[j] ); |
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.
| #PicoLisp | PicoLisp | #!/usr/bin/picolisp /usr/lib/picolisp/lib.l
(let (NoData 0 NoDataMax -1 NoDataMaxline "!" TotFile 0 NumFile 0)
(let InFiles
(glue ","
(mapcar
'((File)
(in File
(while (split (line) "^I")
(let (Len (length @) Date (car @) TotLine 0 NumLine 0)
(for (L (cdr @) L (cddr L))
(if (> 1 (format (cadr L)))
(inc 'NoData)
(when (gt0 NoData)
(when (= NoDataMax NoData)
(setq NoDataMaxline (pack NoDataMaxline ", " Date)) )
(when (> NoData NoDataMax)
(setq NoDataMax NoData NoDataMaxline Date) ) )
(zero NoData)
(inc 'TotLine (format (car L) 3))
(inc 'NumLine) ) )
(inc 'TotFile TotLine)
(inc 'NumFile NumLine)
(tab (-7 -12 -7 3 -9 3 -11 11 -11 11)
"Line:" Date
"Reject:" (- (/ (dec Len) 2) NumLine)
" Accept:" NumLine
" Line_tot:" (format TotLine 3)
" Line_avg:"
(and (gt0 NumLine) (format (*/ TotLine @) 3)) ) ) ) )
File )
(argv) ) )
(prinl)
(prinl "File(s) = " InFiles)
(prinl "Total = " (format TotFile 3))
(prinl "Readings = " NumFile)
(prinl "Average = " (format (*/ TotFile NumFile) 3))
(prinl)
(prinl
"Maximum run(s) of " NoDataMax
" consecutive false readings ends at line starting with date(s): " NoDataMaxline ) ) )
(bye) |
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
| #Lambdatalk | Lambdatalk |
{def days
first second third fourth fifth sixth
seventh eight ninth tenth eleventh twelfth}
-> days
{def texts
{quote A partridge in a pear tree.}
{quote Two turtle doves and}
{quote Three french hens}
{quote Four calling birds}
{quote Five golden rings}
{quote Six geese a-laying}
{quote Seven swans a-swimming}
{quote Eight maids a-milking}
{quote Nine ladies dancing}
{quote Ten lords a-leaping}
{quote Eleven pipers piping}
{quote Twelve drummers drumming}}
-> texts
{S.map {lambda {:i} {hr}On the {S.get :i {days}} day of Christmas
{br}My true love gave to me
{S.map {lambda {:i} {br}{S.get :i {texts}}}
{S.serie :i 0 -1}}
} {S.serie 0 {- {S.length {days}} 1}}}
->
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 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.
|
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)
| #Ring | Ring |
# Project : Terminal control/Coloured text
load "consolecolors.ring"
forecolors = [CC_FG_BLACK,CC_FG_RED,CC_FG_GREEN,CC_FG_YELLOW,
CC_FG_BLUE,CC_FG_MAGENTA,CC_FG_CYAN,CC_FG_GRAY,CC_BG_WHITE]
for n = 1 to len(forecolors)
forecolor = forecolors[n]
cc_print(forecolor | CC_BG_WHITE, "Rosetta Code" + nl)
next
|
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)
| #Ruby | Ruby | #!/usr/bin/ruby -w
require 'rubygems'
require 'colored'
print 'Colors are'.bold
print ' black'.black
print ' blue'.blue
print ' cyan'.cyan
print ' green'.green
print ' magenta'.magenta
print ' red'.red
print ' white '.white
print 'and'.underline, ' yellow'.yellow, "\n"
puts 'black on blue'.black_on_blue
puts 'black on cyan'.black_on_cyan
puts 'black on green'.black_on_green
puts 'black on magenta'.black_on_magenta
puts 'black on red'.black_on_red
puts 'white on black'.white_on_black
puts 'white on blue'.white_on_blue
puts 'white on cyan'.white_on_cyan
puts 'white on green'.white_on_green
puts 'white on magenta'.white_on_magenta
puts 'white on red'.white_on_red |
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.
| #Elixir | Elixir | defmodule RC do
def start do
my_pid = self
pid = spawn( fn -> reader(my_pid, 0) end )
File.open( "input.txt", [:read], fn io ->
process( IO.gets(io, ""), io, pid )
end )
end
defp process( :eof, _io, pid ) do
send( pid, :count )
receive do
i -> IO.puts "Count:#{i}"
end
end
defp process( any, io, pid ) do
send( pid, any )
process( IO.gets(io, ""), io, pid )
end
defp reader( pid, c ) do
receive do
:count -> send( pid, c )
any ->
IO.write any
reader( pid, c+1 )
end
end
end
RC.start |
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.
| #Erlang | Erlang | -module(cc).
-export([start/0]).
start() ->
My_pid = erlang:self(),
Pid = erlang:spawn( fun() -> reader(My_pid, 0) end ),
{ok, IO } = file:open( "input.txt", [read] ),
process( io:get_line(IO, ""), IO, Pid ),
file:close( IO ).
process( eof, _IO, Pid ) ->
Pid ! count,
receive
I -> io:fwrite("Count:~p~n", [I])
end;
process( Any, IO, Pid ) ->
Pid ! Any,
process( io:get_line(IO, ""), IO, Pid ).
reader(Pid, C) ->
receive
count -> Pid ! C;
Any ->
io:fwrite("~s", [Any]),
reader(Pid, C+1)
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.
| #Python.2BSQLite | Python+SQLite | >>> import sqlite3
>>> conn = sqlite3.connect(':memory:')
>>> conn.execute('''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.Cursor object at 0x013265C0>
>>> |
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.
| #Racket | Racket |
#lang at-exp racket
(require db)
(define postal (sqlite3-connect #:database "/tmp/postal.db" #:mode 'create))
(define (add! name street city state zip)
(query-exec postal
@~a{INSERT INTO addresses (name, street, city, state, zip)
VALUES (?, ?, ?, ?, ?)}
name street city state zip))
(unless (table-exists? postal "addresses")
(query-exec postal
@~a{CREATE TABLE addresses(
id INTEGER PRIMARY KEY,
name TEXT NOT NULL,
street TEXT NOT NULL,
city TEXT NOT NULL,
state TEXT NOT NULL,
zip TEXT NOT NULL)}))
(add! "FSF Inc."
"51 Franklin St"
"Boston"
"MA"
"02110-1301")
(add! "The White House"
"1600 Pennsylvania Avenue NW"
"Washington"
"DC"
"20500")
(add! "National Security Council"
"1700 Pennsylvania Avenue NW"
"Washington"
"DC"
"20500")
(printf "Addresses:\n")
(for ([r (query-rows postal "SELECT * FROM addresses")])
(printf " ~a.\n" (string-join (cdr (vector->list r)) ", ")))
(newline)
(printf "By State+ZIP:\n")
(for ([z (query-rows postal "SELECT * FROM addresses"
#:group #("state" "zip"))])
(printf " ~a, ~a:\n" (vector-ref z 0) (vector-ref z 1))
(for ([r (vector-ref z 2)])
(printf " ~a.\n" (string-join (cdr (vector->list r)) ", "))))
(disconnect postal)
|
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.
| #Raku | Raku | use DBIish;
my $dbh = DBIish.connect('SQLite', :database<addresses.sqlite3>);
my $sth = $dbh.do(q:to/STATEMENT/);
DROP TABLE IF EXISTS Address;
CREATE TABLE Address (
addrID INTEGER PRIMARY KEY AUTOINCREMENT,
addrStreet TEXT NOT NULL,
addrCity TEXT NOT NULL,
addrState TEXT NOT NULL,
addrZIP TEXT NOT NULL
)
STATEMENT |
http://rosettacode.org/wiki/System_time | System time | Task
Output the system time (any units will do as long as they are noted) either by a system command or one built into the language.
The system time can be used for debugging, network information, random number seeds, or something as simple as program performance.
Related task
Date format
See also
Retrieving system time (wiki)
| #11l | 11l | print(Time()) |
http://rosettacode.org/wiki/Summarize_and_say_sequence | Summarize and say sequence | There are several ways to generate a self-referential sequence. One very common one (the Look-and-say sequence) is to start with a positive integer, then generate the next term by concatenating enumerated groups of adjacent alike digits:
0, 10, 1110, 3110, 132110, 1113122110, 311311222110 ...
The terms generated grow in length geometrically and never converge.
Another way to generate a self-referential sequence is to summarize the previous term.
Count how many of each alike digit there is, then concatenate the sum and digit for each of the sorted enumerated digits. Note that the first five terms are the same as for the previous sequence.
0, 10, 1110, 3110, 132110, 13123110, 23124110 ...
Sort the digits largest to smallest. Do not include counts of digits that do not appear in the previous term.
Depending on the seed value, series generated this way always either converge to a stable value or to a short cyclical pattern. (For our purposes, I'll use converge to mean an element matches a previously seen element.) The sequence shown, with a seed value of 0, converges to a stable value of 1433223110 after 11 iterations. The seed value that converges most quickly is 22. It goes stable after the first element. (The next element is 22, which has been seen before.)
Task
Find all the positive integer seed values under 1000000, for the above convergent self-referential sequence, that takes the largest number of iterations before converging. Then print out the number of iterations and the sequence they return. Note that different permutations of the digits of the seed will yield the same sequence. For this task, assume leading zeros are not permitted.
Seed Value(s): 9009 9090 9900
Iterations: 21
Sequence: (same for all three seeds except for first element)
9009
2920
192210
19222110
19323110
1923123110
1923224110
191413323110
191433125110
19151423125110
19251413226110
1916151413325110
1916251423127110
191716151413326110
191726151423128110
19181716151413327110
19182716151423129110
29181716151413328110
19281716151423228110
19281716151413427110
19182716152413228110
Related tasks
Fours is the number of letters in the ...
Look-and-say sequence
Number names
Self-describing numbers
Spelling of ordinal numbers
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
Also see
The On-Line Encyclopedia of Integer Sequences.
| #11l | 11l | [String] result
V longest = 0
F make_sequence(n) -> N
DefaultDict[Char, Int] map
L(c) n
map[c]++
V z = ‘’
L(k) sorted(map.keys(), reverse' 1B)
z ‘’= Char(code' map[k] + ‘0’.code)
z ‘’= k
I :longest <= z.len
:longest = z.len
I z !C :result
:result [+]= z
make_sequence(z)
L(test) [‘9900’, ‘9090’, ‘9009’]
result.clear()
longest = 0
make_sequence(test)
print(‘[#.] Iterations: #.’.format(test, result.len + 1))
print(result.join("\n"))
print("\n") |
http://rosettacode.org/wiki/Summarize_primes | Summarize primes | Task
Considering in order of length, n, all sequences of consecutive
primes, p, from 2 onwards, where p < 1000 and n>0, select those
sequences whose sum is prime, and for these display the length of the
sequence, the last item in the sequence, and the sum.
| #11l | 11l | F is_prime(a)
I a == 2
R 1B
I a < 2 | a % 2 == 0
R 0B
L(i) (3 .. Int(sqrt(a))).step(2)
I a % i == 0
R 0B
R 1B
print(‘index prime prime sum’)
V s = 0
V idx = 0
L(n) 2..999
I is_prime(n)
idx++
s += n
I is_prime(s)
print(f:‘{idx:3} {n:5} {s:7}’) |
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.2B.2B | C++ | #include <iostream>
using namespace std;
struct point2D { float x, y; };
const int N = 99; // clipped (new) polygon size
// check if a point is on the LEFT side of an edge
bool inside(point2D p, point2D p1, point2D p2)
{
return (p2.y - p1.y) * p.x + (p1.x - p2.x) * p.y + (p2.x * p1.y - p1.x * p2.y) < 0;
}
// calculate intersection point
point2D intersection(point2D cp1, point2D cp2, point2D s, point2D e)
{
point2D dc = { cp1.x - cp2.x, cp1.y - cp2.y };
point2D dp = { s.x - e.x, s.y - e.y };
float n1 = cp1.x * cp2.y - cp1.y * cp2.x;
float n2 = s.x * e.y - s.y * e.x;
float n3 = 1.0 / (dc.x * dp.y - dc.y * dp.x);
return { (n1 * dp.x - n2 * dc.x) * n3, (n1 * dp.y - n2 * dc.y) * n3 };
}
// Sutherland-Hodgman clipping
void SutherlandHodgman(point2D *subjectPolygon, int &subjectPolygonSize, point2D *clipPolygon, int &clipPolygonSize, point2D (&newPolygon)[N], int &newPolygonSize)
{
point2D cp1, cp2, s, e, inputPolygon[N];
// copy subject polygon to new polygon and set its size
for(int i = 0; i < subjectPolygonSize; i++)
newPolygon[i] = subjectPolygon[i];
newPolygonSize = subjectPolygonSize;
for(int j = 0; j < clipPolygonSize; j++)
{
// copy new polygon to input polygon & set counter to 0
for(int k = 0; k < newPolygonSize; k++){ inputPolygon[k] = newPolygon[k]; }
int counter = 0;
// get clipping polygon edge
cp1 = clipPolygon[j];
cp2 = clipPolygon[(j + 1) % clipPolygonSize];
for(int i = 0; i < newPolygonSize; i++)
{
// get subject polygon edge
s = inputPolygon[i];
e = inputPolygon[(i + 1) % newPolygonSize];
// Case 1: Both vertices are inside:
// Only the second vertex is added to the output list
if(inside(s, cp1, cp2) && inside(e, cp1, cp2))
newPolygon[counter++] = e;
// Case 2: First vertex is outside while second one is inside:
// Both the point of intersection of the edge with the clip boundary
// and the second vertex are added to the output list
else if(!inside(s, cp1, cp2) && inside(e, cp1, cp2))
{
newPolygon[counter++] = intersection(cp1, cp2, s, e);
newPolygon[counter++] = e;
}
// Case 3: First vertex is inside while second one is outside:
// Only the point of intersection of the edge with the clip boundary
// is added to the output list
else if(inside(s, cp1, cp2) && !inside(e, cp1, cp2))
newPolygon[counter++] = intersection(cp1, cp2, s, e);
// Case 4: Both vertices are outside
else if(!inside(s, cp1, cp2) && !inside(e, cp1, cp2))
{
// No vertices are added to the output list
}
}
// set new polygon size
newPolygonSize = counter;
}
}
int main(int argc, char** argv)
{
// subject polygon
point2D subjectPolygon[] = {
{50,150}, {200,50}, {350,150},
{350,300},{250,300},{200,250},
{150,350},{100,250},{100,200}
};
int subjectPolygonSize = sizeof(subjectPolygon) / sizeof(subjectPolygon[0]);
// clipping polygon
point2D clipPolygon[] = { {100,100}, {300,100}, {300,300}, {100,300} };
int clipPolygonSize = sizeof(clipPolygon) / sizeof(clipPolygon[0]);
// define the new clipped polygon (empty)
int newPolygonSize = 0;
point2D newPolygon[N] = { 0 };
// apply clipping
SutherlandHodgman(subjectPolygon, subjectPolygonSize, clipPolygon, clipPolygonSize, newPolygon, newPolygonSize);
// print clipped polygon points
cout << "Clipped polygon points:" << endl;
for(int i = 0; i < newPolygonSize; i++)
cout << "(" << newPolygon[i].x << ", " << newPolygon[i].y << ")" << endl;
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).
| #APL | APL | symdiff ← ∪~∩ |
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).
| #AppleScript | AppleScript | -- SYMMETRIC DIFFERENCE -------------------------------------------
-- symmetricDifference :: [a] -> [a] -> [a]
on symmetricDifference(xs, ys)
union(difference(xs, ys), difference(ys, xs))
end symmetricDifference
-- TEST -----------------------------------------------------------
on run
set a to ["John", "Serena", "Bob", "Mary", "Serena"]
set b to ["Jim", "Mary", "John", "Jim", "Bob"]
symmetricDifference(a, b)
--> {"Serena", "Jim"}
end run
-- GENERIC FUNCTIONS ----------------------------------------------
-- delete :: Eq a => a -> [a] -> [a]
on |delete|(x, xs)
set mbIndex to elemIndex(x, xs)
set lng to length of xs
if mbIndex is not missing value then
if lng > 1 then
if mbIndex = 1 then
items 2 thru -1 of xs
else if mbIndex = lng then
items 1 thru -2 of xs
else
tell xs to items 1 thru (mbIndex - 1) & ¬
items (mbIndex + 1) thru -1
end if
else
{}
end if
else
xs
end if
end |delete|
-- difference :: [a] -> [a] -> [a]
on difference(xs, ys)
script
on |λ|(a, y)
if a contains y then
my |delete|(y, a)
else
a
end if
end |λ|
end script
foldl(result, xs, ys)
end difference
-- elemIndex :: a -> [a] -> Maybe Int
on elemIndex(x, xs)
set lng to length of xs
repeat with i from 1 to lng
if x = (item i of xs) then return i
end repeat
return missing value
end elemIndex
-- foldl :: (a -> b -> a) -> a -> [b] -> a
on foldl(f, startValue, xs)
tell mReturn(f)
set v to startValue
set lng to length of xs
repeat with i from 1 to lng
set v to |λ|(v, item i of xs, i, xs)
end repeat
return v
end tell
end foldl
-- Lift 2nd class handler function into 1st class script wrapper
-- mReturn :: Handler -> Script
on mReturn(f)
if class of f is script then
f
else
script
property |λ| : f
end script
end if
end mReturn
-- nub :: [a] -> [a]
on nub(xs)
if (length of xs) > 1 then
set x to item 1 of xs
[x] & nub(|delete|(x, items 2 thru -1 of xs))
else
xs
end if
end nub
-- union :: [a] -> [a] -> [a]
on union(xs, ys)
script flipDelete
on |λ|(xs, x)
my |delete|(x, xs)
end |λ|
end script
set sx to nub(xs)
sx & foldl(flipDelete, nub(ys), sx)
end union |
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.
| #F.23 | F# |
// Generate Super-N numbers. Nigel Galloway: October 12th., 2019
let superD N=
let I=bigint(pown 10 N)
let G=bigint N
let E=G*(111111111I%I)
let rec fL n=match (E-n%I).IsZero with true->true |_->if (E*10I)<n then false else fL (n/10I)
seq{1I..999999999999999999I}|>Seq.choose(fun n->if fL (G*n**N) then Some n else None)
|
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.
| #Factor | Factor | USING: arrays formatting io kernel lists lists.lazy math
math.functions math.ranges math.text.utils prettyprint sequences
;
IN: rosetta-code.super-d
: super-d? ( seq n d -- ? ) tuck ^ * 1 digit-groups subseq? ;
: super-d ( d -- list )
[ dup <array> ] [ drop 1 lfrom ] [ ] tri [ super-d? ] curry
with lfilter ;
: super-d-demo ( -- )
10 2 6 [a,b] [
dup "First 10 super-%d numbers:\n" printf
super-d ltake list>array [ pprint bl ] each nl nl
] with each ;
MAIN: super-d-demo |
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.
| #F.C5.8Drmul.C3.A6 | Fōrmulæ | package main
import (
"fmt"
"math/big"
"strings"
"time"
)
func main() {
start := time.Now()
rd := []string{"22", "333", "4444", "55555", "666666", "7777777", "88888888", "999999999"}
one := big.NewInt(1)
nine := big.NewInt(9)
for i := big.NewInt(2); i.Cmp(nine) <= 0; i.Add(i, one) {
fmt.Printf("First 10 super-%d numbers:\n", i)
ii := i.Uint64()
k := new(big.Int)
count := 0
inner:
for j := big.NewInt(3); ; j.Add(j, one) {
k.Exp(j, i, nil)
k.Mul(i, k)
ix := strings.Index(k.String(), rd[ii-2])
if ix >= 0 {
count++
fmt.Printf("%d ", j)
if count == 10 {
fmt.Printf("\nfound in %d ms\n\n", time.Since(start).Milliseconds())
break inner
}
}
}
}
} |
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.
| #Erlang | Erlang |
#! /usr/bin/env escript
main( Arguments ) ->
display_notes( Arguments ),
save_notes( Arguments ).
display_notes( [] ) -> io:fwrite( "~s", [erlang:binary_to_list(file_contents())] );
display_notes( _Arguments ) -> ok.
file() -> "NOTES.TXT".
file_contents() -> file_contents( file:read_file(file()) ).
file_contents( {ok, Binary} ) -> Binary;
file_contents( {error, _Error} ) -> <<>>.
save_notes( [] ) -> ok;
save_notes( Arguments ) ->
Date = io_lib:format( "~p~n", [calendar:local_time()] ),
Notes = [Date ++ "\t" | [io_lib:format( "~s ", [X]) || X <- Arguments]],
Existing_contents = file_contents(),
file:write_file( file(), [Existing_contents, Notes, "\n"] ).
|
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
| #EchoLisp | EchoLisp |
(lib 'plot)
(define (eaxpt x n) (expt (abs x) n))
(define (Ellie x y) (+ (eaxpt (// x 200) 2.5) (eaxpt (// y 200) 2.5) -1))
(plot-xy Ellie -400 -400)
→ (("x:auto" -400 400) ("y:auto" -400 400))
|
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
| #Perl | Perl | use strict;
use warnings;
use feature 'say';
use List::Util 'reduce';
use Math::AnyNum ':overload';
local $Math::AnyNum::PREC = 845;
my(@S,$sum);
push @S, 1 + reduce { $a * $b } @S for 0..10;
shift @S;
$sum += 1/$_ for @S;
say "First 10 elements of Sylvester's sequence: @S";
say "\nSum of the reciprocals of first 10 elements: " . float $sum; |
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
| #Phix | Phix | atom n, rn = 0,
lim = power(2,iff(machine_bits()=32?53:64))
for i=1 to 10 do
n = iff(i=1?2:n*n-n+1)
printf(1,iff(n<=lim?"%d: %d\n":"%d: %g\n"),{i,n})
rn += 1/n
end for
printf(1,"sum of reciprocals: %g\n",{rn})
|
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).
| #JavaScript | JavaScript | var n3s = [],
s3s = {}
for (var n = 1, e = 1200; n < e; n += 1) n3s[n] = n * n * n
for (var a = 1; a < e - 1; a += 1) {
var a3 = n3s[a]
for (var b = a; b < e; b += 1) {
var b3 = n3s[b]
var s3 = a3 + b3,
abs = s3s[s3]
if (!abs) s3s[s3] = abs = []
abs.push([a, b])
}
}
var i = 0
for (var s3 in s3s) {
var abs = s3s[s3]
if (abs.length < 2) continue
i += 1
if (abs.length == 2 && i > 25 && i < 2000) continue
if (i > 2006) break
document.write(i, ': ', s3)
for (var ab of abs) {
document.write(' = ', ab[0], '<sup>3</sup>+', ab[1], '<sup>3</sup>')
}
document.write('<br>')
} |
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.
| #Groovy | Groovy | import static java.util.stream.IntStream.rangeClosed
class Superpermutation {
final static int nMax = 12
static char[] superperm
static int pos
static int[] count = new int[nMax]
static int factSum(int n) {
return rangeClosed(1, n)
.map({ m -> rangeClosed(1, m).reduce(1, { a, b -> a * b }) }).sum()
}
static boolean r(int n) {
if (n == 0) {
return false
}
char c = superperm[pos - n]
if (--count[n] == 0) {
count[n] = n
if (!r(n - 1)) {
return false
}
}
superperm[pos++] = c
return true
}
static void superPerm(int n) {
String chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"
pos = n
superperm = new char[factSum(n)]
for (int i = 0; i < n + 1; i++) {
count[i] = i
}
for (int i = 1; i < n + 1; i++) {
superperm[i - 1] = chars.charAt(i)
}
while (r(n)) {
}
}
static void main(String[] args) {
for (int n = 0; n < nMax; n++) {
superPerm(n)
printf("superPerm(%2d) len = %d", n, superperm.length)
println()
}
}
} |
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
| #R | R | tau <- function(t)
{
results <- integer(0)
resultsCount <- 0
n <- 1
while(resultsCount != t)
{
condition <- function(n) (n %% length(c(Filter(function(x) n %% x == 0, seq_len(n %/% 2)), n))) == 0
if(condition(n))
{
resultsCount <- resultsCount + 1
results[resultsCount] <- n
}
n <- n + 1
}
results
}
tau(100) |
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
| #Raku | Raku | use Prime::Factor:ver<0.3.0+>;
use Lingua::EN::Numbers;
say "\nTau function - first 100:\n", # ID
(1..*).map({ +.&divisors })[^100]\ # the task
.batch(20)».fmt("%3d").join("\n"); # display formatting
say "\nTau numbers - first 100:\n", # ID
(1..*).grep({ $_ %% +.&divisors })[^100]\ # the task
.batch(10)».&comma».fmt("%5s").join("\n"); # display formatting
say "\nDivisor sums - first 100:\n", # ID
(1..*).map({ [+] .&divisors })[^100]\ # the task
.batch(20)».fmt("%4d").join("\n"); # display formatting
say "\nDivisor products - first 100:\n", # ID
(1..*).map({ [×] .&divisors })[^100]\ # the task
.batch(5)».&comma».fmt("%16s").join("\n"); # display formatting |
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
| #zkl | zkl | // Limited to ASCII
// This is limited to the max items a Dictionary can hold
fcn teacut(wordFile){
words:=File(wordFile).pump(Dictionary().add.fp1(True),"strip");
seen :=Dictionary();
foreach word in (words.keys){
rots,w,sz := List(), word, word.len();
if(sz>2 and word.unique().len()>2 and not seen.holds(word)){
do(sz-1){
w=String(w[-1],w[0,-1]); // rotate one character
if(not words.holds(w)) continue(2); // not a word, skip these
rots.append(w); // I'd like to see all the rotations
}
println(rots.append(word).sort().concat(" "));
rots.pump(seen.add.fp1(True)); // we've seen these rotations
}
}
} |
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
| #Bracmat | Bracmat | ( ( rational2fixedpoint
= minus fixedpointnumber number decimals
. !arg:(#?number.~<0:~/#?decimals)
& ( !number:0&"0.0"
| ( !number:>0&
| -1*!number:?number&"-"
)
: ?minus
& !number+1/2*10^(-1*!decimals):?number
& !minus div$(!number.1) ".":?fixedpointnumber
& whl
' ( !decimals+-1:~<0:?decimals
& !fixedpointnumber
div$(mod$(!number.1)*10:?number.1)
: ?fixedpointnumber
)
& str$!fixedpointnumber
)
)
& ( fixedpoint2rational
= integerpart fractionalpart decimals
. @( !arg
: #?integerpart
( "." ?fractionalpart
| &0:?fractionalpart
)
)
& @(!fractionalpart:? #?fractionalpart [?decimals)
& !integerpart
+ (!integerpart:<0&-1|1)
* 10^(-1*!decimals)
* !fractionalpart
)
& whl
' ( put$"Enter Kelvin temperature:"
& fixedpoint2rational$(get'(,STR)):?kelvin
& !kelvin+-27315/100:?celcius
& (degree=.str$(chu$(x2d$b0) !arg))
& out$(rational2fixedpoint$(!kelvin.2) K)
& out$(rational2fixedpoint$(!celcius.2) degree$C)
& out$(rational2fixedpoint$(!celcius*9/5+32.2) degree$F)
& out$(rational2fixedpoint$(!kelvin*9/5.2) degree$Ra)
& out$(rational2fixedpoint$(!celcius*4/5.2) degree$Ré)
)
& done!
) |
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
| #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | DivisorSum[#, 1 &] & /@ Range[100] |
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
| #Modula-2 | Modula-2 | MODULE TauFunc;
FROM InOut IMPORT WriteCard, WriteLn;
VAR i: CARDINAL;
PROCEDURE tau(n: CARDINAL): CARDINAL;
VAR total, count, p: CARDINAL;
BEGIN
total := 1;
WHILE n MOD 2 = 0 DO
n := n DIV 2;
total := total + 1
END;
p := 3;
WHILE p*p <= n DO
count := 1;
WHILE n MOD p = 0 DO
n := n DIV p;
count := count + 1
END;
total := total * count;
p := p + 2
END;
IF n>1 THEN total := total * 2 END;
RETURN total;
END tau;
BEGIN
FOR i := 1 TO 100 DO
WriteCard(tau(i), 3);
IF i MOD 20 = 0 THEN WriteLn END
END
END TauFunc. |
http://rosettacode.org/wiki/Terminal_control/Clear_the_screen | Terminal control/Clear the screen | Task
Clear the terminal window.
| #Octave | Octave | system clear; |
http://rosettacode.org/wiki/Terminal_control/Clear_the_screen | Terminal control/Clear the screen | Task
Clear the terminal window.
| #Pascal | Pascal | clrscr; |
http://rosettacode.org/wiki/Terminal_control/Clear_the_screen | Terminal control/Clear the screen | Task
Clear the terminal window.
| #Perl | Perl | system('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
| #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | Maybe /: ! Maybe = Maybe;
Maybe /: (And | Or | Nand | Nor | Xor | Xnor | Implies | Equivalent)[Maybe, Maybe] = Maybe; |
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
| #.D0.9C.D0.9A-61.2F52 | МК-61/52 | П0 Сx С/П ^ 1 + 3 * + 1
+ 3 x^y ИП0 <-> / [x] ^ ^ 3
/ [x] 3 * - 1 - С/П 1 5
6 3 3 БП 00 1 9 5 6 9
БП 00 1 5 9 2 9 БП 00 1
5 6 6 5 БП 00 /-/ ЗН С/П |
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.
| #PL.2FI | PL/I | text1: procedure options (main); /* 13 May 2010 */
declare line character (2000) varying;
declare 1 pairs(24),
2 value fixed (10,4),
2 flag fixed;
declare date character (12) varying;
declare no_items fixed decimal (10);
declare (nv, sum, line_no, ndud_values, max_ndud_values) fixed;
declare (i, k) fixed binary;
declare in file input;
open file (in) title ('/TEXT1.DAT,TYPE(TEXT),RECSIZE(2000)' );
on endfile (in) go to finish_up;
line_no = 0;
loop:
do forever;
get file (in) edit (line) (L);
/* put skip list (line); */
line = translate(line, ' ', '09'x);
line_no = line_no + 1;
line = trim(line);
no_items = tally(line, ' ') - tally(line, ' ') + 1;
if no_items ^= 49 then
do; put skip list ('There are not 49 items on this line'); iterate loop; end;
k = index(line, ' '); /* Find the first blank in the line. */
date = substr(line, 1, k);
line = substr(line, k) || ' ';
on conversion go to loop;
get string (line) list (pairs);
sum, nv, ndud_values, max_ndud_values = 0;
do i = 1 to 24;
if flag(i) > 0 then
do; sum = sum + value(i); nv = nv + 1;
ndud_values = 0; /* reset the counter of dud values */
end;
else
do; /* we have a dud reading. */
ndud_values = ndud_values + 1;
if ndud_values > max_ndud_values then
max_ndud_values = ndud_values;
end;
end;
if nv = 0 then iterate;
put skip list ('Line ' || trim(line_no) || ' average=', divide(sum, nv, 10,4) );
if max_ndud_values > 0 then
put skip list ('Maximum run of dud readings =', max_ndud_values);
end;
finish_up:
end text1; |
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
| #Logo | Logo | make "numbers [first second third fourth fifth sixth seventh eighth ninth tenth eleventh twelfth]
make "gifts [[And a partridge in a pear tree] [Two turtle doves] [Three French hens]
[Four calling birds] [Five gold rings] [Six geese a-laying]
[Seven swans a-swimming] [Eight maids a-miling] [Nine ladies dancing]
[Ten lords a-leaping] [Eleven pipers piping] [Twelve drummers drumming]]
to nth :n
print (sentence [On the] (item :n :numbers) [day of Christmas, my true love sent to me])
end
nth 1
print [A partridge in a pear tree]
for [d 2 12] [
print []
nth :d
for [g :d 1] [
print item :g gifts
]
]
bye |
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
| #LOLCODE | LOLCODE | CAN HAS STDIO?
HAI 1.2
I HAS A Dayz ITZ A BUKKIT
Dayz HAS A SRS 1 ITZ "first"
Dayz HAS A SRS 2 ITZ "second"
Dayz HAS A SRS 3 ITZ "third"
Dayz HAS A SRS 4 ITZ "fourth"
Dayz HAS A SRS 5 ITZ "fifth"
Dayz HAS A SRS 6 ITZ "sixth"
Dayz HAS A SRS 7 ITZ "seventh"
Dayz HAS A SRS 8 ITZ "eighth"
Dayz HAS A SRS 9 ITZ "ninth"
Dayz HAS A SRS 10 ITZ "tenth"
Dayz HAS A SRS 11 ITZ "eleventh"
Dayz HAS A SRS 12 ITZ "twelfth"
I HAS A Prezents ITZ A BUKKIT
Prezents HAS A SRS 1 ITZ "A partridge in a pear tree"
Prezents HAS A SRS 2 ITZ "Two turtle doves"
Prezents HAS A SRS 3 ITZ "Three French hens"
Prezents HAS A SRS 4 ITZ "Four calling birds"
Prezents HAS A SRS 5 ITZ "Five gold rings"
Prezents HAS A SRS 6 ITZ "Six geese a-laying"
Prezents HAS A SRS 7 ITZ "Seven swans a-swimming"
Prezents HAS A SRS 8 ITZ "Eight maids a-milking"
Prezents HAS A SRS 9 ITZ "Nine ladies dancing"
Prezents HAS A SRS 10 ITZ "Ten lords a-leaping"
Prezents HAS A SRS 11 ITZ "Eleven pipers piping"
Prezents HAS A SRS 12 ITZ "Twelve drummers drumming"
IM IN YR Outer UPPIN YR i WILE DIFFRINT i AN 12
I HAS A Day ITZ SUM OF i AN 1
VISIBLE "On the " !
VISIBLE Dayz'Z SRS Day !
VISIBLE " day of Christmas, my true love sent to me"
IM IN YR Inner UPPIN YR j WILE DIFFRINT j AN Day
I HAS A Count ITZ DIFFERENCE OF Day AN j
VISIBLE Prezents'Z SRS Count
IM OUTTA YR Inner
BOTH SAEM i AN 0
O RLY?
YA RLY
Prezents'Z SRS 1 R "And a partridge in a pear tree"
OIC
DIFFRINT i AN 11
O RLY?
YA RLY
VISIBLE ""
OIC
IM OUTTA YR Outer
KTHXBYE |
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)
| #Rust | Rust | const ESC: &str = "\x1B[";
const RESET: &str = "\x1B[0m";
fn main() {
println!("Foreground¦Background--------------------------------------------------------------");
print!(" ¦");
for i in 40..48 {
print!(" ESC[{}m ", i);
}
println!("\n----------¦------------------------------------------------------------------------");
for i in 30..38 {
print!("{}ESC[{}m ¦{}{1}m", RESET, i, ESC);
for j in 40..48 {
print!("{}{}m Rosetta ", ESC, j);
}
println!("{}", RESET);
print!("{}ESC[{};1m ¦{}{1};1m", RESET, i, ESC);
for j in 40..48 {
print!("{}{}m Rosetta ", ESC, j);
}
println!("{}", RESET);
}
} |
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)
| #Scala | Scala | object ColouredText extends App {
val ESC = "\u001B"
val (normal, bold, blink, black, white) =
(ESC + "[0", ESC + "[1"
, ESC + "[5" // not working on my machine
, ESC + "[0;40m" // black background
, ESC + "[0;37m" // normal white foreground
)
print(s"${ESC}c") // clear terminal first
print(black) // set background color to black
def foreColors = Map(
";31m" -> "red",
";32m" -> "green",
";33m" -> "yellow",
";34m" -> "blue",
";35m" -> "magenta",
";36m" -> "cyan",
";37m" -> "white")
Seq(normal, bold, blink).flatMap(attr => foreColors.map(color => (attr, color)))
.foreach { case (attr, (seq, text)) => println(s"$attr${seq}${text}") }
println(white) // set foreground color to normal white
}
|
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.
| #Euphoria | Euphoria | sequence lines
sequence count
lines = {}
count = {}
procedure read(integer fn)
object line
while 1 do
line = gets(fn)
if atom(line) then
exit
else
lines = append(lines, line)
task_yield()
end if
end while
lines = append(lines,0)
while length(count) = 0 do
task_yield()
end while
printf(1,"Count: %d\n",count[1])
end procedure
procedure write(integer fn)
integer n
object line
n = 0
while 1 do
while length(lines) = 0 do
task_yield()
end while
line = lines[1]
lines = lines[2..$]
if atom(line) then
exit
else
puts(fn,line)
n += 1
end if
end while
count = append(count,n)
end procedure
integer fn
atom reader, writer
constant stdout = 1
fn = open("input.txt","r")
reader = task_create(routine_id("read"),{fn})
writer = task_create(routine_id("write"),{stdout})
task_schedule(writer,1)
task_schedule(reader,1)
while length(task_list()) > 1 do
task_yield()
end while |
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.
| #REXX | REXX | ╔════════╤════════════════════════════════════════════════════════════════════════╤══════╗
╟────────┘ Format of an entry in the USA address/city/state/zip code structure: └──────╢
║ ║
║ The structure name can be any variable name, but here it'll be shortened to make these║
║ comments and program easier to read; its name will be: @USA or @usa (or both).║
║ ║
║ Each of the variable names beginning with an underscore (_) aren't to be used elsewhere║
║ in the program. Other possibilities are to have a trailing underscore (or both) or ║
║ some other special eye─catching character such as: ! @ # $ ? ║
║ ║
║ Any field not specified will have a value of a null (which has a length of zero). ║
║ ║
║ Any field may contain any number of characters, this can be limited by the ║
║ restrictions imposed by the standards or the USA legal definitions. ║
║ Any number of fields could be added (with testing for invalid fields). ║
╟────────────────────────────────────────────────────────────────────────────────────────╢
║ @USA.0 the number of entries in the @USA stemmed array. ║
║ ║
║ nnn is some positive integer of any length (no leading zeros). ║
╟────────────────────────────────────────────────────────────────────────────────────────╢
║ @USA.nnn._name is the name of person, business, or a lot description. ║
╟────────────────────────────────────────────────────────────────────────────────────────╢
║ @USA.nnn._addr1 is the 1st street address ║
║ @USA.nnn._addr2 is the 2nd street address ║
║ @USA.nnn._addr3 is the 3rd street address ║
║ @USA.nnn._addrNN ··· (any number, but in sequential order). ║
╟────────────────────────────────────────────────────────────────────────────────────────╢
║ @USA.nnn._state is the USA postal code for the state, territory, etc. ║
╟────────────────────────────────────────────────────────────────────────────────────────╢
║ @USA.nnn._city is the official city name, it may include any character. ║
╟────────────────────────────────────────────────────────────────────────────────────────╢
║ @USA.nnn._zip is the USA postal zip code (five or ten digit format). ║
╟────────────────────────────────────────────────────────────────────────────────────────╢
║ @USA.nnn._upHist is the update history: userID who did the update; date, timestamp.║
╚════════════════════════════════════════════════════════════════════════════════════════╝
|
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.
| #Ring | Ring |
# Project : Table creation/Postal addresses
load "stdlib.ring"
oSQLite = sqlite_init()
sqlite_open(oSQLite,"mytest.db")
sql = "CREATE TABLE ADDRESS (" +
"addrID INT NOT NULL," +
"street CHAR(50) NOT NULL," +
"city CHAR(25) NOT NULL," +
"state CHAR(2), NOT NULL" +
"zip CHAR(20) NOT NULL);"
sqlite_execute(oSQLite,sql)
|
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.
| #Ruby | Ruby | require 'pstore'
require 'set'
Address = Struct.new :id, :street, :city, :state, :zip
db = PStore.new("addresses.pstore")
db.transaction do
db[:next] ||= 0 # Next available Address#id
db[:ids] ||= Set[] # Set of all ids in db
end |
http://rosettacode.org/wiki/System_time | System time | Task
Output the system time (any units will do as long as they are noted) either by a system command or one built into the language.
The system time can be used for debugging, network information, random number seeds, or something as simple as program performance.
Related task
Date format
See also
Retrieving system time (wiki)
| #AArch64_Assembly | AArch64 Assembly |
/* ARM assembly AARCH64 Raspberry PI 3B */
/* program sysTime64.s */
/*******************************************/
/* Constantes file */
/*******************************************/
/* for this file see task include a file in language AArch64 assembly*/
.include "../includeConstantesARM64.inc"
.equ GETTIME, 169 // call system linux gettimeofday
/*******************************************/
/* Structures */
/********************************************/
/* example structure time */
.struct 0
timeval_sec: //
.struct timeval_sec + 8
timeval_usec: //
.struct timeval_usec + 8
timeval_end:
.struct 0
timezone_min: //
.struct timezone_min + 8
timezone_dsttime: //
.struct timezone_dsttime + 8
timezone_end:
/*********************************/
/* Initialized data */
/*********************************/
.data
szMessEmpty: .asciz "Empty queue. \n"
szMessNotEmpty: .asciz "Not empty queue. \n"
szMessError: .asciz "Error detected !!!!. \n"
szMessResult: .asciz "GMT: @/@/@ @:@:@ @ms\n" // message result
szCarriageReturn: .asciz "\n"
.align 4
tbDayMonthYear: .quad 0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335
.quad 366, 397, 425, 456, 486, 517, 547, 578, 609, 639, 670, 700
.quad 731, 762, 790, 821, 851, 882, 912, 943, 974,1004,1035,1065
.quad 1096,1127,1155,1186,1216,1247,1277,1308,1339,1369,1400,1430
/*********************************/
/* UnInitialized data */
/*********************************/
.bss
.align 4
stTVal: .skip timeval_end
stTZone: .skip timezone_end
sZoneConv: .skip 100
/*********************************/
/* code section */
/*********************************/
.text
.global main
main: // entry of program
ldr x0,qAdrstTVal // time zones
ldr x1,qAdrstTZone
mov x8,GETTIME // call system
svc 0
cmp x0,-1 // error ?
beq 99f
ldr x1,qAdrstTVal
ldr x0,[x1,timeval_sec] // timestamp in second
bl convTimeStamp
//ldr x0,qTStest1
//bl convTimeStamp
//ldr x0,qTStest2
//bl convTimeStamp
//ldr x0,qTStest3
//bl convTimeStamp
b 100f
99:
ldr x0,qAdrszMessError
bl affichageMess
100: // standard end of the program
mov x0,0 // return code
mov x8,EXIT // request to exit program
svc 0 // perform the system call
qAdrszMessError: .quad szMessError
qAdrstTVal: .quad stTVal
qAdrstTZone: .quad stTZone
qAdrszMessResult: .quad szMessResult
qAdrszCarriageReturn: .quad szCarriageReturn
qTStest1: .quad 1609508339 // 01/01/2021
qTStest2: .quad 1657805939 // 14/07/2022
qTStest3: .quad 1767221999 // 31/12/2025
/******************************************************************/
/* conversion timestamp to date */
/******************************************************************/
/* x0 contains the value of timestamp */
convTimeStamp:
stp x1,lr,[sp,-16]! // save registers
ldr x2,qSecJan2020
sub x3,x0,x2 // total secondes to 01/01/2020
mov x4,60
udiv x5,x3,x4
msub x6,x5,x4,x3 // compute secondes
udiv x3,x5,x4
msub x7,x3,x4,x5 // compute minutes
mov x4,24
udiv x5,x3,x4
msub x8,x5,x4,x3 // compute hours
mov x4,(365 * 4 + 1)
udiv x9,x5,x4
lsl x9,x9,2 // multiply by 4 = year1
udiv x12,x5,x4
msub x10,x12,x4,x5
ldr x11,qAdrtbDayMonthYear
mov x12,3
mov x13,12
1:
mul x14,x13,x12
ldr x15,[x11,x14,lsl 3] // load days by year
cmp x10,x15
bge 2f
sub x12,x12,1
cmp x12,0
cbnz x12,1b
2: // x12 = year2
mov x16,11
mul x15,x13,x12
lsl x15,x15,3 // * par 8
add x14,x15,x11
3:
ldr x15,[x14,x16,lsl 3] // load days by month
cmp x10,x15
bge 4f
sub x16,x16,1
cmp x16,0
cbnz x16,3b
4: // x16 = month - 1
mul x15,x13,x12
add x15,x15,x16
ldr x1,qAdrtbDayMonthYear
ldr x3,[x1,x15,lsl 3]
sub x0,x10,x3
add x0,x0,1 // final compute day
ldr x1,qAdrsZoneConv
bl conversion10
ldr x0,qAdrszMessResult
ldr x1,qAdrsZoneConv
bl strInsertAtCharInc // insert result at first @ character
mov x2,x0
add x0,x16,1 // final compute month
ldr x1,qAdrsZoneConv
bl conversion10
mov x0,x2
ldr x1,qAdrsZoneConv
bl strInsertAtCharInc // insert result at next @ character
mov x2,x0
add x0,x9,2020
add x0,x0,x12 // final compute year = 2020 + year1 + year2
ldr x1,qAdrsZoneConv
bl conversion10
mov x0,x2
ldr x1,qAdrsZoneConv
bl strInsertAtCharInc // insert result at next @ character
mov x2,x0
mov x0,x8 // hours
ldr x1,qAdrsZoneConv
bl conversion10
mov x0,x2
ldr x1,qAdrsZoneConv
bl strInsertAtCharInc // insert result at next @ character
mov x2,x0
mov x0,x7 // minutes
ldr x1,qAdrsZoneConv
bl conversion10
mov x0,x2
ldr x1,qAdrsZoneConv
bl strInsertAtCharInc // insert result at next @ character
mov x2,x0
mov x0,x6 // secondes
ldr x1,qAdrsZoneConv
bl conversion10
mov x0,x2
ldr x1,qAdrsZoneConv
bl strInsertAtCharInc // insert result at next @ character
mov x2,x0
ldr x1,qAdrstTVal
ldr x0,[x1,timeval_usec] // millisecondes
ldr x1,qAdrsZoneConv
bl conversion10
mov x0,x2
ldr x1,qAdrsZoneConv
bl strInsertAtCharInc // insert result at next @ character
bl affichageMess
b 100f
99:
ldr x0,qAdrszMessError
bl affichageMess
100:
ldp x1,lr,[sp],16 // restaur 2 registers
ret // return to address lr x30
qAdrsZoneConv: .quad sZoneConv
qSecJan2020: .quad 1577836800
qAdrtbDayMonthYear: .quad tbDayMonthYear
/********************************************************/
/* File Include fonctions */
/********************************************************/
/* for this file see task include a file in language AArch64 assembly */
.include "../includeARM64.inc"
|
http://rosettacode.org/wiki/System_time | System time | Task
Output the system time (any units will do as long as they are noted) either by a system command or one built into the language.
The system time can be used for debugging, network information, random number seeds, or something as simple as program performance.
Related task
Date format
See also
Retrieving system time (wiki)
| #ABAP | ABAP | REPORT system_time.
WRITE: sy-uzeit. |
http://rosettacode.org/wiki/Summarize_and_say_sequence | Summarize and say sequence | There are several ways to generate a self-referential sequence. One very common one (the Look-and-say sequence) is to start with a positive integer, then generate the next term by concatenating enumerated groups of adjacent alike digits:
0, 10, 1110, 3110, 132110, 1113122110, 311311222110 ...
The terms generated grow in length geometrically and never converge.
Another way to generate a self-referential sequence is to summarize the previous term.
Count how many of each alike digit there is, then concatenate the sum and digit for each of the sorted enumerated digits. Note that the first five terms are the same as for the previous sequence.
0, 10, 1110, 3110, 132110, 13123110, 23124110 ...
Sort the digits largest to smallest. Do not include counts of digits that do not appear in the previous term.
Depending on the seed value, series generated this way always either converge to a stable value or to a short cyclical pattern. (For our purposes, I'll use converge to mean an element matches a previously seen element.) The sequence shown, with a seed value of 0, converges to a stable value of 1433223110 after 11 iterations. The seed value that converges most quickly is 22. It goes stable after the first element. (The next element is 22, which has been seen before.)
Task
Find all the positive integer seed values under 1000000, for the above convergent self-referential sequence, that takes the largest number of iterations before converging. Then print out the number of iterations and the sequence they return. Note that different permutations of the digits of the seed will yield the same sequence. For this task, assume leading zeros are not permitted.
Seed Value(s): 9009 9090 9900
Iterations: 21
Sequence: (same for all three seeds except for first element)
9009
2920
192210
19222110
19323110
1923123110
1923224110
191413323110
191433125110
19151423125110
19251413226110
1916151413325110
1916251423127110
191716151413326110
191726151423128110
19181716151413327110
19182716151423129110
29181716151413328110
19281716151423228110
19281716151413427110
19182716152413228110
Related tasks
Fours is the number of letters in the ...
Look-and-say sequence
Number names
Self-describing numbers
Spelling of ordinal numbers
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
Also see
The On-Line Encyclopedia of Integer Sequences.
| #Ada | Ada | with Ada.Text_IO; use Ada.Text_IO;
with Ada.Containers.Vectors;
procedure SelfRef is
subtype Seed is Natural range 0 .. 1_000_000;
subtype Num is Natural range 0 .. 10;
type NumList is array (0 .. 10) of Num;
package IO is new Ada.Text_IO.Integer_IO (Natural);
package DVect is new Ada.Containers.Vectors (Positive, NumList);
function Init (innum : Seed) return NumList is
list : NumList := (others => 0);
number : Seed := innum; d : Num;
begin
loop
d := Num (number mod 10);
list (d) := list (d) + 1;
number := number / 10; exit when number = 0;
end loop; return list;
end Init;
procedure Next (inoutlist : in out NumList) is
list : NumList := (others => 0);
begin
for i in list'Range loop
if inoutlist (i) /= 0 then
list (i) := list (i) + 1;
list (inoutlist (i)) := list (inoutlist (i)) + 1;
end if;
end loop; inoutlist := list;
end Next;
procedure Show (list : NumList) is begin
for i in reverse list'Range loop
if list (i) > 0 then
IO.Put (list (i), Width => 1); IO.Put (i, Width => 1);
end if;
end loop; New_Line;
end Show;
function Iterate (theseed : Seed; p : Boolean) return Natural is
list : NumList := Init (theseed);
vect : DVect.Vector;
begin
vect.Append (list);
loop
if p then Show (list); end if;
Next (list); exit when vect.Contains (list); vect.Append (list);
end loop;
return Integer (DVect.Length (vect)) + 1;
end Iterate;
mseed : Seed;
len, maxlen : Natural := 0;
begin
for i in Seed'Range loop
len := Iterate (i, False);
if len > maxlen then mseed := i; maxlen := len; end if;
end loop;
IO.Put (maxlen, Width => 1); Put_Line (" Iterations:");
IO.Put (mseed, Width => 1); New_Line;
len := Iterate (mseed, True);
end SelfRef; |
http://rosettacode.org/wiki/Summarize_primes | Summarize primes | Task
Considering in order of length, n, all sequences of consecutive
primes, p, from 2 onwards, where p < 1000 and n>0, select those
sequences whose sum is prime, and for these display the length of the
sequence, the last item in the sequence, and the sum.
| #ALGOL_68 | ALGOL 68 | BEGIN # sum the primes below n and report the sums that are prime #
# sieve the primes to 999 #
PR read "primes.incl.a68" PR
[]BOOL prime = PRIMESIEVE 999;
# sum the primes and test the sum #
INT prime sum := 0;
INT prime count := 0;
INT prime sum count := 0;
print( ( "prime prime", newline ) );
print( ( "count prime sum", newline ) );
FOR i TO UPB prime DO
IF prime[ i ] THEN
# have another prime #
prime count +:= 1;
prime sum +:= i;
# check whether the prime sum is prime or not #
BOOL is prime := TRUE;
FOR p TO i OVER 2 WHILE is prime DO
IF prime[ p ] THEN is prime := prime sum MOD p /= 0 FI
OD;
IF is prime THEN
# the prime sum is also prime #
prime sum count +:= 1;
print( ( whole( prime count, -5 )
, " "
, whole( i, -6 )
, " "
, whole( prime sum, -6 )
, newline
)
)
FI
FI
OD;
print( ( newline
, "Found "
, whole( prime sum count, 0 )
, " prime sums of primes below "
, whole( UPB prime + 1, 0 )
, newline
)
)
END |
http://rosettacode.org/wiki/Summarize_primes | Summarize primes | Task
Considering in order of length, n, all sequences of consecutive
primes, p, from 2 onwards, where p < 1000 and n>0, select those
sequences whose sum is prime, and for these display the length of the
sequence, the last item in the sequence, and the sum.
| #ALGOL_W | ALGOL W | begin % sum the primes below n and report the sums that are prime %
integer MAX_NUMBER;
MAX_NUMBER := 999;
begin
logical array prime( 1 :: MAX_NUMBER );
integer primeCount, primeSum, primeSumCount;
% sieve the primes to MAX_NUMBER %
prime( 1 ) := false; prime( 2 ) := true;
for i := 3 step 2 until MAX_NUMBER do prime( i ) := true;
for i := 4 step 2 until MAX_NUMBER do prime( i ) := false;
for i := 3 step 2 until truncate( sqrt( MAX_NUMBER ) ) do begin
integer ii; ii := i + i;
if prime( i ) then begin
for p := i * i step ii until MAX_NUMBER do prime( p ) := false
end if_prime_i
end for_i ;
% find the prime sums that are prime %
primeCount := primeSum := primeSumCount := 0;
write( "prime prime" );
write( "count sum" );
for i := 1 until MAX_NUMBER do begin
if prime( i ) then begin
% have another prime %
logical isPrime;
primeSum := primeSum + i;
primeCount := primeCount + 1;
% check whether the prime sum is also prime %
isPrime := true;
for p := 1 until i div 2 do begin
if prime( p ) then begin
isPrime := primeSum rem p not = 0;
if not isPrime then goto endPrimeCheck
end if_prime_p
end for_p ;
endPrimeCheck:
if isPrime then begin
% the prime sum is also prime %
primeSumCount := primeSumCount + 1;
write( i_w := 5, s_w := 0
, primeCount
, " "
, i_w := 6
, primeSum
)
end if_isPrime
end if_prime_i
end for_i ;
write();
write( i_w := 1, s_w := 0
, "Found "
, primeSumCount
, " prime sums of primes below "
, MAX_NUMBER + 1
)
end
end. |
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.)
| #D | D | import std.stdio, std.array, std.range, std.typecons, std.algorithm;
struct Vec2 { // To be replaced with Phobos code.
double x, y;
Vec2 opBinary(string op="-")(in Vec2 other)
const pure nothrow @safe @nogc {
return Vec2(this.x - other.x, this.y - other.y);
}
typeof(x) cross(in Vec2 other) const pure nothrow @safe @nogc {
return this.x * other.y - this.y * other.x;
}
}
immutable(Vec2)[] clip(in Vec2[] subjectPolygon, in Vec2[] clipPolygon)
pure /*nothrow*/ @safe in {
assert(subjectPolygon.length > 1);
assert(clipPolygon.length > 1);
// Probably clipPolygon needs to be convex and probably
// its vertices need to be listed in a direction.
} out(result) {
assert(result.length > 1);
} body {
alias Edge = Tuple!(Vec2,"p", Vec2,"q");
static enum isInside = (in Vec2 p, in Edge cle)
pure nothrow @safe @nogc =>
(cle.q.x - cle.p.x) * (p.y - cle.p.y) >
(cle.q.y - cle.p.y) * (p.x - cle.p.x);
static Vec2 intersection(in Edge se, in Edge cle)
pure nothrow @safe @nogc {
immutable dc = cle.p - cle.q;
immutable dp = se.p - se.q;
immutable n1 = cle.p.cross(cle.q);
immutable n2 = se.p.cross(se.q);
immutable n3 = 1.0 / dc.cross(dp);
return Vec2((n1 * dp.x - n2 * dc.x) * n3,
(n1 * dp.y - n2 * dc.y) * n3);
}
// How much slower is this compared to lower-level code?
static enum edges = (in Vec2[] poly) pure nothrow @safe @nogc =>
// poly[$ - 1 .. $].chain(poly).zip!Edge(poly);
poly[$ - 1 .. $].chain(poly).zip(poly).map!Edge;
immutable(Vec2)[] result = subjectPolygon.idup; // Not nothrow.
foreach (immutable clipEdge; edges(clipPolygon)) {
immutable inputList = result;
result.destroy;
foreach (immutable inEdge; edges(inputList)) {
if (isInside(inEdge.q, clipEdge)) {
if (!isInside(inEdge.p, clipEdge))
result ~= intersection(inEdge, clipEdge);
result ~= inEdge.q;
} else if (isInside(inEdge.p, clipEdge))
result ~= intersection(inEdge, clipEdge);
}
}
return result;
}
// Code adapted from the C version.
void saveEPSImage(in string fileName, in Vec2[] subjPoly,
in Vec2[] clipPoly, in Vec2[] clipped)
in {
assert(!fileName.empty);
assert(subjPoly.length > 1);
assert(clipPoly.length > 1);
assert(clipped.length > 1);
} body {
auto eps = File(fileName, "w");
// The image bounding box is hard-coded, not computed.
eps.writeln(
"%%!PS-Adobe-3.0
%%%%BoundingBox: 40 40 360 360
/l {lineto} def
/m {moveto} def
/s {setrgbcolor} def
/c {closepath} def
/gs {fill grestore stroke} def
");
eps.writef("0 setlinewidth %g %g m ", clipPoly[0].tupleof);
foreach (immutable cl; clipPoly[1 .. $])
eps.writef("%g %g l ", cl.tupleof);
eps.writefln("c 0.5 0 0 s gsave 1 0.7 0.7 s gs");
eps.writef("%g %g m ", subjPoly[0].tupleof);
foreach (immutable s; subjPoly[1 .. $])
eps.writef("%g %g l ", s.tupleof);
eps.writefln("c 0 0.2 0.5 s gsave 0.4 0.7 1 s gs");
eps.writef("2 setlinewidth [10 8] 0 setdash %g %g m ",
clipped[0].tupleof);
foreach (immutable c; clipped[1 .. $])
eps.writef("%g %g l ", c.tupleof);
eps.writefln("c 0.5 0 0.5 s gsave 0.7 0.3 0.8 s gs");
eps.writefln("%%%%EOF");
eps.close;
writeln(fileName, " written.");
}
void main() {
alias V = Vec2;
immutable subjectPolygon = [V(50, 150), V(200, 50), V(350, 150),
V(350, 300), V(250, 300), V(200, 250),
V(150, 350), V(100, 250), V(100, 200)];
immutable clippingPolygon = [V(100, 100), V(300, 100),
V(300, 300), V(100, 300)];
immutable clipped = subjectPolygon.clip(clippingPolygon);
writefln("%(%s\n%)", clipped);
saveEPSImage("sutherland_hodgman_clipping_out.eps",
subjectPolygon, clippingPolygon, clipped);
} |
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).
| #Arturo | Arturo | a: ["John" "Bob" "Mary" "Serena"]
b: ["Jim" "Mary" "John" "Bob"]
print difference.symmetric a b |
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).
| #AutoHotkey | AutoHotkey | setA = John, Bob, Mary, Serena
setB = Jim, Mary, John, Bob
MsgBox,, Singles, % SymmetricDifference(setA, setB)
setA = John, Serena, Bob, Mary, Serena
setB = Jim, Mary, John, Jim, Bob
MsgBox,, Duplicates, % SymmetricDifference(setA, setB)
;---------------------------------------------------------------------------
SymmetricDifference(A, B) { ; returns the symmetric difference of A and B
;---------------------------------------------------------------------------
StringSplit, A_, A, `,, %A_Space%
Loop, %A_0%
If Not InStr(B, A_%A_Index%)
And Not InStr(Result, A_%A_Index%)
Result .= A_%A_Index% ", "
StringSplit, B_, B, `,, %A_Space%
Loop, %B_0%
If Not InStr(A, B_%A_Index%)
And Not InStr(Result, B_%A_Index%)
Result .= B_%A_Index% ", "
Return, SubStr(Result, 1, -2)
} |
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.
| #Go | Go | package main
import (
"fmt"
"math/big"
"strings"
"time"
)
func main() {
start := time.Now()
rd := []string{"22", "333", "4444", "55555", "666666", "7777777", "88888888", "999999999"}
one := big.NewInt(1)
nine := big.NewInt(9)
for i := big.NewInt(2); i.Cmp(nine) <= 0; i.Add(i, one) {
fmt.Printf("First 10 super-%d numbers:\n", i)
ii := i.Uint64()
k := new(big.Int)
count := 0
inner:
for j := big.NewInt(3); ; j.Add(j, one) {
k.Exp(j, i, nil)
k.Mul(i, k)
ix := strings.Index(k.String(), rd[ii-2])
if ix >= 0 {
count++
fmt.Printf("%d ", j)
if count == 10 {
fmt.Printf("\nfound in %d ms\n\n", time.Since(start).Milliseconds())
break inner
}
}
}
}
} |
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.
| #Haskell | Haskell | import Data.List (isInfixOf)
import Data.Char (intToDigit)
isSuperd :: (Show a, Integral a) => a -> a -> Bool
isSuperd p n =
(replicate <*> intToDigit) (fromIntegral p) `isInfixOf` show (p * n ^ p)
findSuperd :: (Show a, Integral a) => a -> [a]
findSuperd p = filter (isSuperd p) [1 ..]
main :: IO ()
main =
mapM_
(putStrLn .
("First 10 super-" ++) .
((++) . show <*> ((" : " ++) . show . take 10 . findSuperd)))
[2 .. 6] |
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.
| #Euphoria | Euphoria | constant cmd = command_line()
constant filename = "notes.txt"
integer fn
object line
sequence date_time
if length(cmd) < 3 then
fn = open(filename,"r")
if fn != -1 then
while 1 do
line = gets(fn)
if atom(line) then
exit
end if
puts(1,line)
end while
close(fn)
end if
else
fn = open(filename,"a") -- if such file doesn't exist it will be created
date_time = date()
date_time = date_time[1..6]
date_time[1] += 1900
printf(fn,"%d-%02d-%02d %d:%02d:%02d\n",date_time)
line = "\t"
for n = 3 to length(cmd) do
line &= cmd[n] & ' '
end for
line[$] = '\n'
puts(fn,line)
close(fn)
end if |
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.
| #F.23 | F# | open System;;
open System.IO;;
let file_path = "notes.txt";;
let show_notes () =
try
printfn "%s" <| File.ReadAllText(file_path)
with
_ -> printfn "Take some notes first!";;
let take_note (note : string) =
let now = DateTime.Now.ToString() in
let note = sprintf "%s\n\t%s" now note in
use file_stream = File.AppendText file_path in (* 'use' closes file_stream automatically when control leaves the scope *)
file_stream.WriteLine note;;
[<EntryPoint>]
let main args =
match Array.length args with
| 0 -> show_notes()
| _ -> take_note <| String.concat " " args;
0;; |
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
| #FreeBASIC | FreeBASIC | ' version 23-10-2016
' compile with: fbc -s console
Const scr_x = 800 ' screen 800 x 800
Const scr_y = 600
Const m_x = scr_x \ 2 ' middle of screen
Const m_y = scr_y \ 2
Sub superellipse(a As Long, b As Long, n As Double)
ReDim As Long y(0 To a)
Dim As Long x
y(0) = b ' value for x = 0
y(a) = 0 ' value for x = a
'(0,0) is in upper left corner
PSet (m_x, m_y - y(0)) ' set starting point
For x = 1 To a-1
y(x) = Int( Exp( Log(1 - ((x / a) ^ n)) / n ) * b )
Line - ((m_x + x), (m_y - y(x)))
Next
For x = a To 0 Step -1
Line - ((m_x + x), (m_y + y(x)))
Next
For x = 0 To a
Line - ((m_x - x), (m_y + y(x)))
Next
For x = a To 0 Step -1
Line - ((m_x - x), (m_y - y(x)))
Next
End Sub
' ------=< MAIN >=------
ScreenRes scr_x, scr_y, 32
Dim As Long a = 200
Dim As Long b = 150
Dim As Double n = 2.5
superellipse(a, b, n)
' empty keyboard buffer
While Inkey <> "" : Wend
Print : Print "hit any key to end program"
Sleep
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
| #PL.2FM | PL/M | 100H: /* CALCULATE ELEMENTS OF SYLVESTOR'S SEQUENCE */
BDOS: PROCEDURE( FN, ARG ); /* CP/M BDOS SYSTEM CALL */
DECLARE FN BYTE, ARG ADDRESS;
GOTO 5;
END BDOS;
PRINT$CHAR: PROCEDURE( C ); DECLARE C BYTE; CALL BDOS( 2, C ); END;
PRINT$STRING: PROCEDURE( S ); DECLARE S ADDRESS; CALL BDOS( 9, S ); END;
DECLARE PRINT$NL LITERALLY 'PRINT$STRING( .( 0DH, 0AH, ''$'' ) )';
DECLARE LONG$INTEGER LITERALLY '(201)BYTE';
DECLARE DIGIT$BASE LITERALLY '10';
/* PRINTS A LONG INTEGER */
PRINT$LONG$INTEGER: PROCEDURE( N$PTR );
DECLARE N$PTR ADDRESS;
DECLARE N BASED N$PTR LONG$INTEGER;
DECLARE ( D, F ) BYTE;
F = N( 0 );
DO D = 1 TO N( 0 );
CALL PRINT$CHAR( N( F ) + '0' );
F = F - 1;
END;
END PRINT$LONG$INTEGER;
/* IMPLEMENTS LONG MULTIPLICATION, C IS SET TO A * B */
/* C CAN BE THE SAME LONG$INTEGER AS A OR B */
LONG$MULTIPLY: PROCEDURE( A$PTR, B$PTR, C$PTR );
DECLARE ( A$PTR, B$PTR, C$PTR ) ADDRESS;
DECLARE ( A BASED A$PTR, B BASED B$PTR, C BASED C$PTR ) LONG$INTEGER;
DECLARE MRESULT LONG$INTEGER;
DECLARE RPOS BYTE;
/* MULTIPLIES THE LONG INTEGER IN B BY THE INTEGER A, THE RESULT */
/* IS ADDED TO C, STARTING FROM DIGIT START */
/* OVERFLOW IS IGNORED */
MULTIPLY$ELEMENT: PROCEDURE( A, B$PTR, C$PTR, START );
DECLARE ( B$PTR, C$PTR ) ADDRESS;
DECLARE ( A, START ) BYTE;
DECLARE ( B BASED B$PTR, C BASED C$PTR ) LONG$INTEGER;
DECLARE ( CDIGIT, D$CARRY, BPOS, CPOS ) BYTE;
D$CARRY = 0;
CPOS = START;
DO BPOS = 1 TO B( 0 );
CDIGIT = C( CPOS ) + ( A * B( BPOS ) ) + D$CARRY;
IF CDIGIT < DIGIT$BASE THEN D$CARRY = 0;
ELSE DO;
/* HAVE DIGITS TO CARRY */
D$CARRY = CDIGIT / DIGIT$BASE;
CDIGIT = CDIGIT MOD DIGIT$BASE;
END;
C( CPOS ) = CDIGIT;
CPOS = CPOS + 1;
END;
C( CPOS ) = D$CARRY;
/* REMOVE LEADING ZEROS BUT IF THE NUMBER IS 0, KEEP THE FINAL 0 */
DO WHILE( CPOS > 1 AND C( CPOS ) = 0 );
CPOS = CPOS - 1;
END;
C( 0 ) = CPOS;
END MULTIPLY$ELEMENT ;
/* THE RESULT WILL BE COMPUTED IN MRESULT, ALLOWING A OR B TO BE C */
DO RPOS = 1 TO LAST( MRESULT ); MRESULT( RPOS ) = 0; END;
/* MULTIPLY BY EACH DIGIT AND ADD TO THE RESULT */
DO RPOS = 1 TO A( 0 );
IF A( RPOS ) <> 0 THEN DO;
CALL MULTIPLY$ELEMENT( A( RPOS ), B$PTR, .MRESULT, RPOS );
END;
END;
/* RETURN THE RESULT IN C */
DO RPOS = 0 TO MRESULT( 0 ); C( RPOS ) = MRESULT( RPOS ); END;
END;
/* ADDS THE INTEGER A TO THE LONG$INTEGER N */
ADD$BYTE$TO$LONG$INTEGER: PROCEDURE( A, N$PTR );
DECLARE A BYTE, N$PTR ADDRESS;
DECLARE N BASED N$PTR LONG$INTEGER;
DECLARE ( D, D$CARRY, DIGIT ) BYTE;
D = 1;
D$CARRY = A;
DO WHILE( D$CARRY > 0 );
DIGIT = N( D ) + D$CARRY;
IF DIGIT < DIGIT$BASE THEN DO;
N( D ) = DIGIT;
D$CARRY = 0;
END;
ELSE DO;
D$CARRY = DIGIT / DIGIT$BASE;
N( D ) = DIGIT MOD DIGIT$BASE;
D = D + 1;
IF D > N( 0 ) THEN DO;
/* THE NUMBER NOW HAS AN EXTRA DIGIT */
N( 0 ) = D;
N( D ) = D$CARRY;
D$CARRY = 0;
END;
END;
END;
END ADD$BYTE$TO$LONG$INTEGER;
/* FIND THE FIRST 10 ELEMENTS OF SYLVESTOR'S SEQUENCE */
DECLARE ( SEQ$ELEMENT, PRODUCT ) LONG$INTEGER;
DECLARE ( I, D ) BYTE;
DO D = 2 TO LAST( PRODUCT ); PRODUCT( D ) = 0; END;
DO D = 2 TO LAST( SEQ$ELEMENT ); SEQ$ELEMENT( D ) = 0; END;
SEQ$ELEMENT( 0 ) = 1; /* THE FIRST SEQUENCE ELEMENT HAS 1 DIGIT... */
SEQ$ELEMENT( 1 ) = 2; /* WHICH IS 2 */
PRODUCT( 0 ) = 1;
PRODUCT( 1 ) = 2;
CALL PRINT$LONG$INTEGER( .SEQ$ELEMENT ); /* SHOW ELEMENT 1 */
CALL PRINT$NL;
DO I = 2 TO 9;
DO D = 0 TO PRODUCT( 0 ); SEQ$ELEMENT( D ) = PRODUCT( D ); END;
CALL ADD$BYTE$TO$LONG$INTEGER( 1, .SEQ$ELEMENT );
CALL PRINT$LONG$INTEGER( .SEQ$ELEMENT );
CALL LONG$MULTIPLY( .SEQ$ELEMENT, .PRODUCT, .PRODUCT );
CALL PRINT$NL;
END;
/* THE FINAL ELEMENT IS THE PRODUCT PLUS 1 */
CALL ADD$BYTE$TO$LONG$INTEGER( 1, .PRODUCT );
CALL PRINT$LONG$INTEGER( .PRODUCT );
CALL PRINT$NL;
EOF |
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
| #Prolog | Prolog | sylvesters_sequence(N, S, R):-
sylvesters_sequence(N, S, 2, R, 0).
sylvesters_sequence(0, [X], X, R, S):-
!,
R is S + 1 rdiv X.
sylvesters_sequence(N, [X|Xs], X, R, S):-
Y is X * X - X + 1,
M is N - 1,
T is S + 1 rdiv X,
sylvesters_sequence(M, Xs, Y, R, T).
main:-
sylvesters_sequence(9, Sequence, Sum),
writeln('First 10 elements in Sylvester\'s sequence:'),
forall(member(S, Sequence), writef('%t\n', [S])),
N is numerator(Sum),
D is denominator(Sum),
writef('\nSum of reciprocals: %t / %t\n', [N, D]). |
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
| #Python | Python | '''Sylvester's sequence'''
from functools import reduce
from itertools import count, islice
# sylvester :: [Int]
def sylvester():
'''Non-finite stream of the terms
of Sylvester's sequence.
(OEIS A000058)
'''
def go(n):
return 1 + reduce(
lambda a, x: a * go(x),
range(0, n),
1
) if 0 != n else 2
return map(go, count(0))
# ------------------------- TEST -------------------------
# main :: IO ()
def main():
'''First terms, and sum of reciprocals.'''
print("First 10 terms of OEIS A000058:")
xs = list(islice(sylvester(), 10))
print('\n'.join([
str(x) for x in xs
]))
print("\nSum of the reciprocals of the first 10 terms:")
print(
reduce(lambda a, x: a + 1 / x, xs, 0)
)
# MAIN ---
if __name__ == '__main__':
main() |
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).
| #jq | jq | # Output: an array of the form [i^3 + j^3, [i, j]] sorted by the sum.
# Only cubes of 1 to ($in-1) are considered; the listing is therefore truncated
# as it might not capture taxicab numbers greater than $in ^ 3.
def sum_of_two_cubes:
def cubed: .*.*.;
. as $in
| (cubed + 1) as $limit
| [range(1;$in) as $i | range($i;$in) as $j
| [ ($i|cubed) + ($j|cubed), [$i, $j] ] ] | sort
| map( select( .[0] < $limit ) );
# Output a stream of triples [t, d1, d2], in order of t,
# where t is a taxicab number, and d1 and d2 are distinct
# decompositions [i,j] with i^3 + j^3 == t.
# The stream includes each taxicab number once only.
#
def taxicabs0:
sum_of_two_cubes as $sums
| range(1;$sums|length) as $i
| if $sums[$i][0] == $sums[$i-1][0]
and ($i==1 or $sums[$i][0] != $sums[$i-2][0])
then [$sums[$i][0], $sums[$i-1][1], $sums[$i][1]]
else empty
end;
# Output a stream of $n taxicab triples: [t, d1, d2] as described above,
# without repeating t.
def taxicabs:
# If your jq includes until/2 then the following definition
# can be omitted:
def until(cond; next):
def _until: if cond then . else (next|_until) end; _until;
. as $n
| [10, ($n / 10 | floor)] | max as $increment
| [20, ($n / 2 | floor)] | max
| [ ., [taxicabs0] ]
| until( .[1] | length >= $m; (.[0] + $increment) | [., [taxicabs0]] )
| .[1][0:$n] ; |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.