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/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).
| #ZX_Spectrum_Basic | ZX Spectrum Basic | 10 DIM f(1625): REM populating a cube table at the start will be faster than computing the cubes on the fly
20 FOR x=1 TO 1625
30 LET f(x)=x*x*x: REM x*x*x rather than x^3 as the ZX Spectrum's exponentiation function is legendarily slow
40 NEXT x
50 LET c=0
60 FOR x=1 TO 4294967295: REM the highest number the ZX Spectrum Basic can accurately hold internally; floor (cuberoot max)=1625, hence the table limit
70 LET k=0
80 FOR m=1 TO 1625
90 FOR n=m+1 TO 1625
100 IF f(m)+f(n)=x THEN GOTO 160
110 IF f(n)>=x THEN LET n=1625: REM overshot, break out of the loop
120 IF f(m)>=x THEN LET m=1625
130 NEXT n
140 NEXT m
150 NEXT x
160 IF k=1 THEN LET q=m: LET r=n: GO TO 230: REM got one!
170 LET o=m
180 LET p=n
190 LET k=1
200 NEXT n
210 NEXT m
220 NEXT x
230 LET c=c+1
240 IF c>25 AND c<2000 THEN GO TO 330
250 LET t$="": REM convert number to string; while ZX Spectrum Basic can store all the digits of integers up to 2^32-1...
260 LET t=INT (x/100000): REM ...it will resort to scientific notation trying to display any more than eight digits
270 LET b=x-t*100000
280 IF t=0 THEN GO TO 300: REM omit leading zero
290 LET t$=STR$ t
300 LET t$=t$+STR$ b
310 PRINT c;":";t$;"=";q;"^3+";r;"^3=";o;"^3+";p;"^3"
320 POKE 23692,10: REM suppress "scroll?" prompt when screen fills up at c=22
330 IF c=2006 THEN LET x=4294967295: LET n=1625: LET m=1625
340 NEXT n
350 NEXT m
360 NEXT x |
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
| #Go | Go | package main
import (
"fmt"
"os"
"strconv"
)
func main() {
if len(os.Args) != 2 {
fmt.Println("Usage: k <Kelvin>")
return
}
k, err := strconv.ParseFloat(os.Args[1], 64)
if err != nil {
fmt.Println(err)
return
}
if k < 0 {
fmt.Println("Kelvin must be >= 0.")
return
}
fmt.Printf("K %.2f\n", k)
fmt.Printf("C %.2f\n", k-273.15)
fmt.Printf("F %.2f\n", k*9/5-459.67)
fmt.Printf("R %.2f\n", k*9/5)
} |
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
| #Yabasic | Yabasic |
tFalse = 0
tDontKnow = 1
tTrue = 2
sub not3(b)
return 2-b
end sub
sub and3(a,b)
return min(a,b)
end sub
sub or3(a,b)
return max(a,b)
end sub
sub eq3(a,b)
if a = tDontKnow or b = tDontKnow then
return tDontKnow
elsif a = b then
return tTrue
else
return tFalse
end if
end sub
sub xor3(a,b)
return not3(eq3(a,b))
end sub
sub shortName3$(i)
return mid$("F?T", i+1, 1)
end sub
sub longName3$(i)
switch i
case 1
return "Don't know"
case 2
return "True"
default
return "False"
end switch
end sub
print "Nombres cortos y largos para valores logicos ternarios:"
for i = tFalse to tTrue
print shortName3$(i), " ", longName3$(i)
next i
print
print "Funciones de parametro unico"
print "x", " ", "=x", " ", "not(x)"
for i = tFalse to tTrue
print shortName3$(i), " ", shortName3$(i), " ", shortName3$(not3(i))
next i
print
print "Funciones de doble parametro"
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), " ";
print shortName3$(and3(a,b)), " ", shortName3$(or3(a,b)), " ";
print shortName3$(eq3(a,b)), " ", shortName3$(xor3(a,b))
next b
next a
end
|
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
| #Scala | Scala | val gifts = Array(
"A partridge in a pear tree.",
"Two turtle doves and",
"Three French hens,",
"Four calling birds,",
"Five gold 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,"
)
val days = Array(
"first", "second", "third", "fourth", "fifth", "sixth",
"seventh", "eighth", "ninth", "tenth", "eleventh", "twelfth"
)
val giftsForDay = (day: Int) =>
"On the %s day of Christmas, my true love sent to me:\n".format(days(day)) +
gifts.take(day+1).reverse.mkString("\n") + "\n"
(0 until 12).map(giftsForDay andThen println)
|
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
| #Scheme | Scheme | ; Racket has this built in, but it's not standard
(define (take lst n)
(if (or (null? lst) (<= n 0))
'()
(cons (car lst) (take (cdr lst) (- n 1)))))
(let
((days '("first" "second" "third" "fourth" "fifth" "sixth" "seventh"
"eighth" "ninth" "tenth" "eleventh" "twelfth"))
(gifts '("A partridge in a pear tree." "Two turtle doves, and"
"Three French hens," "Four calling birds,"
"Five gold 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,")))
(do ((left days (cdr left))
; No universal predefined (+ 1) function, sadly. Implementations
; are divided between (add1) and (1+).
(day 1 (+ 1 day)))
((null? left) #t)
(display "On the ")
(display (car left))
(display " day of Christmas, my true love sent to me:")
(newline)
(do ((daily (reverse (take gifts day)) (cdr daily)))
((null? daily) #t)
(display (car daily))
(newline))
(newline)))
(exit) |
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.
| #UnixPipes | UnixPipes | rm -f node ; mkfifo node
cat file | tee >(wc -l > node ) | cat - node |
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.
| #Visual_Basic_.NET | Visual Basic .NET | Imports System.Threading
Module Module1
Sub Main()
Dim t1 As New Thread(AddressOf Reader)
Dim t2 As New Thread(AddressOf Writer)
t1.Start()
t2.Start()
t1.Join()
t2.Join()
End Sub
Sub Reader()
For Each line In IO.File.ReadAllLines("input.txt")
m_WriterQueue.Enqueue(line)
Next
m_WriterQueue.Enqueue(Nothing)
Dim result As Integer
Do Until m_ReaderQueue.TryDequeue(result)
Thread.Sleep(10)
Loop
Console.WriteLine(result)
End Sub
Sub Writer()
Dim count = 0
Dim line As String = Nothing
Do
Do Until m_WriterQueue.TryDequeue(line)
Thread.Sleep(10)
Loop
If line IsNot Nothing Then
Console.WriteLine(line)
count += 1
Else
m_ReaderQueue.Enqueue(count)
Exit Do
End If
Loop
End Sub
Private m_WriterQueue As New SafeQueue(Of String)
Private m_ReaderQueue As New SafeQueue(Of Integer)
End Module
Class SafeQueue(Of T)
Private m_list As New Queue(Of T)
Public Function TryDequeue(ByRef result As T) As Boolean
SyncLock m_list
If m_list.Count = 0 Then Return False
result = m_list.Dequeue
Return True
End SyncLock
End Function
Public Sub Enqueue(ByVal value As T)
SyncLock m_list
m_list.Enqueue(value)
End SyncLock
End Sub
End Class |
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)
| #Excel | Excel | =NOW() |
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)
| #F.23 | F# | printfn "%s" (System.DateTime.Now.ToString("u")) |
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.
| #JavaScript | JavaScript |
function selfReferential(n) {
n = n.toString();
let res = [n];
const makeNext = (n) => {
let matchs = {
'9':0,'8':0,'7':0,'6':0,'5':0,'4':0,'3':0,'2':0,'1':0,'0':0}, res = [];
for(let index=0;index<n.length;index++)
matchs[n[index].toString()]++;
for(let index=9;index>=0;index--)
if(matchs[index]>0)
res.push(matchs[index],index);
return res.join("").toString();
}
for(let i=0;i<10;i++)
res.push(makeNext(res[res.length-1]));
return [...new Set(res)];
}
|
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.)
| #TypeScript | TypeScript | interface XYCoords {
x : number;
y : number;
}
const inside = ( cp1 : XYCoords, cp2 : XYCoords, p : XYCoords) : boolean => {
return (cp2.x-cp1.x)*(p.y-cp1.y) > (cp2.y-cp1.y)*(p.x-cp1.x);
};
const intersection = ( cp1 : XYCoords ,cp2 : XYCoords ,s : XYCoords, e : XYCoords ) : XYCoords => {
const dc = {
x: cp1.x - cp2.x,
y : cp1.y - cp2.y
},
dp = { x: s.x - e.x,
y : s.y - e.y
},
n1 = cp1.x * cp2.y - cp1.y * cp2.x,
n2 = s.x * e.y - s.y * e.x,
n3 = 1.0 / (dc.x * dp.y - dc.y * dp.x);
return { x : (n1*dp.x - n2*dc.x) * n3,
y : (n1*dp.y - n2*dc.y) * n3
};
};
export const sutherland_hodgman = ( subjectPolygon : Array<XYCoords>,
clipPolygon : Array<XYCoords> ) : Array<XYCoords> => {
let cp1 : XYCoords = clipPolygon[clipPolygon.length-1];
let cp2 : XYCoords;
let s : XYCoords;
let e : XYCoords;
let outputList : Array<XYCoords> = subjectPolygon;
for( var j in clipPolygon ) {
cp2 = clipPolygon[j];
var inputList = outputList;
outputList = [];
s = inputList[inputList.length - 1]; // last on the input list
for (var i in inputList) {
e = inputList[i];
if (inside(cp1,cp2,e)) {
if (!inside(cp1,cp2,s)) {
outputList.push(intersection(cp1,cp2,s,e));
}
outputList.push(e);
}
else if (inside(cp1,cp2,s)) {
outputList.push(intersection(cp1,cp2,s,e));
}
s = e;
}
cp1 = cp2;
}
return outputList
} |
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.)
| #Sidef | Sidef | class Point(x, y) {
method to_s {
"(#{'%.2f' % x}, #{'%.2f' % y})"
}
}
func sutherland_hodgman(subjectPolygon, clipPolygon) {
var inside = { |cp1, cp2, p|
((cp2.x-cp1.x)*(p.y-cp1.y)) > ((cp2.y-cp1.y)*(p.x-cp1.x))
}
var intersection = { |cp1, cp2, s, e|
var (dcx, dcy) = (cp1.x-cp2.x, cp1.y-cp2.y)
var (dpx, dpy) = (s.x-e.x, s.y-e.y)
var n1 = (cp1.x*cp2.y - cp1.y*cp2.x)
var n2 = (s.x*e.y - s.y*e.x)
var n3 = (1 / (dcx*dpy - dcy*dpx))
Point((n1*dpx - n2*dcx) * n3, (n1*dpy - n2*dcy) * n3)
}
var outputList = subjectPolygon
var cp1 = clipPolygon.last
for cp2 in clipPolygon {
var inputList = outputList
outputList = []
var s = inputList.last
for e in inputList {
if (inside(cp1, cp2, e)) {
outputList << intersection(cp1, cp2, s, e) if !inside(cp1, cp2, s)
outputList << e
}
elsif(inside(cp1, cp2, s)) {
outputList << intersection(cp1, cp2, s, e)
}
s = e
}
cp1 = cp2
}
outputList
}
var subjectPolygon = [
[50, 150], [200, 50], [350, 150], [350, 300],
[250, 300], [200, 250], [150, 350], [100, 250],
[100, 200]
].map{|pnt| Point(pnt...) }
var clipPolygon = [
[100, 100], [300, 100],
[300, 300], [100, 300]
].map{|pnt| Point(pnt...) }
sutherland_hodgman(subjectPolygon, clipPolygon).each { .say } |
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).
| #Java | Java | import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
public class SymmetricDifference {
public static void main(String[] args) {
Set<String> setA = new HashSet<String>(Arrays.asList("John", "Serena", "Bob", "Mary", "Serena"));
Set<String> setB = new HashSet<String>(Arrays.asList("Jim", "Mary", "John", "Jim", "Bob"));
// Present our initial data set
System.out.println("In set A: " + setA);
System.out.println("In set B: " + setB);
// Option 1: union of differences
// Get our individual differences.
Set<String> notInSetA = new HashSet<String>(setB);
notInSetA.removeAll(setA);
Set<String> notInSetB = new HashSet<String>(setA);
notInSetB.removeAll(setB);
// The symmetric difference is the concatenation of the two individual differences
Set<String> symmetricDifference = new HashSet<String>(notInSetA);
symmetricDifference.addAll(notInSetB);
// Option 2: union minus intersection
// Combine both sets
Set<String> union = new HashSet<String>(setA);
union.addAll(setB);
// Get the intersection
Set<String> intersection = new HashSet<String>(setA);
intersection.retainAll(setB);
// The symmetric difference is the union of the 2 sets minus the intersection
Set<String> symmetricDifference2 = new HashSet<String>(union);
symmetricDifference2.removeAll(intersection);
// Present our results
System.out.println("Not in set A: " + notInSetA);
System.out.println("Not in set B: " + notInSetB);
System.out.println("Symmetric Difference: " + symmetricDifference);
System.out.println("Symmetric Difference 2: " + symmetricDifference2);
}
} |
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.
| #Scala | Scala | import java.io.{ FileNotFoundException, FileOutputStream, PrintStream }
import java.time.LocalDateTime
object TakeNotes extends App {
val notesFileName = "notes.txt"
if (args.length > 0) {
val ps = new PrintStream(new FileOutputStream(notesFileName, true))
ps.println(LocalDateTime.now() + args.mkString("\n\t", " ", "."))
ps.close()
} else try {
io.Source.fromFile(notesFileName).getLines().foreach(println)
} catch {
case e: FileNotFoundException => println(e.getLocalizedMessage())
case e: Throwable => {
println("Some other exception type:")
e.printStackTrace()
}
}
} |
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.
| #Scheme | Scheme | #lang racket
(require racket/date)
(define *notes* "NOTES.TXT")
(let ([a (vector->list (current-command-line-arguments))])
(cond
[(empty? a)
(with-handlers ([exn:fail? void])
(call-with-input-file *notes*
(lambda (fi)
(copy-port fi (current-output-port)))))
]
[else
(call-with-output-file *notes*
(lambda (fo)
(let ([ln (apply string-append (add-between a " "))]
[dt (date->string (current-date))])
(fprintf fo "~a~n\t~a~n" dt ln)))
#:mode 'text #:exists 'append)
])) |
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
| #zkl | zkl | fcn superEllipse(plot,n,color=0xff0000){ // we'll assume width <= height
a,p:=(plot.w/2).toFloat(), 1.0/n; // just calculate upper right quadrant
foreach x in ([0.0 .. a]){
y:=(a.pow(n) - x.pow(n)).pow(p); // a==b>0 --> y=(a^n - x^n)^(1/n)
//println( (x/a).abs().pow(n) + (y/b).abs().pow(n) ); // sanity check
plot[x,y]=plot[-x,-y]=plot[-x,y]=plot[x,-y]=color; // all 4 quadrants
}
plot
} |
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
| #Groovy | Groovy |
class Convert{
static void main(String[] args){
def c=21.0;
println("K "+c)
println("C "+k_to_c(c));
println("F "+k_to_f(k_to_c(c)));
println("R "+k_to_r(c));
}
static def k_to_c(def k=21.0){return k-273.15;}
static def k_to_f(def k=21.0){return ((k*9)/5)+32;}
static def k_to_r(def k=21.0){return k*1.8;}
}
|
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
| #Seed7 | Seed7 | $ include "seed7_05.s7i";
const proc: main is func
local
const array string: gifts is [] (
"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");
const array string: days is [] (
"first", "second", "third", "fourth", "fifth", "sixth",
"seventh", "eighth", "ninth", "tenth", "eleventh", "Twelfth");
var integer: day is 0;
var integer: gift is 0;
begin
for day range 1 to length(days) do
writeln;
writeln("On the " <& days[day] <& " day of Christmas,");
writeln("My true love gave to me:");
for gift range day downto 1 do
writeln(gifts[gift]);
end for;
end for;
end func; |
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
| #Self | Self | (|
parent* = traits oddball.
gifts = (
'And a partridge in a pear tree' &
'Two turtle doves' &
'Three french hens' &
'Four calling birds' &
'FIVE GO-OLD 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'
) asSequence.
days = (
'first' & 'second' & 'third' & 'fourth' &
'fifth' & 'sixth' & 'seventh' & 'eighth' &
'ninth' & 'tenth' & 'eleventh' & 'twelfth'
) asSequence.
intro: i = ( 'On the ', (days at: i), ' day of Christmas, my true love gave to me:').
gifts: i = ( i = 0 ifTrue: [sequence copyAddFirst: 'A partridge in a pear tree' ]
False: [(gifts slice: 0@(i + 1)) reverse ]).
verse: i = ( ((sequence copyAddFirst: intro: i) addAll: gifts: i) addLast: '' ).
value = ( (days gather: [|:d. :i| verse: i ]) asSequence joinUsing: '\n' )
|) value printLine
|
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.
| #Wren | Wren | import "io" for File
var EOT = "\x04"
var readLines = Fiber.new { |fileName|
var file = File.open(fileName)
var offset = 0
var line = ""
while (true) {
var b = file.readBytes(1, offset)
offset = offset + 1
if (b == "\n") {
Fiber.yield(line)
line = "" // reset line variable
} else if (b == "\r") { // Windows
// wait for following "\n"
} else if (b == "") { // end of stream
var numLines = Fiber.yield(EOT)
System.print("Number of lines read = %(numLines)")
break
} else {
line = line + b
}
}
file.close()
}
var numLines = 0
while(true) {
var line = readLines.call("input.txt")
if (line != EOT) {
System.print(line)
numLines = numLines + 1
} else {
readLines.call(numLines)
break
}
} |
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)
| #Factor | Factor | USE: calendar
now . |
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)
| #Falcon | Falcon |
/* Added by Aykayayciti Earl Lamont Montgomery
April 10th, 2018 */
> CurrentTime().toString()
|
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.
| #jq | jq | # Given any array, produce an array of [item, count] pairs for each run.
def runs:
reduce .[] as $item
( [];
if . == [] then [ [ $item, 1] ]
else .[length-1] as $last
| if $last[0] == $item
then (.[0:length-1] + [ [$item, $last[1] + 1] ] )
else . + [[$item, 1]]
end
end ) ;
# string to string
def next_self_referential:
def runs2integer: # input is an array as produced by runs,
# i.e. an array of [count, n] pairs, where count is an int,
# and n is an "exploded" digit
reduce .[] as $pair
(""; . + ($pair[1] | tostring) + ([$pair[0]]|implode) ) ;
explode | sort | reverse | runs | runs2integer;
# Given an integer as a string,
# compute the entire sequence (of strings) to convergence:
def sequence_of_self_referentials:
def seq:
. as $ary
| (.[length-1] | next_self_referential) as $next
| if ($ary|index($next)) then $ary
else $ary + [$next] | seq
end;
[.] | seq;
def maximals(n):
def interesting:
tostring | (. == (explode | sort | reverse | implode));
reduce range(0;n) as $i
([[], 0]; # maximalseeds, length
if ($i | interesting) then
($i|tostring|sequence_of_self_referentials|length) as $length
| if .[1] == $length then [ .[0] + [$i], $length]
elif .[1] < $length then [ [$i], $length]
else .
end
else .
end );
def task(n):
maximals(n) as $answer
| "The maximal length to convergence for seeds up to \(n) is \($answer[1]).",
"The corresponding seeds are the allowed permutations",
"of the representative number(s): \($answer[0][])",
"For each representative seed, the self-referential sequence is as follows:",
($answer[0][] | tostring
| ("Representative: \(.)",
"Self-referential sequence:",
(sequence_of_self_referentials | map(tonumber))))
;
task(1000000) |
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.)
| #Swift | Swift | struct Point {
var x: Double
var y: Double
}
struct Polygon {
var points: [Point]
init(points: [Point]) {
self.points = points
}
init(points: [(Double, Double)]) {
self.init(points: points.map({ Point(x: $0.0, y: $0.1) }))
}
}
func isInside(_ p1: Point, _ p2: Point, _ p3: Point) -> Bool {
(p3.x - p2.x) * (p1.y - p2.y) > (p3.y - p2.y) * (p1.x - p2.x)
}
func computeIntersection(_ p1: Point, _ p2: Point, _ s: Point, _ e: Point) -> Point {
let dc = Point(x: p1.x - p2.x, y: p1.y - p2.y)
let dp = Point(x: s.x - e.x, y: s.y - e.y)
let n1 = p1.x * p2.y - p1.y * p2.x
let n2 = s.x * e.y - s.y * e.x
let n3 = 1.0 / (dc.x * dp.y - dc.y * dp.x)
return Point(x: (n1 * dp.x - n2 * dc.x) * n3, y: (n1 * dp.y - n2 * dc.y) * n3)
}
func sutherlandHodgmanClip(subjPoly: Polygon, clipPoly: Polygon) -> Polygon {
var ring = subjPoly.points
var p1 = clipPoly.points.last!
for p2 in clipPoly.points {
let input = ring
var s = input.last!
ring = []
for e in input {
if isInside(e, p1, p2) {
if !isInside(s, p1, p2) {
ring.append(computeIntersection(p1, p2, s, e))
}
ring.append(e)
} else if isInside(s, p1, p2) {
ring.append(computeIntersection(p1, p2, s, e))
}
s = e
}
p1 = p2
}
return Polygon(points: ring)
}
let subj = Polygon(points: [
(50.0, 150.0),
(200.0, 50.0),
(350.0, 150.0),
(350.0, 300.0),
(250.0, 300.0),
(200.0, 250.0),
(150.0, 350.0),
(100.0, 250.0),
(100.0, 200.0)
])
let clip = Polygon(points: [
(100.0, 100.0),
(300.0, 100.0),
(300.0, 300.0),
(100.0, 300.0)
])
print(sutherlandHodgmanClip(subjPoly: subj, clipPoly: clip)) |
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.)
| #Tcl | Tcl | # Find intersection of an arbitrary polygon with a convex one.
package require Tcl 8.6
# Does the path (x0,y0)->(x1,y1)->(x2,y2) turn clockwise
# or counterclockwise?
proc cw {x0 y0 x1 y1 x2 y2} {
set dx1 [expr {$x1 - $x0}]; set dy1 [expr {$y1 - $y0}]
set dx2 [expr {$x2 - $x0}]; set dy2 [expr {$y2 - $y0}]
# (0,0,$dx1*$dy2 - $dx2*$dy1) is the crossproduct of
# ($x1-$x0,$y1-$y0,0) and ($x2-$x0,$y2-$y0,0).
# Its z-component is positive if the turn
# is clockwise, negative if the turn is counterclockwise.
set pr1 [expr {$dx1 * $dy2}]
set pr2 [expr {$dx2 * $dy1}]
if {$pr1 > $pr2} {
# Clockwise
return 1
} elseif {$pr1 < $pr2} {
# Counter-clockwise
return -1
} elseif {$dx1*$dx2 < 0 || $dy1*$dy2 < 0} {
# point 0 is the middle point
return 0
} elseif {($dx1*$dx1 + $dy1*$dy1) < ($dx2*$dx2 + $dy2+$dy2)} {
# point 1 is the middle point
return 0
} else {
# point 2 lies on the segment joining points 0 and 1
return 1
}
}
# Calculate the point of intersection of two lines
# containing the line segments (x1,y1)-(x2,y2) and (x3,y3)-(x4,y4)
proc intersect {x1 y1 x2 y2 x3 y3 x4 y4} {
set d [expr {($y4 - $y3) * ($x2 - $x1) - ($x4 - $x3) * ($y2 - $y1)}]
set na [expr {($x4 - $x3) * ($y1 - $y3) - ($y4 - $y3) * ($x1 - $x3)}]
if {$d == 0} {
return {}
}
set r [list \
[expr {$x1 + $na * ($x2 - $x1) / $d}] \
[expr {$y1 + $na * ($y2 - $y1) / $d}]]
return $r
}
# Coroutine that yields the elements of a list in pairs
proc pairs {list} {
yield [info coroutine]
foreach {x y} $list {
yield [list $x $y]
}
return {}
}
# Coroutine to clip one segment of a polygon against a line.
proc clipsegment {inside0 cx0 cy0 cx1 cy1 sx0 sy0 sx1 sy1} {
set inside1 [expr {[cw $cx0 $cy0 $cx1 $cy1 $sx1 $sy1] > 0}]
if {$inside1} {
if {!$inside0} {
set int [intersect $cx0 $cy0 $cx1 $cy1 \
$sx0 $sy0 $sx1 $sy1]
if {[llength $int] >= 0} {
yield $int
}
}
yield [list $sx1 $sy1]
} else {
if {$inside0} {
set int [intersect $cx0 $cy0 $cx1 $cy1 \
$sx0 $sy0 $sx1 $sy1]
if {[llength $int] >= 0} {
yield $int
}
}
}
return $inside1
}
# Coroutine to perform one step of Sutherland-Hodgman polygon clipping
proc clipstep {source cx0 cy0 cx1 cy1} {
yield [info coroutine]
set pt0 [{*}$source]
if {[llength $pt0] == 0} {
return
}
lassign $pt0 sx0 sy0
set inside0 [expr {[cw $cx0 $cy0 $cx1 $cy1 $sx0 $sy0] > 0}]
set finished 0
while {!$finished} {
set thispt [{*}$source]
if {[llength $thispt] == 0} {
set thispt $pt0
set finished 1
}
lassign $thispt sx1 sy1
set inside0 [clipsegment $inside0 \
$cx0 $cy0 $cx1 $cy1 $sx0 $sy0 $sx1 $sy1]
set sx0 $sx1
set sy0 $sy1
}
return {}
}
# Perform Sutherland-Hodgman polygon clipping
proc clippoly {cpoly spoly} {
variable clipindx
set source [coroutine clipper[incr clipindx] pairs $spoly]
set cx0 [lindex $cpoly end-1]
set cy0 [lindex $cpoly end]
foreach {cx1 cy1} $cpoly {
set source [coroutine clipper[incr clipindx] \
clipstep $source $cx0 $cy0 $cx1 $cy1]
set cx0 $cx1; set cy0 $cy1
}
set result {}
while {[llength [set pt [{*}$source]]] > 0} {
lappend result {*}$pt
}
return $result
} |
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).
| #JavaScript | JavaScript | // in A but not in B
function relative_complement(A, B) {
return A.filter(function(elem) {return B.indexOf(elem) == -1});
}
// in A or in B but not in both
function symmetric_difference(A,B) {
return relative_complement(A,B).concat(relative_complement(B,A));
}
var a = ["John", "Serena", "Bob", "Mary", "Serena"].unique();
var b = ["Jim", "Mary", "John", "Jim", "Bob"].unique();
print(a);
print(b);
print(symmetric_difference(a,b)); |
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.
| #Seed7 | Seed7 | $ include "seed7_05.s7i";
$ include "getf.s7i";
$ include "time.s7i";
const string: noteFileName is "NOTES.TXT";
const proc: main is func
local
var file: note is STD_NULL;
begin
if length(argv(PROGRAM)) = 0 then
# write NOTES.TXT
write(getf(noteFileName));
else
# Write date & time to NOTES.TXT, and then arguments
note := open(noteFileName, "a");
if note <> STD_NULL then
writeln(note, truncToSecond(time(NOW)));
writeln(note, "\t" <& join(argv(PROGRAM), " "));
close(note);
end if;
end if;
end func; |
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.
| #Sidef | Sidef | var file = %f'notes.txt'
if (ARGV.len > 0) {
var fh = file.open_a
fh.say(Time.local.ctime + "\n\t" + ARGV.join(" "))
fh.close
} else {
var fh = file.open_r
fh && fh.each { .say }
} |
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
| #Haskell | Haskell | import System.Exit (die)
import Control.Monad (mapM_)
main = do
putStrLn "Please enter temperature in kelvin: "
input <- getLine
let kelvin = read input
if kelvin < 0.0
then die "Temp cannot be negative"
else mapM_ putStrLn $ convert kelvin
convert :: Double -> [String]
convert n = zipWith (++) labels nums
where labels = ["kelvin: ", "celcius: ", "farenheit: ", "rankine: "]
conversions = [id, subtract 273, subtract 459.67 . (1.8 *), (*1.8)]
nums = (show . ($n)) <$> conversions |
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
| #SenseTalk | SenseTalk | put [
"partridge in a pear tree.",
"turtle doves and",
"french hens",
"calling birds",
"golden rings",
"geese a-laying",
"swans a-swimming",
"maids a-milking",
"ladies dancing",
"lords a-leaping",
"pipers piping",
"drummers drumming"
] into gifts
repeat with each item d1 of 1 .. 12
put "On the" && ordinalwords of d1 && "day of Christmas,"
put "My true love gave to me:"
repeat with each item d2 of d1 .. 1
if d2 is 1
put "A" into number
else
put capitalized(numberwords of d2) into number
end if
put number && item d2 of gifts
end repeat
put ""
end repeat |
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
| #Sidef | Sidef | var days = <first second third fourth fifth sixth seventh eighth ninth tenth eleventh twelfth>;
var gifts = <<'EOT'.lines;
And a partridge in a pear tree.
Two turtle doves,
Three french hens,
Four calling birds,
Five golden rings,
Six geese a-laying,
Seven swans a-swimming,
Eight maids a-milking,
Nine ladies dancing,
Ten lords a-leaping,
Eleven pipers piping,
Twelve drummers drumming,
EOT
func nth(n) { say "On the #{days[n]} day of Christmas, my true love gave to me:" };
nth(0);
say gifts[0].sub('And a', 'A');
range(1, 11).each { |d|
say '';
nth(d);
d.downto(0).each { |i|
say gifts[i];
}
} |
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.
| #zkl | zkl | fcn reader(fileName,out){
n:=0; foreach line in (File(fileName)) { out.write(line); n+=1; }
out.close(); // signal done
Atomic.waitFor(out.Property("isOpen")); // wait for other thread to reopen Pipe
out.write(n);
}
fcn writer(in){
Utils.zipWith(fcn(n,line){ "%3d: %s".fmt(n,line).print() },[1..],in);
in.open(); // signal other thread to send num lines read
println("Other thread read ",in.read()," lines");
}
p:=Thread.Pipe(); // NOT Unix pipes, thread safe channel between threads
reader.launch("input.txt",p);
writer.future(p).noop(); // noop forces eval, ie sleep until writer finished |
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)
| #Fantom | Fantom | fansh> DateTime.nowTicks
351823905158000000
fansh> DateTime.now
2011-02-24T00:51:47.066Z London
fansh> DateTime.now.toJava
1298508885979 |
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)
| #Forth | Forth | [UNDEFINED] MS@ [IF] \ Win32Forth (rolls over daily)
[DEFINED] ?MS [IF] ( -- ms )
: ms@ ?MS ; \ iForth
[ELSE] [DEFINED] cputime [IF] ( -- Dusec )
: ms@ cputime d+ 1000 um/mod nip ; \ gforth: Anton Ertl
[ELSE] [DEFINED] timer@ [IF] ( -- Dusec )
: ms@ timer@ >us 1000 um/mod nip ; \ bigForth
[ELSE] [DEFINED] gettimeofday [IF] ( -- usec sec )
: ms@ gettimeofday 1000 MOD 1000 * SWAP 1000 / + ; \ PFE
[ELSE] [DEFINED] counter [IF]
: ms@ counter ; \ SwiftForth
[ELSE] [DEFINED] GetTickCount [IF]
: ms@ GetTickCount ; \ VFX Forth
[ELSE] [DEFINED] MICROSECS [IF]
: ms@ microsecs 1000 UM/MOD nip ; \ MacForth
[THEN] [THEN] [THEN] [THEN] [THEN] [THEN] [THEN]
MS@ . \ print millisecond counter |
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.
| #Julia | Julia | const seen = Dict{Vector{Char}, Vector{Char}}()
function findnextterm(prevterm)
counts = Dict{Char, Int}()
reversed = Vector{Char}()
for c in prevterm
if !haskey(counts, c)
counts[c] = 0
end
counts[c] += 1
end
for c in sort(collect(keys(counts)))
if counts[c] > 0
push!(reversed, c)
if counts[c] == 10
push!(reversed, '0'); push!(reversed, '1')
else
push!(reversed, Char(UInt8(counts[c]) + UInt8('0')))
end
end
end
reverse(reversed)
end
function findsequence(seedterm)
term = seedterm
sequence = Vector{Vector{Char}}()
while !(term in sequence)
push!(sequence, term)
if !haskey(seen, term)
nextterm = findnextterm(term)
seen[term] = nextterm
end
term = seen[term]
end
return sequence
end
function selfseq(maxseed)
maxseqlen = -1
maxsequences = Vector{Pair{Int, Vector{Char}}}()
for i in 1:maxseed
seq = findsequence([s[1] for s in split(string(i), "")])
seqlen = length(seq)
if seqlen > maxseqlen
maxsequences = [Pair(i, seq)]
maxseqlen = seqlen
elseif seqlen == maxseqlen
push!(maxsequences, Pair(i, seq))
end
end
println("The longest sequence length is $maxseqlen.")
for p in maxsequences
println("\n Seed: $(p[1])")
for seq in p[2]
println(" ", join(seq, ""))
end
end
end
selfseq(1000000)
|
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.)
| #Wren | Wren | import "graphics" for Canvas, Color
import "dome" for Window
import "./polygon" for Polygon
class SutherlandHodgman {
construct new(width, height, subject, clipper) {
Window.title = "Sutherland-Hodgman"
Window.resize(width, height)
Canvas.resize(width, height)
_subject = subject
_result = subject.toList
_clipper = clipper
}
init() {
clipPolygon()
System.print("Clipped polygon points:")
for (p in _result) {
p[1] = (1000*p[1]).round/1000
System.print(p)
}
// display all 3 polygons
Polygon.quick(_subject).drawfill(Color.blue)
Polygon.quick(_clipper).drawfill(Color.red)
Polygon.quick(_result ).drawfill(Color.green)
}
clipPolygon() {
var len = _clipper.count
for (i in 0...len) {
var len2 = _result.count
var input = _result
_result = []
var a = _clipper[(i + len - 1) % len]
var b = _clipper[i]
for (j in 0...len2) {
var p = input[(j + len2 - 1) % len2]
var q = input[j]
if (isInside(a, b, q)) {
if (!isInside(a, b, p)) _result.add(intersection(a, b, p, q))
_result.add(q)
} else if (isInside(a, b, p)) _result.add(intersection(a, b, p, q))
}
}
}
isInside(a, b, c) { (a[0] - c[0]) * (b[1] - c[1]) > (a[1] - c[1]) * (b[0] - c[0]) }
intersection(a, b, p, q) {
var a1 = b[1] - a[1]
var b1 = a[0] - b[0]
var c1 = a1 * a[0] + b1 * a[1]
var a2 = q[1] - p[1]
var b2 = p[0] - q[0]
var c2 = a2 * p[0] + b2 * p[1]
var d = a1 * b2 - a2 * b1
var x = (b2 * c1 - b1 * c2) / d
var y = (a1 * c2 - a2 * c1) / d
return [x, y]
}
update() {}
draw(alpha) {}
}
var subject = [
[ 50, 150], [200, 50], [350, 150],
[350, 300], [250, 300], [200, 250],
[150, 350], [100, 250], [100, 200]
]
var clipper = [
[100, 100], [300, 100],
[300, 300], [100, 300]
]
var Game = SutherlandHodgman.new(600, 500, subject, clipper) |
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).
| #jq | jq | # The following implementation of intersection (but not symmetric_difference) assumes that the
# elements of a (and of b) are unique and do not include null:
def intersection(a; b):
reduce ((a + b) | sort)[] as $i
([null, []]; if .[0] == $i then [null, .[1] + [$i]] else [$i, .[1]] end)
| .[1] ;
def symmetric_difference(a;b):
(a|unique) as $a | (b|unique) as $b
| (($a + $b) | unique) - (intersection($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).
| #Julia | Julia | A = ["John", "Bob", "Mary", "Serena"]
B = ["Jim", "Mary", "John", "Bob"]
@show A B symdiff(A, B) |
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.
| #SNOBOL4 | SNOBOL4 | #! /usr/local/bin/snobol4 -b
a = 2 ;* skip '-b' parameter
notefile = "notes.txt"
while args = args host(2,a = a + 1) " " :s(while)
ident(args) :f(append)
noparms input(.notes,io_findunit(),,notefile) :s(display)f(end)
display output = notes :s(display)
endfile(notes) :(end)
append output(.notes,io_findunit(),"A",notefile) :f(end)
notes = date()
notes = char(9) args
end |
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.
| #Swift | Swift | import Foundation
let args = Process.arguments
let manager = NSFileManager()
let currentPath = manager.currentDirectoryPath
var err:NSError?
// Create file if it doesn't exist
if !manager.fileExistsAtPath(currentPath + "/notes.txt") {
println("notes.txt doesn't exist")
manager.createFileAtPath(currentPath + "/notes.txt", contents: nil, attributes: nil)
}
// handler is what is used to write to the file
let handler = NSFileHandle(forUpdatingAtPath: currentPath + "/notes.txt")
// Print the file if there are no args
if args.count == 1 {
let str = NSString(contentsOfFile: currentPath + "/notes.txt", encoding: NSUTF8StringEncoding, error: &err)
println(str!)
exit(0)
}
let time = NSDate()
let format = NSDateFormatter()
let timeData = (format.stringFromDate(time) + "\n").dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)
format.dateFormat = "yyyy.MM.dd 'at' HH:mm:ss zzz"
// We're writing to the end of the file
handler?.seekToEndOfFile()
handler?.writeData(timeData!)
var str = "\t"
for i in 1..<args.count {
str += args[i] + " "
}
str += "\n"
let strData = str.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)
handler?.writeData(strData!) |
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.
| #Tcl | Tcl | # Make it easier to change the name of the notes file
set notefile notes.txt
if {$argc} {
# Write a message to the file
set msg [clock format [clock seconds]]\n\t[join $argv " "]
set f [open $notefile a]
puts $f $msg
close $f
} else {
# Print the contents of the file
catch {
set f [open $notefile]
fcopy $f stdout
close $f
}
} |
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
| #Icon_and_Unicon | Icon and Unicon | procedure main(A)
k := A[1] | 21.00
write("K ",k)
write("C ",k-273.15)
write("R ",r := k*(9.0/5.0))
write("F ",r - 459.67)
end |
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
| #Simula | Simula | Begin
Text Array days(1:12), gifts(1:12);
Integer day, gift;
days(1) :- "first";
days(2) :- "second";
days(3) :- "third";
days(4) :- "fourth";
days(5) :- "fifth";
days(6) :- "sixth";
days(7) :- "seventh";
days(8) :- "eighth";
days(9) :- "ninth";
days(10) :- "tenth";
days(11) :- "eleventh";
days(12) :- "twelfth";
gifts(1) :- "A partridge in a pear tree.";
gifts(2) :- "Two turtle doves and";
gifts(3) :- "Three French hens,";
gifts(4) :- "Four calling birds,";
gifts(5) :- "Five gold rings,";
gifts(6) :- "Six geese a-laying,";
gifts(7) :- "Seven swans a-swimming,";
gifts(8) :- "Eight maids a-milking,";
gifts(9) :- "Nine ladies dancing,";
gifts(10) :- "Ten lords a-leaping,";
gifts(11) :- "Eleven pipers piping,";
gifts(12) :- "Twelve drummers drumming,";
For day := 1 Step 1 Until 12 Do Begin
outtext("On the "); outtext(days(day));
outtext(" day of Christmas, my true love sent to me:"); outimage;
For gift := day Step -1 Until 1 Do Begin
outtext(gifts(gift)); outimage
End;
outimage
End
End
|
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
| #Smalltalk | Smalltalk | Object subclass: TwelveDays [
Ordinals := #('first' 'second' 'third' 'fourth' 'fifth' 'sixth'
'seventh' 'eighth' 'ninth' 'tenth' 'eleventh' 'twelfth').
Gifts := #( 'A partridge in a pear tree.' 'Two turtle doves and'
'Three French hens,' 'Four calling birds,'
'Five gold 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,' ).
]
TwelveDays class extend [
giftsFor: day [
|newLine ordinal giftList|
newLine := $<10> asString.
ordinal := Ordinals at: day.
giftList := (Gifts first: day) reverse.
^'On the ', ordinal, ' day of Christmas, my true love sent to me:',
newLine, (giftList join: newLine), newLine.
]
]
1 to: 12 do: [:i |
Transcript show: (TwelveDays giftsFor: i); cr.
]. |
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)
| #Fortran | Fortran | integer :: start, stop, rate
real :: result
! optional 1st integer argument (COUNT) is current raw system clock counter value (not UNIX epoch millis!!)
! optional 2nd integer argument (COUNT_RATE) is clock cycles per second
! optional 3rd integer argument (COUNT_MAX) is maximum clock counter value
call system_clock( start, rate )
result = do_timed_work()
call system_clock( stop )
print *, "elapsed time: ", real(stop - start) / real(rate) |
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)
| #FreeBASIC | FreeBASIC | ' FB 1.05.0 Win64
Print Date + " " + Time '' returns system date/time in format : mm-dd-yyyy hh:mm:ss
Sleep |
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.
| #Kotlin | Kotlin | // version 1.1.2
const val LIMIT = 1_000_000
val sb = StringBuilder()
fun selfRefSeq(s: String): String {
sb.setLength(0) // faster than using a local StringBuilder object
for (d in '9' downTo '0') {
if (d !in s) continue
val count = s.count { it == d }
sb.append("$count$d")
}
return sb.toString()
}
fun permute(input: List<Char>): List<List<Char>> {
if (input.size == 1) return listOf(input)
val perms = mutableListOf<List<Char>>()
val toInsert = input[0]
for (perm in permute(input.drop(1))) {
for (i in 0..perm.size) {
val newPerm = perm.toMutableList()
newPerm.add(i, toInsert)
perms.add(newPerm)
}
}
return perms
}
fun main(args: Array<String>) {
val sieve = IntArray(LIMIT) // all zero by default
val elements = mutableListOf<String>()
for (n in 1 until LIMIT) {
if (sieve[n] > 0) continue
elements.clear()
var next = n.toString()
elements.add(next)
while (true) {
next = selfRefSeq(next)
if (next in elements) {
val size = elements.size
sieve[n] = size
if (n > 9) {
val perms = permute(n.toString().toList()).distinct()
for (perm in perms) {
if (perm[0] == '0') continue
val k = perm.joinToString("").toInt()
sieve[k] = size
}
}
break
}
elements.add(next)
}
}
val maxIterations = sieve.max()!!
for (n in 1 until LIMIT) {
if (sieve[n] < maxIterations) continue
println("$n -> Iterations = $maxIterations")
var next = n.toString()
for (i in 1..maxIterations) {
println(next)
next = selfRefSeq(next)
}
println()
}
} |
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.)
| #Yabasic | Yabasic |
open window 400, 400
backcolor 0,0,0
clear window
DPOL = 8
DREC = 3
CX = 1 : CY = 2
dim poligono(DPOL, 2)
dim rectang(DREC, 2)
dim clipped(DPOL + DREC, 2)
for n = 0 to DPOL : read poligono(n, CX), poligono(n, CY) : next n
DATA 50,150, 200,50, 350,150, 350,300, 250,300, 200,250, 150,350, 100,250, 100,200
for n = 0 to DREC : read rectang(n, CX), rectang(n, CY) : next n
DATA 100,100, 300,100, 300,300, 100,300
color 255,0,0
dibuja(poligono(), DPOL)
color 0,0,255
dibuja(rectang(), DREC)
nvert = FNsutherland_hodgman(poligono(), rectang(), clipped(), DPOL + DREC)
color 250,250,0
dibuja(clipped(), nvert - 1)
sub dibuja(figura(), i)
local n
print
new curve
for n = 0 to i
line to figura(n, CX), figura(n, CY)
print figura(n, CX), ", ", figura(n, CY)
next n
close curve
end sub
sub FNsutherland_hodgman(subj(), clip(), out(), n)
local i, j, o, tclip, p1(2), p2(2), s(2), e(2), p(2), inp(n, 2)
FOR o = 0 TO arraysize(subj(), 1) : out(o, CX) = subj(o, CX) : out(o, CY) = subj(o, CY) : NEXT o
tclip = arraysize(clip(),1)
p1(CX) = clip(tclip, CX) : p1(CY) = clip(tclip, CY)
FOR i = 0 TO tclip
p2(CX) = clip(i, CX) : p2(CY) = clip(i, CY)
FOR n = 0 TO o - 1 : inp(n, CX) = out(n, CX) : inp(n, CY) = out(n, CY) : NEXT n : o = 0
IF n >= 2 THEN
s(CX) = inp(n - 1, CX) : s(CY) = inp(n - 1, CY)
FOR j = 0 TO n - 1
e(CX) = inp(j, CX) : e(CY) = inp(j, CY)
IF FNside(e(), p1(), p2()) THEN
IF NOT FNside(s(), p1(), p2()) THEN
PROCintersection(p1(), p2(), s(), e(), p())
out(o, CX) = round(p(CX)) : out(o, CY) = round(p(CY))
o = o + 1
ENDIF
out(o, CX) = round(e(CX)) : out(o, CY) = round(e(CY))
o = o + 1
ELSE
IF FNside(s(), p1(), p2()) THEN
PROCintersection(p1(), p2(), s(), e(), p())
out(o, CX) = round(p(CX)) : out(o, CY) = round(p(CY))
o = o + 1
ENDIF
ENDIF
s(CX) = e(CX) : s(CY) = e(CY)
NEXT j
ENDIF
p1(CX) = p2(CX) : p1(CY) = p2(CY)
NEXT i
return o
end sub
sub FNside(p(), p1(), p2())
return (p2(CX) - p1(CX)) * (p(CY) - p1(CY)) > (p2(CY) - p1(CY)) * (p(CX) - p1(CX))
end sub
sub PROCintersection(p1(), p2(), p3(), p4(), p())
LOCAL a(2), b(2), k, l, m
a(CX) = p1(CX) - p2(CX) : a(CY) = p1(CY) - p2(CY)
b(CX) = p3(CX) - p4(CX) : b(CY) = p3(CY) - p4(CY)
k = p1(CX) * p2(CY) - p1(CY) * p2(CX)
l = p3(CX) * p4(CY) - p3(CY) * p4(CX)
m = 1 / (a(CX) * b(CY) - a(CY) * b(CX))
p(CX) = m * (k * b(CX) - l * a(CX))
p(CY) = m * (k * b(CY) - l * a(CY))
end sub
sub round(n)
return int(n + .5)
end sub |
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.)
| #zkl | zkl | class P{ // point
fcn init(_x,_y){ var [const] x=_x.toFloat(), y=_y.toFloat() }
fcn __opSub(p) { self(x - p.x, y - p.y) }
fcn cross(p) { x*p.y - y*p.x }
fcn toString { "(%7.2f,%7.2f)".fmt(x,y) }
var [const,proxy] ps=fcn{ T(x.toInt(),y.toInt()) }; // property
}
fcn shClipping(clip,polygon){
inputList,outputList,clipEdge:=List(), polygon.copy(), List(Void,clip[-1]);
foreach p in (clip){
clipEdge.del(0).append(p);
inputList.clear().extend(outputList);
outputList.clear();
S:=inputList[-1];
foreach E in (inputList){
if(leftOf(clipEdge,E)){
if(not leftOf(clipEdge,S))
outputList.append(intersection(S,E,clipEdge));
outputList.append(E);
}
else if(leftOf(clipEdge,S))
outputList.append(intersection(S,E,clipEdge));
S=E;
}
}
outputList
}
fcn leftOf(line,p){ //-->True (p is left of line), direction of line matters
p1,p2:=line; // line is (p1,p2)
(p2-p1).cross(p-p2)>0;
}
fcn intersection(p1,p2, line){ //-->Point of intersection or False
p3,p4:=line;
dx,dy,d:=p2-p1, p3-p4, p1-p3;
// x0 + a dx = y0 + b dy ->
// x0 X dx = y0 X dx + b dy X dx ->
// b = (x0 - y0) X dx / (dy X dx)
dyx:=dy.cross(dx);
if(not dyx) return(False); // parallel lines, could just throw on next line
dyx=d.cross(dx)/dyx;
P(p3.x + dyx*dy.x, p3.y + dyx*dy.y);
}
fcn drawPolygon(ppm,listOfPoints,rgb){
foreach n in (listOfPoints.len()-1){
ppm.line(listOfPoints[n].ps.xplode(),listOfPoints[n+1].ps.xplode(),rgb);
}
ppm.line(listOfPoints[0].ps.xplode(),listOfPoints[-1].ps.xplode(),rgb);
} |
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).
| #K | K | A: ?("John";"Bob";"Mary";"Serena")
B: ?("Jim";"Mary";"John";"Bob")
A _dvl B / in A but not in B
"Serena"
B _dvl A / in B but not in A
"Jim"
(A _dvl B;B _dvl A) / Symmetric difference
("Serena"
"Jim") |
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).
| #Kotlin | Kotlin | // version 1.1.2
fun main(args: Array<String>) {
val a = setOf("John", "Bob", "Mary", "Serena")
val b = setOf("Jim", "Mary", "John", "Bob")
println("A = $a")
println("B = $b")
val c = a - b
println("A \\ B = $c")
val d = b - a
println("B \\ A = $d")
val e = c.union(d)
println("A Δ B = $e")
} |
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.
| #uBasic.2F4tH | uBasic/4tH | If Cmd (0) > 1 Then ' if there are commandline arguments
If Set (a, Open ("notes.txt", "a")) < 0 Then
Print "Cannot write \qnotes.txt\q" ' open the file in "append" mode
End ' on error, issue message and exit
EndIf
' write the date and time
Write a, Show (FUNC(_DateStr (Time ())));" ";Show (FUNC(_TimeStr (Time ())))
Write a, "\t"; ' prepend with a tab
For i = 2 To Cmd (0) - 1 ' now write all commandline arguments
Write a, Show (Cmd (i)); " "; ' with the exception of the last one
Next
Write a, Show (Cmd (Cmd (0))) ' write the last argument
Else ' if no commandline arguments are given
If Set (a, Open ("notes.txt", "r")) < 0 Then
Print "Cannot read \qnotes.txt\q" ' open the file in "read" mode
End ' on error, issue message and exit
EndIf
Do While Read (a) ' read until EOF
Print Show (Tok (0)) ' show the entire line
Loop ' and repeat..
EndIf
Close a ' finally, close the file
End
_DateStr ' convert epoch to date string
Param (1)
Local (6)
a@ = a@ / 86400 ' just get the number of days since epoch
b@ = 1970+(a@/365) ' ball parking year, will not be accurate!
d@ = 0
For c@ = 1972 To b@ - 1 Step 4
If (((c@%4) = 0) * ((c@%100) # 0)) + ((c@%400) = 0) Then d@ = d@+1
Next
b@ = 1970+((a@ - d@)/365) ' calculating accurate current year by (x - extra leap days)
e@ = ((a@ - d@)%365)+1 ' if current year is leap, set indicator to 1
f@ = (((b@%4) = 0) * ((b@%100) # 0)) + ((b@%400) = 0)
g@ = 0 ' calculating current month
For c@ = 0 To 11 Until e@ < (g@+1)
g@ = g@ + FUNC(_Monthdays (c@, f@))
Next
' calculating current date
g@ = g@ - FUNC(_Monthdays (c@-1, f@))
' Print a@, d@, e@, f@
Return (Join (Str(b@), FUNC(_Format (c@, Dup("-"))), FUNC(_Format (e@ - g@, Dup("-")))))
_TimeStr ' convert epoch to time string
Param (1)
Return (Join(Str((a@%86400)/3600), FUNC(_Format ((a@%3600)/60, Dup(":"))), FUNC(_Format (a@%60, Dup(":")))))
_Format Param (2) : Return (Join (Iif (a@<10, Join(b@, "0"), b@), Str (a@)))
_Monthdays Param (2) : Return (((a@ + (a@<7)) % 2) + 30 - ((2 - b@) * (a@=1)))
|
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.
| #UNIX_Shell | UNIX Shell | #
NOTES=$HOME/notes.txt
if [[ $# -eq 0 ]] ; then
[[ -r $NOTES ]] && more $NOTES
else
date >> $NOTES
echo " $*" >> $NOTES
fi |
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
| #J | J | NB. Temp conversions are all linear polynomials
K2K =: 0 1 NB. K = (1 *k) + 0
K2C =: _273 1 NB. C = (1 *k) - 273
K2F =: _459.67 1.8 NB. F = (1.8*k) - 459.67
K2R =: 0 1.8 NB. R = (1.8*k) + 0
NB. Do all conversions at once (eval
NB. polynomials in parallel). This is the
NB. numeric matrix J programs would manipulate
NB. directly.
k2KCFR =: (K2K , K2C , K2F ,: K2R) p./ ] |
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
| #Smart_BASIC | Smart BASIC | ' by rbytes
dim d$(12),x$(15)!s=15
for t=0 to 11!read d$(t)!next t
for t=0 to 14!read x$(t)!next t
for u=0 to 11!s-=1
print x$(0)&d$(u)&x$(1)&chr$(10)&x$(2)
for t=s to 14!print x$(t)!next t
print!next u!data "first","second","third","fourth","fifth","sixth","seventh","eight","ninth","tenth","eleventh","Twelfth","On the "," 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/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
| #Snobol | Snobol | DAYS = ARRAY('12')
DAYS<1> = 'first'
DAYS<2> = 'second'
DAYS<3> = 'third'
DAYS<4> = 'fourth'
DAYS<5> = 'fifth'
DAYS<6> = 'sixth'
DAYS<7> = 'seventh'
DAYS<8> = 'eighth'
DAYS<9> = 'ninth'
DAYS<10> = 'tenth'
DAYS<11> = 'eleventh'
DAYS<12> = 'twelfth'
GIFTS = ARRAY('12')
GIFTS<1> = 'A partridge in a pear tree.'
GIFTS<2> = 'Two turtle doves and'
GIFTS<3> = 'Three French hens,'
GIFTS<4> = 'Four calling birds,'
GIFTS<5> = 'Five gold rings,'
GIFTS<6> = 'Six geese a-laying,'
GIFTS<7> = 'Seven swans a-swimming,'
GIFTS<8> = 'Eight maids a-milking,'
GIFTS<9> = 'Nine ladies dancing,'
GIFTS<10> = 'Ten lords a-leaping,'
GIFTS<11> = 'Eleven pipers piping,'
GIFTS<12> = 'Twelve drummers drumming,'
DAY = 1
OUTER LE(DAY,12) :F(END)
INTRO = 'On the NTH day of Christmas, my true love sent to me:'
INTRO 'NTH' = DAYS<DAY>
OUTPUT = INTRO
GIFT = DAY
INNER GE(GIFT,1) :F(NEXT)
OUTPUT = GIFTS<GIFT>
GIFT = GIFT - 1 :(INNER)
NEXT OUTPUT = ''
DAY = DAY + 1 :(OUTER)
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)
| #Frink | Frink | println[now[]] |
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)
| #FutureBasic | FutureBasic | window 1
print time
print time(@"hh:mm:ss" )
print time(@"h:mm a" )
print time(@"h:mm a zzz")
HandleEvents |
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.
| #Lua | Lua | -- Return the next term in the self-referential sequence
function findNext (nStr)
local nTab, outStr, pos, count = {}, "", 1, 1
for i = 1, #nStr do nTab[i] = nStr:sub(i, i) end
table.sort(nTab, function (a, b) return a > b end)
while pos <= #nTab do
if nTab[pos] == nTab[pos + 1] then
count = count + 1
else
outStr = outStr .. count .. nTab[pos]
count = 1
end
pos = pos + 1
end
return outStr
end
-- Return boolean indicating whether table t contains string s
function contains (t, s)
for k, v in pairs(t) do
if v == s then return true end
end
return false
end
-- Return the sequence generated by the given seed term
function buildSeq (term)
local sequence = {}
repeat
table.insert(sequence, term)
if not nextTerm[term] then nextTerm[term] = findNext(term) end
term = nextTerm[term]
until contains(sequence, term)
return sequence
end
-- Main procedure
nextTerm = {}
local highest, seq, hiSeq = 0
for i = 1, 10^6 do
seq = buildSeq(tostring(i))
if #seq > highest then
highest = #seq
hiSeq = {seq}
elseif #seq == highest then
table.insert(hiSeq, seq)
end
end
io.write("Seed values: ")
for _, v in pairs(hiSeq) do io.write(v[1] .. " ") end
print("\n\nIterations: " .. highest)
print("\nSample sequence:")
for _, v in pairs(hiSeq[1]) do print(v) end |
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).
| #Ksh | Ksh |
#!/bin/ksh
# Symmetric difference - enumerate the items that are in A or B but not both.
# # Variables:
#
typeset -a A=( John Bob Mary Serena )
typeset -a B=( Jim Mary John Bob )
# # Functions:
#
# # Function _flattenarr(arr, sep) - flatten arr into string by separator sep
#
function _flattenarr {
typeset _arr ; nameref _arr="$1"
typeset _sep ; typeset -L1 _sep="$2"
typeset _buff
typeset _oldIFS=$IFS ; IFS="${_sep}"
_buff=${_arr[*]}
IFS="${_oldIFS}"
echo "${_buff}"
}
# # Function _notin(_arr1, _arr2) - elements in arr1 and not in arr2
#
function _notin {
typeset _ar1 ; nameref _ar1="$1"
typeset _ar2 ; nameref _ar2="$2"
typeset _i _buff _set ; integer _i
_buff=$(_flattenarr _ar2 \|)
for((_i=0; _i<${#_ar1[*]}; _i++)); do
[[ ${_ar1[_i]} != @(${_buff}) ]] && _set+="${_ar1[_i]} "
done
echo ${_set% *}
}
######
# main #
######
AnB=$(_notin A B) ; echo "A - B = ${AnB}"
BnA=$(_notin B A) ; echo "B - A = ${BnA}"
echo "A xor B = ${AnB} ${BnA}" |
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).
| #Lasso | Lasso |
[
var(
'a' = array(
'John'
,'Bob'
,'Mary'
,'Serena'
)
,'b' = array
);
$b->insert( 'Jim' ); // Alternate method of populating array
$b->insert( 'Mary' );
$b->insert( 'John' );
$b->insert( 'Bob' );
$a->sort( true ); // arrays must be sorted (true = ascending) for difference to work
$b->sort( true );
$a->difference( $b )->union( $b->difference( $a ) );
]
|
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.
| #Visual_Basic_.NET | Visual Basic .NET | Imports System.IO
Module Notes
Function Main(ByVal cmdArgs() As String) As Integer
Try
If cmdArgs.Length = 0 Then
Using sr As New StreamReader("NOTES.TXT")
Console.WriteLine(sr.ReadToEnd)
End Using
Else
Using sw As New StreamWriter("NOTES.TXT", True)
sw.WriteLine(Date.Now.ToString())
sw.WriteLine("{0}{1}", ControlChars.Tab, String.Join(" ", cmdArgs))
End Using
End If
Catch
End Try
End Function
End Module |
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.
| #Wren | Wren | import "os" for Process
import "/ioutil" for File, FileUtil
import "/date" for Date
var dateFormatIn = "yyyy|-|mm|-|dd|+|hh|:|MM"
var dateFormatOut = "yyyy|-|mm|-|dd| |hh|:|MM"
var args = Process.arguments
if (args.count == 0) {
if (File.exists("NOTES.TXT")) System.print(File.read("NOTES.TXT"))
} else if (args.count == 1) {
System.print("Enter the current date/time (MM/DD+HH:mm) plus at least one other argument.")
} else {
var dateTime = Date.parse(args[0], dateFormatIn)
var note = "\t" + args[1..-1].join(" ") + "\n"
FileUtil.append("NOTES.TXT", dateTime.format(dateFormatOut) + "\n" + note)
} |
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
| #Java | Java | public class TemperatureConversion {
public static void main(String args[]) {
if (args.length == 1) {
try {
double kelvin = Double.parseDouble(args[0]);
if (kelvin >= 0) {
System.out.printf("K %2.2f\n", kelvin);
System.out.printf("C %2.2f\n", kelvinToCelsius(kelvin));
System.out.printf("F %2.2f\n", kelvinToFahrenheit(kelvin));
System.out.printf("R %2.2f\n", kelvinToRankine(kelvin));
} else {
System.out.printf("%2.2f K is below absolute zero", kelvin);
}
} catch (NumberFormatException e) {
System.out.println(e);
}
}
}
public static double kelvinToCelsius(double k) {
return k - 273.15;
}
public static double kelvinToFahrenheit(double k) {
return k * 1.8 - 459.67;
}
public static double kelvinToRankine(double k) {
return k * 1.8;
}
} |
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
| #SQL | SQL |
WITH
FUNCTION nl ( s IN varchar2 )
RETURN varchar2
IS
BEGIN
RETURN chr(10) || s;
END nl;
FUNCTION v ( d NUMBER, x NUMBER, g IN varchar2 )
RETURN varchar2
IS
BEGIN
RETURN
CASE WHEN d >= x THEN nl (g) END;
END v;
SELECT 'On the '
|| to_char(to_date(level,'j'),'jspth' )
|| ' day of Christmas,'
|| nl( 'my true love sent to me:')
|| v ( level, 12, 'Twelve drummers drumming,' )
|| v ( level, 11, 'Eleven pipers piping,' )
|| v ( level, 10, 'Ten lords a-leaping,' )
|| v ( level, 9, 'Nine ladies dancing,' )
|| v ( level, 8, 'Eight maids a-milking,' )
|| v ( level, 7, 'Seven swans a-swimming,' )
|| v ( level, 6, 'Six geese a-laying,' )
|| v ( level, 5, 'Five golden rings!' )
|| v ( level, 4, 'Four calling birds,' )
|| v ( level, 3, 'Three French hens,' )
|| v ( level, 2, 'Two turtle doves,' )
|| v ( level, 1, CASE level WHEN 1 THEN 'A' ELSE 'And a' END || ' partridge in a pear tree.' )
|| nl(NULL)
"The Twelve Days of Christmas"
FROM dual
CONNECT BY level <= 12
/
|
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)
| #Gambas | Gambas | Public Sub Main()
Print Format(Now, "dddd dd mmmm yyyy hh:nn:ss")
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)
| #Genie | Genie | [indent=4]
init
var now = new DateTime.now_local()
print now.to_string() |
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.
| #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | selfRefSequence[ x_ ] := FromDigits@Flatten@Reverse@Cases[Transpose@{RotateRight[DigitCount@x,1], Range[0,9]},Except[{0,_}]]
DisplaySequence[ x_ ] := NestWhileList[selfRefSequence,x,UnsameQ[##]&,4]
data= {#, Length@DisplaySequence[#]}&/@Range[1000000];
Print["Values: ", Select[data ,#[[2]] == Max@data[[;;,2]]&][[1,;;]]]
Print["Iterations: ", Length@DisplaySequence[#]&/@Select[data ,#[[2]] == Max@data[[;;,2]]&][[1,;;]]]
DisplaySequence@Select[data, #[[2]] == Max@data[[;;,2]]&][[1]]//Column |
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).
| #Logo | Logo | to diff :a :b [:acc []]
if empty? :a [output sentence :acc :b]
ifelse member? first :a :b ~
[output (diff butfirst :a remove first :a :b :acc)] ~
[output (diff butfirst :a :b lput first :a :acc)]
end
make "a [John Bob Mary Serena]
make "b [Jim Mary John Bob]
show diff :a :b ; [Serena Jim] |
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).
| #Lua | Lua | A = { ["John"] = true, ["Bob"] = true, ["Mary"] = true, ["Serena"] = true }
B = { ["Jim"] = true, ["Mary"] = true, ["John"] = true, ["Bob"] = true }
A_B = {}
for a in pairs(A) do
if not B[a] then A_B[a] = true end
end
B_A = {}
for b in pairs(B) do
if not A[b] then B_A[b] = true end
end
for a_b in pairs(A_B) do
print( a_b )
end
for b_a in pairs(B_A) do
print( b_a )
end |
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.
| #XPL0 | XPL0 | include xpllib; \Date and Time routines
int I, NotesSize, Ch, CmdArgSize;
char Notes(1_000_000), CmdArg(1000);
[\Read in notes.txt, if it exists
Trap(false); \disable abort on errors
FSet(FOpen("notes.txt", 0), ^i);
OpenI(3);
if GetErr = 0 then \file exists
[I:= 0;
while GetErr = 0 do \GetErr detects end-of-file
[Notes(I):= ChIn(3);
I:= I+1;
];
NotesSize:= I-2; \remove 2 EOFs
];
\Get command-line argument, if any, from command line
I:= 0;
loop [Ch:= ChIn(8);
if Ch = CR then quit;
CmdArg(I):= Ch;
I:= I+1;
];
CmdArg(I):= 0; \terminate string
if I = 0 then \no args, just display notes.txt
for I:= 0 to NotesSize-1 do ChOut(0, Notes(I))
else \open notes.txt for output and append CmdArg
[FSet(FOpen("notes.txt", 1), ^o);
OpenO(3);
for I:= 0 to NotesSize-1 do ChOut(3, Notes(I));
DateOut(3, GetDosDate); ChOut(3, ^ );
TimeOut(3, GetDosTime); CrLf(3);
ChOut(3, Tab); Text(3, CmdArg); CrLf(3);
Close(3);
];
] |
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.
| #zkl | zkl | const notesName="NOTES.TXT";
args:=vm.arglist;
if (not args)
{ try{ File(notesName).read(*).text.print(); } catch{println("no file")} }
else{
f:=File(notesName,"a+");
f.writeln(Time.Date.ctime(),"\n\t",args.concat(" "));
f.close();
} |
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
| #JavaScript | JavaScript | var k2c = k => k - 273.15
var k2r = k => k * 1.8
var k2f = k => k2r(k) - 459.67
Number.prototype.toMaxDecimal = function (d) {
return +this.toFixed(d) + ''
}
function kCnv(k) {
document.write( k,'K° = ', k2c(k).toMaxDecimal(2),'C° = ', k2r(k).toMaxDecimal(2),'R° = ', k2f(k).toMaxDecimal(2),'F°<br>' )
}
kCnv(21)
kCnv(295) |
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
| #Swift | Swift | let gifts = [ "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-milking",
"Nine ladies dancing", "Ten lords a-leaping",
"Eleven pipers piping", "Twelve drummers drumming" ]
let nth = [ "first", "second", "third", "fourth", "fifth", "sixth",
"seventh", "eighth", "ninth", "tenth", "eleventh", "twelfth" ]
func giftsForDay(day: Int) -> String {
var result = "On the \(nth[day-1]) day of Christmas, my true love sent to me:\n"
if day > 1 {
for again in 1...day-1 {
let n = day - again
result += gifts[n]
if n > 1 { result += "," }
result += "\n"
}
result += "And a "
} else {
result += "A "
}
return result + gifts[0] + ".\n";
}
for day in 1...12 {
print(giftsForDay(day))
} |
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
| #Tailspin | Tailspin |
def ordinal: ['first', 'second', 'third', 'fourth', 'fifth', 'sixth', 'seventh', 'eighth', 'ninth', 'tenth', 'eleventh', 'twelfth'];
def gift: [
'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'
];
templates punctuation
<=1> '.' !
<=2> ' and' !
<=5> ';' !
<> ',' !
end punctuation
1..12 -> \singVerse(
'On the $ordinal($); day of Christmas,
my true love gave to me:
' !
$..1:-1 -> '$gift($);$->punctuation;
' !
'
' !
\singVerse) -> !OUT::write
|
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)
| #Go | Go | package main
import "time"
import "fmt"
func main() {
t := time.Now()
fmt.Println(t) // default format
fmt.Println(t.Format("Mon Jan 2 15:04:05 2006")) // some custom format
} |
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)
| #Groovy | Groovy | def nowMillis = new Date().time
println 'Milliseconds since the start of the UNIX Epoch (Jan 1, 1970) == ' + nowMillis |
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.
| #Nim | Nim | import algorithm, sequtils, sets, strutils, tables
var cache: Table[seq[char], int] # Maps key -> number of iterations.
iterator sequence(seed: string): string =
## Yield the successive strings of a sequence.
var history: HashSet[string]
history.incl seed
var current = seed
yield current
while true:
var counts = current.toCountTable()
var next: string
for ch in sorted(toSeq(counts.keys), Descending):
next.add $counts[ch] & ch
if next in history: break
current = move(next)
history.incl current
yield current
proc seqLength(seed: string): int =
## Return the number of iterations for the given seed.
let key = sorted(seed, Descending)
if key in cache: return cache[key]
result = toSeq(sequence(seed)).len
cache[key] = result
var seeds: seq[int]
var itermax = 0
for seed in 0..<1_000_000:
let itercount = seqLength($seed)
if itercount > itermax:
itermax = itercount
seeds = @[seed]
elif itercount == itermax:
seeds.add seed
echo "Maximum iterations: ", itermax
echo "Seed values: ", seeds.join(", ")
echo "Sequence for $#:".format(seeds[0])
for s in sequence($seeds[0]): echo s |
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).
| #Maple | Maple | A := {John, Bob, Mary, Serena};
B := {Jim, Mary, John, Bob}; |
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).
| #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | SymmetricDifference[x_List,y_List] := Join[Complement[x,Intersection[x,y]],Complement[y,Intersection[x,y]]] |
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
| #jq | jq |
# round(keep) takes as input any jq (i.e. JSON) number and emits a string.
# "keep" is the desired maximum number of numerals after the decimal point,
# e.g. 9.999|round(2) => 10.00
def round(keep):
tostring
| (index("e") | if . then . else index("E") end) as $e
| if $e then (.[0:$e] | round(keep)) + .[$e+1:]
else index(".") as $ix
| if $ix == null then .
else .[0:$ix + 1] as $head
| .[$ix+1:$ix+keep+2] as $tail
| if ($tail|length) <= keep then $head + $tail
else ($tail | .[length-1:] | tonumber) as $last
| if $last < 5 then $head + $tail[0:$tail|length - 1]
else (($head + $tail) | length) as $length
| ($head[0:-1] + $tail)
| (tonumber + (if $head[0:1]=="-" then -5 else 5 end))
| tostring
| .[0: ($ix+1+length-$length)] + "." + .[length-keep-1:-1]
end
end
end
end;
def k2c: . - 273.15;
def k2f: . * 1.8 - 459.67;
def k2r: . * 1.8;
# produce a stream
def cfr:
if . >= 0
then "Kelvin: \(.)", "Celsius: \(k2c|round(2))",
"Fahrenheit: \(k2f|round(2))", "Rankine: \(k2r|round(2))"
else error("cfr: \(.) is an invalid temperature in degrees Kelvin")
end;
cfr |
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
| #Terraform | Terraform | locals {
days = [ "first", "second", "third", "fourth", "fifth", "sixth",
"seventh", "eighth", "ninth", "tenth", "eleventh", "twelfth" ]
gifts = [
"A partridge in a pear tree.",
"Two turtle doves, and",
"Three French hens,",
"Four calling birds,",
"Five gold 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,"
]
}
data "template_file" "days" {
count = 12
template = "On the ${local.days[count.index]} day of Christmas, my true love sent to me:\n${join("\n",[for g in range(count.index,-1,-1): local.gifts[g]])}"
}
output "lyrics" {
value = join("\n\n",[for t in data.template_file.days: t.rendered])
} |
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
| #Tcl | Tcl | set days {
first second third fourth fifth sixth
seventh eighth ninth tenth eleventh twelfth
}
set gifts [lreverse {
"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,"
}]
set n -1;puts [join [lmap day $days {
format "On the $day day of Christmas,\nMy true love gave to me:\n%s" \
[join [lrange $gifts end-[incr n] end] \n]
}] \n\n] |
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)
| #GUISS | GUISS | Taskbar |
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)
| #Haskell | Haskell | import System.Time
(getClockTime, toCalendarTime, formatCalendarTime)
import System.Locale (defaultTimeLocale)
main :: IO ()
main = do
ct <- getClockTime
print ct -- print default format, or
cal <- toCalendarTime ct
putStrLn $ formatCalendarTime defaultTimeLocale "%a %b %e %H:%M:%S %Y" cal |
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.
| #Perl | Perl | sub next_num {
my @a;
$a[$_]++ for split '', shift;
join('', map(exists $a[$_] ? $a[$_].$_ : "", reverse 0 .. 9));
}
my %cache;
sub seq {
my $a = shift;
my (%seen, @s);
until ($seen{$a}) {
$seen{$a} = 1;
push(@s, $a);
last if !wantarray && $cache{$a};
$a = next_num($a);
}
return (@s) if wantarray;
my $l = $cache{$a};
if ($l) { $cache{$s[$_]} = $#s - $_ + $l for (0 .. $#s); }
else {
$l++ while ($s[-$l] != $a);
$cache{pop @s} = $l for (1 .. $l);
$cache{pop @s} = ++$l while @s;
}
$cache{$s[0]}
}
my (@mlist, $mlen);
for (1 .. 100_000) { # 1_000_000 takes very, very long
my $l = seq($_);
next if $l < $mlen;
if ($l > $mlen) { $mlen = $l; @mlist = (); }
push @mlist, $_;
}
print "longest ($mlen): @mlist\n";
print join("\n", seq($_)), "\n\n" for @mlist; |
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).
| #MATLAB | MATLAB | >> [setdiff([1 2 3],[2 3 4]) setdiff([2 3 4],[1 2 3])]
ans =
1 4 |
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
| #Julia | Julia | cfr(k) = print("Kelvin: $k, ",
"Celsius: $(round(k-273.15,2)), ",
"Fahrenheit: $(round(k*1.8-459.67,2)), ",
"Rankine: $(round(k*1.8,2))") |
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
| #Kotlin | Kotlin | // version 1.1.2
class Kelvin(val degrees: Double) {
fun toCelsius() = degrees - 273.15
fun toFahreneit() = (degrees - 273.15) * 1.8 + 32.0
fun toRankine() = (degrees - 273.15) * 1.8 + 32.0 + 459.67
}
fun main(args: Array<String>) {
print("Enter the temperature in degrees Kelvin : ")
val degrees = readLine()!!.toDouble()
val k = Kelvin(degrees)
val f = "% 1.2f"
println()
println("K ${f.format(k.degrees)}\n")
println("C ${f.format(k.toCelsius())}\n")
println("F ${f.format(k.toFahreneit())}\n")
println("R ${f.format(k.toRankine())}")
} |
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
| #True_BASIC | True BASIC | DATA "first","second","third","fourth","fifth","sixth"
DATA "seventh","eighth","ninth","tenth","eleventh","twelfth"
DATA "A partridge in a pear tree."
DATA "Two turtle doves and"
DATA "Three french hens"
DATA "Four calling birds"
DATA "Five golden rings"
DATA "Six geese a-laying"
DATA "Seven swans a-swimming"
DATA "Eight maids a-milking"
DATA "Nine ladies dancing"
DATA "Ten lords a-leaping"
DATA "Eleven pipers piping"
DATA "Twelve drummers drumming"
DIM day$(12), gift$(12)
FOR i = 1 TO 12
READ day$(i)
NEXT i
FOR i = 1 TO 12
READ gift$(i)
NEXT i
FOR i = 1 TO 12
PRINT "On the "; day$(i); " day of Christmas,"
PRINT "My true love gave TO me:"
FOR j = i TO 1 STEP -1
PRINT gift$(j)
NEXT j
PRINT
NEXT i
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)
| #HicEst | HicEst | seconds_since_midnight = TIME() ! msec as fraction
seconds_since_midnight = TIME(Year=yr, Day=day, WeekDay=wday, Gregorian=gday)
! other options e.g. Excel, YYYYMMDD (num or text) |
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)
| #HolyC | HolyC | CDateStruct ds;
Date2Struct(&ds, Now + local_time_offset);
Print("%04d-%02d-%02d %02d:%02d:%02d\n", ds.year, ds.mon, ds.day_of_mon, ds.hour, ds.min, ds.sec);
|
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.
| #Phix | Phix | with javascript_semantics
string n = "000000"
function incn()
for i=length(n) to 1 by -1 do
if n[i]='9' then
if i=1 then return false end if
n[i]='0'
else
n[i] += 1
exit
end if
end for
return true
end function
sequence res = {}, bestseen
integer maxcycle = 0
procedure srs()
sequence curr = n
while length(curr)>1 and curr[1]='0' do
curr = curr[2..$]
end while
integer ch = curr[1]
for i=2 to length(curr) do
if curr[i]>ch then return end if
ch = curr[i]
end for
sequence seen = {curr}
integer cycle = 1
while true do
sequence digits = repeat(0,10)
for i=1 to length(curr) do
integer idx = curr[i]-'0'+1
digits[idx] += 1
end for
string next = ""
for i=length(digits) to 1 by -1 do
if digits[i]!=0 then
next &= sprint(digits[i])
next &= i+'0'-1
end if
end for
if find(next,seen) then exit end if
seen = append(seen,next)
curr = next
cycle += 1
end while
if cycle>maxcycle then
res = {seen[1]}
maxcycle = cycle
bestseen = seen
elsif cycle=maxcycle then
res = append(res,seen[1])
end if
end procedure
while true do
srs()
if not incn() then exit end if
end while
-- add non-leading-0 perms:
for i=length(res) to 1 by -1 do
string ri = res[i]
for p=1 to factorial(length(ri)) do
string pri = permute(p,ri)
if pri[1]!='0' and not find(pri,res) then
res = append(res,pri)
end if
end for
end for
?res
puts(1,"cycle length is ") ?maxcycle
pp(bestseen,{pp_Nest,1})
|
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).
| #Maxima | Maxima | /* builtin */
symmdifference({"John", "Bob", "Mary", "Serena"},
{"Jim", "Mary", "John", "Bob"});
{"Jim", "Serena"} |
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).
| #Mercury | Mercury | :- module symdiff.
:- interface.
:- import_module io.
:- pred main(io::di, io::uo) is det.
:- implementation.
:- import_module list, set, string.
main(!IO) :-
A = set(["John", "Bob", "Mary", "Serena"]),
B = set(["Jim", "Mary", "John", "Bob"]),
print_set("A\\B", DiffAB @ (A `difference` B), !IO),
print_set("B\\A", DiffBA @ (B `difference` A), !IO),
print_set("A symdiff B", DiffAB `union` DiffBA, !IO).
:- pred print_set(string::in, set(T)::in, io::di, io::uo) is det.
print_set(Desc, Set, !IO) :-
to_sorted_list(Set, Elems),
io.format("%11s: %s\n", [s(Desc), s(string(Elems))], !IO). |
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
| #Lambdatalk | Lambdatalk |
{def to-celsius {lambda {:k} {- :k 273.15}}}
-> to-celsius
{def to-farenheit {lambda {:k} {- {* :k 1.8} 459.67}}}
-> to-farenheit
{def to-rankine {lambda {:k} {* :k 1.8}}}
-> to-rankine
{def format {lambda {:n} {/ {round {* :n 100}} 100}}}
-> format
{def kelvinConversion
{lambda {:k}
kelvin is equivalent to:{br}
{format {to-celsius :k}} celsius{br}
{format {to-farenheit :k}} farenheit{br}
{format {to-rankine :k}} rankine}}
-> kelvinConversion
{kelvinConversion 21}
->
kelvin is equivalent to:
-252.15 celsius
-421.87 farenheit
37.8 rankine
|
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
| #uBasic.2F4tH | uBasic/4tH | Dim @n(12) : Dim @v(12) ' define both arrays
Proc _DataDays ' put data on the stack
For i=11 To 0 Step -1 ' read them in
@n(i) = Pop()
Next
Proc _DataGifts ' put data on the stack
For i=11 To 0 Step -1 ' read them in
@v(i) = Pop()
Next
For i=0 To 11 ' print all twelve verses
Print "On the ";Show(@n(i));" day of Christmas"
Print "My true love gave to me:"
For j=i To 0 Step -1 ' show list of gifts
Print Show(@v(j))
Next
Print ' next verse
Next
End
_DataDays
Push Dup("first"), Dup("second"), Dup("third"), Dup ("fourth")
Push Dup("fifth"), Dup("sixth"), Dup("seventh"), Dup("eighth")
Push Dup("ninth"), Dup("tenth"), Dup("eleventh"), Dup("twelfth")
Return
_DataGifts
Push Dup("A partridge in a pear tree.")
Push Dup("Two turtle doves and")
Push Dup("Three french hens")
Push Dup("Four calling birds")
Push Dup("Five golden rings")
Push Dup("Six geese a-laying")
Push Dup("Seven swans a-swimming")
Push Dup("Eight maids a-milking")
Push Dup("Nine ladies dancing")
Push Dup("Ten lords a-leaping")
Push Dup("Eleven pipers piping")
Push Dup("Twelve drummers drumming")
Return |
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
| #UNIX_Shell | UNIX Shell | #!/usr/bin/env bash
ordinals=(first second third fourth fifth sixth
seventh eighth ninth tenth eleventh twelfth)
gifts=( "A partridge in a pear tree." "Two turtle doves and"
"Three French hens," "Four calling birds,"
"Five gold 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," )
echo_gifts() {
local i day=$1
echo "On the ${ordinals[day]} day of Christmas, my true love sent to me:"
for (( i=day; i >=0; --i )); do
echo "${gifts[i]}"
done
echo
}
for (( day=0; day < 12; ++day )); do
echo_gifts $day
done |
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)
| #Hoon | Hoon | now |
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)
| #Icon_and_Unicon | Icon and Unicon | procedure main()
write("&time - milliseconds of CPU time = ",&time)
write("&clock - Time of day as hh:mm:ss (24-hour format) = ",&clock)
write("&date - current date in yyyy/mm/dd format = ",&date)
write("&dateline - timestamp with day of the week, date, and current time to the minute = ",&dateline)
if find("Unicon",&version) then
write("&now - time in seconds since the epoch = ", &now) # Unicon only
end |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.