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/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.
| #PicoLisp | PicoLisp | (de selfRefSequence (Seed)
(let L (mapcar format (chop Seed))
(make
(for (Cache NIL (not (idx 'Cache L T)))
(setq L
(las (flip (sort (copy (link L))))) ) ) ) ) )
(let Res NIL
(for Seed 1000000
(let N (length (selfRefSequence Seed))
(cond
((> N (car Res)) (setq Res (list N Seed)))
((= N (car Res)) (queue 'Res Seed)) ) ) )
(println 'Values: (cdr Res))
(println 'Iterations: (car Res))
(mapc prinl (selfRefSequence (cadr Res))) ) |
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).
| #Nim | Nim | import sets
var setA = ["John", "Bob", "Mary", "Serena"].toHashSet
var setB = ["Jim", "Mary", "John", "Bob"].toHashSet
echo setA -+- setB # Symmetric difference
echo setA - setB # Difference
echo setB - setA # Difference |
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).
| #Objective-C | Objective-C | #import <Foundation/Foundation.h>
int main(int argc, const char *argv[]) {
@autoreleasepool {
NSSet* setA = [NSSet setWithObjects:@"John", @"Serena", @"Bob", @"Mary", @"Serena", nil];
NSSet* setB = [NSSet setWithObjects:@"Jim", @"Mary", @"John", @"Jim", @"Bob", nil];
// Present our initial data set
NSLog(@"In set A: %@", setA);
NSLog(@"In set B: %@", setB);
// Get our individual differences.
NSMutableSet* notInSetA = [NSMutableSet setWithSet:setB];
[notInSetA minusSet:setA];
NSMutableSet* notInSetB = [NSMutableSet setWithSet:setA];
[notInSetB minusSet:setB];
// The symmetric difference is the concatenation of the two individual differences
NSMutableSet* symmetricDifference = [NSMutableSet setWithSet:notInSetA];
[symmetricDifference unionSet:notInSetB];
// Present our results
NSLog(@"Not in set A: %@", notInSetA);
NSLog(@"Not in set B: %@", notInSetB);
NSLog(@"Symmetric Difference: %@", symmetricDifference);
}
return 0;
} |
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
| #Lasso | Lasso | define tempconverter(temp, kind) => {
local(
_temp = decimal(#temp),
convertratio = 1.8,
k_c = 273.15,
r_f = 459.67,
k,c,r,f
)
match(#kind) => {
case('k')
#k = #_temp
#c = -#k_c + #k
#r = #k * #convertratio
#f = -#r_f + #r
case('c')
#c = #_temp
#k = #k_c + #c
#r = #k * #convertratio
#f = -#r_f + #r
case('r')
#r = #_temp
#f = -#r_f + #r
#k = #r / #convertratio
#c = -#k_c + #k
case('f')
#f = #_temp
#r = #r_f + #f
#k = #r / #convertratio
#c = -#k_c + #k
case
return 'Something wrong'
}
return ('K = ' + #k -> asstring(-precision = 2) +
' C = ' + #c -> asstring(-precision = 2) +
' R = ' + #r -> asstring(-precision = 2) +
' F = ' + #f -> asstring(-precision = 2)
)
}
tempconverter(21, 'k')
'<br />'
tempconverter(21, 'c')
'<br />'
tempconverter(-41, 'c')
'<br />'
tempconverter(37.80, 'r')
'<br />'
tempconverter(69.80, '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
| #LIL | LIL | # Temperature conversion, in LIL
func kToc k {expr $k - 273.15}
func kTor k {expr $k / 5.0 * 9.0}
func kTof k {expr [kTor $k] - 469.67}
write "Enter kelvin temperatures or just enter to quit: "
for {set k [readline]} {![streq $k {}]} {set k [readline]} {
print "Kelvin: $k"
print "Celsius: [kToc $k]"
print "Fahrenheit: [kTof $k]"
print "Rankine: [kTor $k]"
} |
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
| #VBA | VBA | Sub Main()
Dim i As Integer, c As Integer, j As Integer, strReturn() As String
Dim s, n
s = Split(SING_, "$")
n = Split(NUMBERS_, " ")
ReDim strReturn(UBound(s))
For i = LBound(s) To UBound(s)
strReturn(i) = Replace(BASE_, "(X)", n(i))
For j = c To 0 Step -1
strReturn(i) = strReturn(i) & s(j) & vbCrLf
Next
c = c + 1
Next i
strReturn(UBound(strReturn)) = Replace(strReturn(UBound(strReturn)), "and" & vbCrLf & "A", vbCrLf & "And a")
Debug.Print Join(strReturn, vbCrLf)
End Sub |
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
| #VBScript | VBScript | days = Array("first","second","third","fourth","fifth","sixth",_
"seventh","eight","ninth","tenth","eleventh","twelfth")
gifts = Array("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")
For i = 0 To 11
WScript.StdOut.Write "On the " & days(i) & " day of Christmas"
WScript.StdOut.WriteLine
WScript.StdOut.Write "My true love sent to me:"
WScript.StdOut.WriteLine
If i = 0 Then
WScript.StdOut.Write gifts(i)
Else
For j = i To 0 Step - 1
If j = 0 Then
WScript.StdOut.Write "and " & gifts(0)
Else
WScript.StdOut.Write gifts(j)
WScript.StdOut.WriteLine
End If
Next
End If
WScript.StdOut.WriteBlankLines(2)
Next |
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)
| #IDL | IDL | print,systime(0)
Wed Feb 10 09:41:14 2010
print,systime(1)
1.2658237e+009
|
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)
| #Io | Io | Date now println |
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.
| #Python | Python | from itertools import groupby, permutations
def A036058(number):
return ''.join( str(len(list(g))) + k
for k,g in groupby(sorted(str(number), reverse=True)) )
def A036058_length(numberstring='0', printit=False):
iterations, last_three, queue_index = 1, ([None] * 3), 0
def A036058(number):
# rely on external reverse-sort of digits of number
return ''.join( str(len(list(g))) + k
for k,g in groupby(number) )
while True:
if printit:
print(" %2i %s" % (iterations, numberstring))
numberstring = ''.join(sorted(numberstring, reverse=True))
if numberstring in last_three:
break
assert iterations < 1000000
last_three[queue_index], numberstring = numberstring, A036058(numberstring)
iterations += 1
queue_index +=1
queue_index %=3
return iterations
def max_A036058_length( start_range=range(11) ):
already_done = set()
max_len = (-1, [])
for n in start_range:
sn = str(n)
sns = tuple(sorted(sn, reverse=True))
if sns not in already_done:
already_done.add(sns)
size = A036058_length(sns)
if size > max_len[0]:
max_len = (size, [n])
elif size == max_len[0]:
max_len[1].append(n)
return max_len
lenmax, starts = max_A036058_length( range(1000000) )
# Expand
allstarts = []
for n in starts:
allstarts += [int(''.join(x))
for x in set(k
for k in permutations(str(n), 4)
if k[0] != '0')]
allstarts = [x for x in sorted(allstarts) if x < 1000000]
print ( '''\
The longest length, followed by the number(s) with the longest sequence length
for starting sequence numbers below 1000000 are:
Iterations = %i and sequence-starts = %s.''' % (lenmax, allstarts) )
print ( '''
Note that only the first of any sequences with the same digits is printed below.
(The others will differ only in their first term)''' )
for n in starts:
print()
A036058_length(str(n), printit=True) |
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).
| #OCaml | OCaml | let unique lst =
let f lst x = if List.mem x lst then lst else x::lst in
List.rev (List.fold_left f [] lst)
let ( -| ) a b =
unique (List.filter (fun v -> not (List.mem v b)) a)
let ( -|- ) a b = (b -| a) @ (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).
| #ooRexx | ooRexx | a = .set~of("John", "Bob", "Mary", "Serena")
b = .set~of("Jim", "Mary", "John", "Bob")
-- the xor operation is a symmetric difference
do item over a~xor(b)
say item
end |
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
| #LiveCode | LiveCode | function convertDegrees k
put k/5 * 9 into r
put k - 273.15 into c
put r - 459.67 into f
return k,r,c,f
end convertDegrees |
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
| #Lua | Lua | function convert_temp(k)
local c = k - 273.15
local r = k * 1.8
local f = r - 459.67
return k, c, r, f
end
print(string.format([[
Kelvin: %.2f K
Celcius: %.2f °C
Rankine: %.2f °R
Fahrenheit: %.2f °F
]],convert_temp(21.0))) |
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
| #Vedit_macro_language | Vedit macro language | for (#1 = 1; #1 <= 12; #1++) {
Num_Str(#1, 9, LEFT)
IT("On the ")
Call("day |@(9)")
IT(" day of Christmas, my true love sent to me:") IN
Call("gift |@(9)")
IN
}
return
:day 1: IT("first") return
:day 2: IT("second") return
:day 3: IT("third") return
:day 4: IT("fourth") return
:day 5: IT("fifth") return
:day 6: IT("sixth") return
:day 7: IT("seventh") return
:day 8: IT("eighth") return
:day 9: IT("ninth") return
:day 10: IT("tenth") return
:day 11: IT("eleventh") return
:day 12: IT("twelfth") return
:gift 12: IT("Twelve drummers drumming,") IN
:gift 11: IT("Eleven pipers piping,") IN
:gift 10: IT("Ten lords a-leaping,") IN
:gift 9: IT("Nine ladies dancing,") IN
:gift 8: IT("Eight maids a-milking,") IN
:gift 7: IT("Seven swans a-swimming,") IN
:gift 6: IT("Six geese a-laying,") IN
:gift 5: IT("Five gold rings,") IN
:gift 4: IT("Four calling birds,") IN
:gift 3: IT("Three French hens,") IN
:gift 2: IT("Two turtle doves, and") IN
:gift 1: IT("A partridge in a pear tree.") IN
return |
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)
| #IS-BASIC | IS-BASIC | 100 PRINT TIME$ |
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)
| #J | J | 6!:0 ''
2008 1 23 12 52 10.341 |
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.
| #q | q | ls:{raze(string 1_ deltas d,count x),'x d:where differ x} / look & say
sumsay:ls desc@ / summarize & say
seeds:group desc each string til 1000000 / seeds for million integers
seq:(key seeds)!30 sumsay\'key seeds / sequences for unique seeds
top:max its:(count distinct@)each seq / count iterations
/ report results
rpt:{1 x,": ",y,"\n\n";}
rpt["Seeds"]" "sv string raze seeds where its=top / all forms of top seed/s
rpt["Iterations"]string top
rpt["Sequence"]"\n\n","\n"sv raze seq where its=top |
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).
| #Oz | Oz | declare
fun {SymDiff A B}
{Union {Diff A B} {Diff B A}}
end
%% implement sets in terms of lists
fun {MakeSet Xs}
set({Nub2 Xs nil})
end
fun {Diff set(A) set(B)}
set({FoldL B List.subtract A})
end
fun {Union set(A) set(B)}
set({Append A B})
end
%% --
fun {Nub2 Xs Ls}
case Xs of nil then nil
[] X|Xr andthen {Member X Ls} then {Nub2 Xr Ls}
[] X|Xr then X|{Nub2 Xr X|Ls}
end
end
in
{Show {SymDiff
{MakeSet [john bob mary serena]}
{MakeSet [jim mary john bob]}}}
{Show {SymDiff
{MakeSet [john serena bob mary serena]}
{MakeSet [jim mary john jim bob]}}} |
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
| #Liberty_BASIC | Liberty BASIC | Do
Input "Kelvin degrees (>=0): ";K
Loop Until (K >= 0)
Print "K = ";K
Print "C = ";(K - 273.15)
Print "F = ";(K * 1.8 - 459.67)
Print "R = ";(K * 1.8)
End |
http://rosettacode.org/wiki/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
| #Maple | Maple | tempConvert := proc(k)
seq(printf("%c: %.2f\n", StringTools[UpperCase](substring(i, 1)), convert(k, temperature, kelvin, i)), i in [kelvin, Celsius, Fahrenheit, Rankine]);
return NULL;
end proc:
tempConvert(21); |
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
| #Vim_Script | Vim Script |
let b:days=["first", "second", "third", "fourth", "fifth", "sixth",
\ "seventh", "eighth", "ninth", "tenth", "eleventh", "twelfth"]
let b:gifts=[
\ "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,"
\ ]
function Nth(n)
echom "On the " . b:days[a:n] . " day of Christmas, my true love gave to me:"
endfunction
call Nth(0)
echom toupper(strpart(b:gifts[0], 4, 1)) . strpart(b:gifts[0], 5)
let b:day = 1
while (b:day < 12)
echom " "
call Nth(b:day)
let b:gift = b:day
while (b:gift >= 0)
echom b:gifts[b:gift]
let b:gift = b:gift - 1
endwhile
let b:day = b:day + 1
endwhile |
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
| #Visual_Basic_.NET | Visual Basic .NET | Module Program
Sub Main()
Dim days = New String(11) {"first", "second", "third", "fourth", "fifth", "sixth", "seventh", "eighth", "ninth", "tenth", "eleventh", "twelfth"}
Dim gifts = New String(11) {
"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"
}
For i = 0 To 11
Console.WriteLine($"On the {days(i)} day of Christmas, my true love gave to me")
For j = i To 0 Step -1
Console.WriteLine(gifts(j))
Next
Console.WriteLine()
If i = 0 Then gifts(0) = "And a partridge in a pear tree"
Next
End Sub
End Module |
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)
| #Java | Java | public class SystemTime{
public static void main(String[] args){
System.out.format("%tc%n", System.currentTimeMillis());
}
} |
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)
| #JavaScript | JavaScript | console.log(new Date()) // => Sat, 28 May 2011 08:22:53 GMT
console.log(Date.now()) // => 1306571005417 // Unix epoch |
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.
| #Racket | Racket |
#lang racket
(define (next s)
(define v (make-vector 10 0))
(for ([c s])
(define d (- (char->integer #\9) (char->integer c)))
(vector-set! v d (add1 (vector-ref v d))))
(string-append* (for/list ([x v] [i (in-range 9 -1 -1)] #:when (> x 0))
(format "~a~a" x i))))
(define (seq-of s)
(reverse (let loop ([ns (list s)])
(define n (next (car ns)))
(if (member n ns) ns (loop (cons n ns))))))
(define (sort-string s)
(list->string (sort (string->list s) char>?)))
(define-values [len nums seq]
(for/fold ([*len #f] [*nums #f] [*seq #f])
([n (in-range 1000000 -1 -1)]) ; start at the high end
(define s (number->string n))
(define sorted (sort-string s))
(cond [(equal? s sorted)
(define seq (seq-of s))
(define len (length seq))
(cond [(or (not *len) (> len *len)) (values len (list s) seq)]
[(= len *len) (values len (cons s *nums) seq)]
[else (values *len *nums *seq)])]
;; not sorted: see if it's a permutation of the best
[else (values
*len
(if (and *nums (member sorted *nums)) (cons s *nums) *nums)
*seq)])))
(printf "Numbers: ~a\nLength: ~a\n" (string-join nums ", ") len)
(for ([n seq]) (printf " ~a\n" n))
|
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).
| #PARI.2FGP | PARI/GP | sd(u,v)={
my(r=List());
u=vecsort(u,,8);
v=vecsort(v,,8);
for(i=1,#u,if(!setsearch(v,u[i]),listput(r,u[i])));
for(i=1,#v,if(!setsearch(u,v[i]),listput(r,v[i])));
Vec(r)
};
sd(["John", "Serena", "Bob", "Mary", "Serena"],["Jim", "Mary", "John", "Jim", "Bob"]) |
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
| #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | tempConvert[t_] := # -> Thread@UnitConvert[#,{"DegreesFahrenheit", "DegreesCelsius", "DegreesRankine"}]&@Quantity[N@t, "Kelvins"]
tempConvert[21] |
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
| #Wren | Wren | var days = [
"first", "second", "third", "fourth", "fifth", "sixth",
"seventh", "eighth", "ninth", "tenth", "eleventh", "twelfth"
]
var gifts = [
"A partridge in a pear tree.", "Two turtle doves 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"
]
for (i in 0..11) {
System.print("On the %(days[i]) day of Christmas,")
System.print("My true love gave to me:")
for (j in i..0) System.print(gifts[j])
System.print()
} |
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)
| #jq | jq | $ jq -n 'now | [., todate]'
[
1437619000.970498,
"2015-07-23T02:36:40Z"
] |
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)
| #Jsish | Jsish | console.log(strftime()); |
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.
| #Raku | Raku | my @list;
my $longest = 0;
my %seen;
for 1 .. 1000000 -> $m {
next unless $m ~~ /0/; # seed must have a zero
my $j = join '', $m.comb.sort;
next if %seen{$j}:exists; # already tested a permutation
%seen{$j} = '';
my @seq = converging($m);
my %elems;
my $count;
for @seq[] -> $value { last if ++%elems{$value} == 2; $count++; };
if $longest == $count {
@list.push($m);
}
elsif $longest < $count {
$longest = $count;
@list = $m;
print "\b" x 20, "$count, $m"; # monitor progress
}
};
for @list -> $m {
say "\nSeed Value(s): ", my $seeds = ~permutations($m).unique.grep( { .substr(0,1) != 0 } );
my @seq = converging($m);
my %elems;
my $count;
for @seq[] -> $value { last if ++%elems{$value} == 2; $count++; };
say "\nIterations: ", $count;
say "\nSequence: (Only one shown per permutation group.)";
.say for |@seq[^$count], "\n";
}
sub converging ($seed) { return $seed, -> $l { join '', map { $_.value.elems~$_.key }, $l.comb.classify({$^b}).sort: {-$^c.key} } ... * }
sub permutations ($string, $sofar? = '' ) {
return $sofar unless $string.chars;
my @perms;
for ^$string.chars -> $idx {
my $this = $string.substr(0,$idx)~$string.substr($idx+1);
my $char = substr($string, $idx,1);
@perms.push( |permutations( $this, join '', $sofar, $char ) );
}
return @perms;
} |
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).
| #Pascal | Pascal | PROGRAM Symmetric_difference;
TYPE
TName = (Bob, Jim, John, Mary, Serena);
TList = SET OF TName;
PROCEDURE Put(txt : String; ResSet : TList);
VAR
I : TName;
BEGIN
Write(txt);
FOR I IN ResSet DO Write(I,' ');
WriteLn
END;
VAR
ListA : TList = [John, Bob, Mary, Serena];
ListB : TList = [Jim, Mary, John, Bob];
BEGIN
Put('ListA -> ', ListA);
Put('ListB -> ', ListB);
Put('ListA >< ListB -> ', ListA >< ListB);
Put('ListA - ListB -> ', ListA - ListB);
Put('ListB - ListA -> ', ListB - ListA);
ReadLn;
END. |
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
| #min | min | (
((float) (273.15 -) (9 5 / * 459.67 -) (9 5 / *)) cleave
() 'cons 4 times "K $1\nC $2\nF $3\nR $4" swap % puts!
) :convert
21 convert |
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
| #XPL0 | XPL0 | int Day, Gift, D, G;
[Day:= [0, "first", "second", "third", "forth", "fifth", "sixth",
"seventh", "eighth", "ninth", "tenth", "eleventh", "twelfth"];
Gift:= [0,
"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,"];
for D:= 1 to 12 do
[Text(0, "On the "); Text(0, Day(D));
Text(0, " day of Christmas
My true love gave to me:
"); for G:= D downto 1 do
[Text(0, Gift(G)); CrLf(0)];
CrLf(0);
];
] |
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
| #Yabasic | Yabasic | 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
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" |
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)
| #Julia | Julia |
ts = time()
println("The system time is (in ISO 8601 format):")
println(strftime(" %F %T %Z", ts))
|
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)
| #Kotlin | Kotlin | // version 1.0.6
fun main(args: Array<String>) {
println("%tc".format(System.currentTimeMillis()))
}
|
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.
| #REXX | REXX | /*REXX pgm generates a self─referential sequence and displays sequences with max length.*/
parse arg LO HI . /*obtain optional arguments from the CL*/
if LO=='' | LO=="," then LO= 1 /*Not specified? Then use the default.*/
if HI=='' | HI=="," then HI=1000000 - 1 /* " " " " " " */
max$=; seeds=; maxL=0 /*inialize some defaults and counters. */
do #=LO to HI; n=#; @.=0; @.#=1 /*loop thru seed; define some defaults.*/
$=n
do c=1 until x==n; x=n /*generate a self─referential sequence.*/
n=; do k=9 by -1 for 10 /*generate a new sequence (downwards). */
_=countstr(k, x) /*obtain the number of sequence counts.*/
if _\==0 then n=n || _ || k /*is count > zero? Then append it to N*/
end /*k*/
if @.n then leave /*has sequence been generated before ? */
$=$'-'n; @.n=1 /*add the number to sequence and roster*/
end /*c*/
if c==maxL then do; seeds=seeds # /*is the sequence equal to max so far ?*/
max$=max$ $ /*append this self─referential # to $ */
end
else if c>maxL then do; seeds=# /*use the new number as the new seed. */
maxL=c; max$=$ /*also, set the new maximum L; max seq.*/
end /* [↑] have we found a new best seq ? */
end /*#*/
say ' seeds that had the most iterations: ' seeds
say 'the maximum self─referential length: ' maxL
do j=1 for words(max$) ; say
say copies('─',30) "iteration sequence for: " word(seeds,j) ' ('maxL "iterations)"
q=translate( word( max$, j), ,'-')
do k=1 for words(q); say word(q, k)
end /*k*/
end /*j*/ /*stick a fork in it, we're all done. */ |
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).
| #Perl | Perl | sub symm_diff {
# two lists passed in as references
my %in_a = map(($_=>1), @{+shift});
my %in_b = map(($_=>1), @{+shift});
my @a = grep { !$in_b{$_} } keys %in_a;
my @b = grep { !$in_a{$_} } keys %in_b;
# return A-B, B-A, A xor B as ref to lists
return \@a, \@b, [ @a, @b ]
}
my @a = qw(John Serena Bob Mary Serena);
my @b = qw(Jim Mary John Jim Bob );
my ($a, $b, $s) = symm_diff(\@a, \@b);
print "A\\B: @$a\nB\\A: @$b\nSymm: @$s\n"; |
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
| #MiniScript | MiniScript | fromKelvin = function(temp)
print temp + " degrees in Kelvin is:"
Celsius = temp - 273.15
print Celsius + " degrees Celsius"
Fahrenheit = round(Celsius * 9/5 + 32,2)
print Fahrenheit + " degrees Fahrenheit"
Rankine = Fahrenheit + 459.67
print Rankine + " degrees Rankine"
end function
temp = input("Enter a temperature in Kelvin: ")
fromKelvin temp.val |
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
| #MiniZinc | MiniZinc | float: kelvin;
var float: celsius;
var float: fahrenheit;
var float: rankine;
constraint celsius == kelvin - 273.15;
constraint fahrenheit == celsius * 1.8 + 32;
constraint rankine == fahrenheit + 459.67;
solve satisfy;
output ["K \(kelvin)\n", "C \(celsius)\n", "F \(fahrenheit)\n", "R \(rankine)\n"]; |
http://rosettacode.org/wiki/The_Twelve_Days_of_Christmas | The Twelve Days of Christmas | Task
Write a program that outputs the lyrics of the Christmas carol The Twelve Days of Christmas.
The lyrics can be found here.
(You must reproduce the words in the correct order, but case, format, and punctuation are left to your discretion.)
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Z80_Assembly | Z80 Assembly | waitChar equ &BB06 ;wait for a key press
PrintChar equ &BB5A ;print accumulator to screen
org &8000
ld ix,VerseTable
inc ix
inc ix
ld iy,SongLookup
ld b,12 ;12 verses total
outerloop_song:
push af ;new line
ld a,13
call PrintChar
ld a,10
call PrintChar
pop af
push bc
push ix
ld ix,VerseTable
ld a,(ix+0)
ld c,a ;get the low byte of verse ptr
ld a,(ix+1)
ld b,a ;get the high byte
pop ix
;bc = the memory location of Verse1
call loop_meta_PrintString
push ix
push iy
ld iy,Verse0
inc (IY+1)
inc (IY+1)
ld a,(IX+2)
ld (IY+7),a
ld a,(IX+3)
ld (IY+8),a
pop iy
pop ix
inc ix
inc ix
pop bc
call WaitChar ;wait for user to press any key before
;continuing so they have time to read it.
djnz outerloop_song
ReturnToBasic:
ret
loop_meta_PrintString:
ld a,(bc)
or a ;compare A to 0. 0 is the null terminator for verses.
ret z
cp 255 ;255 means "goto the verse specified after the 255"
jr z,GotoPreviousVerse
ld (smc_loop_meta_PrintString_alpha+2),a
;use self modifying code to point IY's offset to the correct
; song line, without changing IY itself.
inc a
ld (smc_loop_meta_PrintString_beta+2),a
smc_loop_meta_PrintString_alpha:
ld a,(iy+0) ;the "+0" gets clobbered with the desired lyric low byte
ld L,a
smc_loop_meta_PrintString_beta:
ld a,(iy+0) ;the "+0" gets clobbered with the desired lyric high byte
ld H,a
call PrintString ;now print the string in HL.
inc bc
jp loop_meta_PrintString
GotoPreviousVerse:
inc bc ;advance past &FF opcode
ld a,(bc) ;get low byte
ld e,a
inc bc ;advance to high byte
ld a,(bc)
ld d,a
push de
pop bc
jp loop_meta_PrintString
PrintString:
ld a,(hl)
or a
ret z
call PrintChar
inc hl
jr PrintString
;;;; data
VerseTable:
word Verse0
word Verse1
word Verse2
word Verse3
word Verse4
word Verse5
word Verse6
word Verse7
word Verse8
word Verse9
word Verse10
word Verse11
word Verse12
Verse0:
byte 2
byte 32 ;increment this by 2 after each verse.
byte 4,56,6,56
byte 255
word Verse1 ;look up next verse and write that here too.
;repeat until a hardcoded 12 verses are "sung"
Verse1:
byte 8,56,0
Verse2:
byte 10,56,255
word Verse1
Verse3:
byte 12,56,255
word Verse2
Verse4:
byte 14,56,255
word Verse3
Verse5:
byte 16,56,255
word Verse4
Verse6:
byte 18,56,255
word Verse5
Verse7:
byte 20,56,255
word Verse6
Verse8:
byte 22,56,255
word Verse7
Verse9:
byte 24,56,255
word Verse8
Verse10:
byte 26,56,255
word Verse9
Verse11:
byte 28,56,255
word Verse10
Verse12:
byte 30,56,255
word Verse11
SongLookup:
word null ;0
word Day_Part1 ;2
word Day_Part2 ;4
word Day_Part3 ;6
word Day1 ;8
word Day2 ;10
word Day3 ;12
word Day4 ;14
word Day5 ;16
word Day6 ;18
word Day7 ;20
word Day8 ;22
word Day9 ;24
word Day10 ;26
word Day11 ;28
word Day12 ;30
word First ;32
word Second ;34
word Third ;36
word Fourth ;38
word Fifth ;40
word Sixth ;42
word Seventh ;44
word Eighth ;46
word Ninth ;48
word Tenth ;50
word Eleventh ;52
word Twelfth ;54
word Song_NewLine ;56
null:
byte 0
Day_Part1:
byte "On the",0
Day_Part2:
byte "day of Christmas,",0
Day_Part3:
byte "my true love gave to me",0
Day1:
byte "a partridge in a pear tree.",0
Day2:
byte "two turtle doves, and",0
Day3:
byte "three french hens",0
Day4:
byte "four calling birds",0
Day5:
byte "five golden rings",0
Day6:
byte "six geese a-laying",0
Day7:
byte "seven swans a-swimming",0
Day8:
byte "eight maids a-milking",0
Day9:
byte "nine ladies dancing",0
Day10:
byte "ten lords a-leaping",0
Day11:
byte "eleven pipers piping",0
Day12:
byte "twelve drummers drumming",0
First:
byte " first ",0
Second:
byte " second ",0
Third:
byte " third ",0
Fourth:
byte " fourth ",0
Fifth:
byte " fifth ",0
Sixth:
byte " sixth ",0
Seventh:
byte " seventh ",0
Eighth:
byte " eighth ",0
Ninth:
byte " ninth ",0
Tenth:
byte " tenth ",0
Eleventh:
byte " eleventh ",0
Twelfth:
byte " twelfth ",0
Song_NewLine:
byte 13,10,0 ;control codes for a new line. |
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)
| #Lambdatalk | Lambdatalk |
{date}
-> 2021 02 22 07 23 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)
| #Lasso | Lasso | date->format('%Q %T')
date->asInteger |
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.
| #Ruby | Ruby | $cache = {}
def selfReferentialSequence_cached(n, seen = [])
return $cache[n] if $cache.include? n
return [] if seen.include? n
digit_count = Array.new(10, 0)
n.to_s.chars.collect {|char| digit_count[char.to_i] += 1}
term = ''
9.downto(0).each do |d|
if digit_count[d] > 0
term += digit_count[d].to_s + d.to_s
end
end
term = term.to_i
$cache[n] = [n] + selfReferentialSequence_cached(term, [n] + seen)
end
limit = 1_000_000
max_len = 0
max_vals = []
1.upto(limit - 1) do |n|
seq = selfReferentialSequence_cached(n)
if seq.length > max_len
max_len = seq.length
max_vals = [n]
elsif seq.length == max_len
max_vals << n
end
end
puts "values: #{max_vals.inspect}"
puts "iterations: #{max_len}"
puts "sequence:"
selfReferentialSequence_cached(max_vals[0]).each_with_index do |val, idx|
puts "%2d %d" % [idx + 1, val]
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).
| #Phix | Phix | function Union(sequence a, sequence b)
for i=1 to length(a) do
if not find(a[i],b) then
b = append(b,a[i])
end if
end for
return b
end function
function Difference(sequence a, sequence b)
sequence res = {}
for i=1 to length(a) do
if not find(a[i],b)
and not find(a[i],res) then
res = append(res,a[i])
end if
end for
return res
end function
function Symmetric_Difference(sequence a, sequence b)
return Union(Difference(a, b), Difference(b, a))
end function
sequence a = {"John", "Serena", "Bob", "Mary", "Serena"},
b = {"Jim", "Mary", "John", "Jim", "Bob"}
?Symmetric_Difference(a,a)
?Symmetric_Difference(a,b)
?Symmetric_Difference(b,a)
?Symmetric_Difference(b,b)
|
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
| #.D0.9C.D0.9A-61.2F52 | МК-61/52 | П7 0 , 8 * П8 ИП7 9 * 5
/ 3 2 + П9 ИП7 2 7 3 ,
1 5 + П4 С/П П8 1 , 8 /
БП 00 П9 3 2 - 5 * 9 /
БП 00 П4 2 7 3 , 1 5 -
БП 00 |
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
| #ML | ML | fun KtoC n = n - 273.15;
fun KtoF n = n * 1.8 - 459.67;
fun KtoR n = n * 1.8;
val K = argv 0;
if K = false then
println "mlite -f temcon.m <temp>"
else
let
val K = ston K
in
print "Kelvin: "; println K;
print "Celcius: "; println ` KtoC K;
print "Fahrenheit: "; println ` KtoF K;
print "Rankine: "; println ` KtoR K
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
| #zkl | zkl | gifts:=
#<<<
"A beer, in a tree.; Two turtlenecks; Three french toast;
Four pounds of backbacon; Five golden touques; Six packs of two-four;
Seven packs of smokes; Eight comic books; Nine back up singers;
Ten feet of snow; Eleven hosers hosing; Twelve dozen donuts"
#<<<
.split(";").apply("strip");
days:=("first second third fourth fifth sixth seventh eighth ninth tenth "
"eleventh twelfth").split();
foreach n,day in (days.enumerate()){ n+=1;
g:=gifts[0,n].reverse();
println("On the %s day of Christmas\nMy true love gave to me:\n".fmt(day),
g[0,-1].concat("\n"), (n>1) and " and\n" or "", g[-1], "\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)
| #LFE | LFE |
> (os:timestamp)
#(1423 786308 145798)
|
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)
| #Liberty_BASIC | Liberty BASIC | print time$() 'time now as string "16:21:44"
print time$("seconds") 'seconds since midnight as number 32314
print time$("milliseconds") 'milliseconds since midnight as number 33221342
print time$("ms") 'milliseconds since midnight as number 33221342 |
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.
| #Scala | Scala | import spire.math.SafeLong
import scala.annotation.tailrec
import scala.collection.parallel.immutable.ParVector
object SelfReferentialSequence {
def main(args: Array[String]): Unit = {
val nums = ParVector.range(1, 1000001).map(SafeLong(_))
val seqs = nums.map{ n => val seq = genSeq(n); (n, seq, seq.length) }.toVector.sortWith((a, b) => a._3 > b._3)
val maxes = seqs.takeWhile(t => t._3 == seqs.head._3)
println(s"Seeds: ${maxes.map(_._1).mkString(", ")}\nIterations: ${maxes.head._3}")
for(e <- maxes.distinctBy(a => nextTerm(a._1.toString))){
println(s"\nSeed: ${e._1}\n${e._2.mkString("\n")}")
}
}
def genSeq(seed: SafeLong): Vector[String] = {
@tailrec
def gTrec(seq: Vector[String], n: String): Vector[String] = {
if(seq.contains(n)) seq
else gTrec(seq :+ n, nextTerm(n))
}
gTrec(Vector[String](), seed.toString)
}
def nextTerm(num: String): String = {
@tailrec
def dTrec(digits: Vector[(Int, Int)], src: String): String = src.headOption match{
case Some(n) => dTrec(digits :+ ((n.asDigit, src.count(_ == n))), src.filter(_ != n))
case None => digits.sortWith((a, b) => a._1 > b._1).map(p => p._2.toString + p._1.toString).mkString
}
dTrec(Vector[(Int, Int)](), num)
}
} |
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).
| #PHP | PHP | <?php
$a = array('John', 'Bob', 'Mary', 'Serena');
$b = array('Jim', 'Mary', 'John', 'Bob');
// Remove any duplicates
$a = array_unique($a);
$b = array_unique($b);
// Get the individual differences, using array_diff()
$a_minus_b = array_diff($a, $b);
$b_minus_a = array_diff($b, $a);
// Simply merge them together to get the symmetric difference
$symmetric_difference = array_merge($a_minus_b, $b_minus_a);
// Present our results.
echo 'List A: ', implode(', ', $a),
"\nList B: ", implode(', ', $b),
"\nA \\ B: ", implode(', ', $a_minus_b),
"\nB \\ A: ", implode(', ', $b_minus_a),
"\nSymmetric difference: ", implode(', ', $symmetric_difference), "\n";
?> |
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
| #Nanoquery | Nanoquery | % while true
... print "K ? "
... k = float(input())
...
... println format("%g Kelvin = %g Celsius = %g Fahrenheit = %g Rankine degrees.", k, k-273.15, k*1.8-459.67, k*1.8)
... end
K ? 21
21.0000 Kelvin = -252.150 Celsius = -421.870 Fahrenheit = 37.8000 Rankine degrees.
K ? 222.2
222.200 Kelvin = -50.9500 Celsius = -59.7100 Fahrenheit = 399.960 Rankine degrees.
K ? |
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)
| #LIL | LIL | print [system date]; print [system date +%s.%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)
| #Lingo | Lingo | put time()
-- "03:45"
put date()
-- "01.10.2016"
put the systemdate
-- date( 2016, 10, 1 )
put the systemdate.seconds
-- 13950
-- milliseconds since last boot, due to higher resolution better suited for random number seeding
put _system.milliseconds
-- 41746442 |
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.
| #Tcl | Tcl | proc nextterm n {
foreach c [split $n ""] {incr t($c)}
foreach c {9 8 7 6 5 4 3 2 1 0} {
if {[info exist t($c)]} {append r $t($c) $c}
}
return $r
}
# Local context of lambda term is just for speed
apply {limit {
# Build a digit cache; this adds quite a bit of speed
set done [lrepeat [set l2 [expr {$limit * 100}]] 0]
# Iterate over search space
set maxlen 0
set maxes {}
for {set i 0} {$i < $limit} {incr i} {
if {[lindex $done $i]} continue
# Compute the sequence length for this value (with help from cache)
set seq {}
for {set seed $i} {$seed ni $seq} {set seed [nextterm $seed]} {
if {$seed < $l2 && [lindex $done $seed]} {
set len [expr {[llength $seq] + [lindex $done $seed]}]
break
}
set len [llength [lappend seq $seed]]
}
# What are we going to do about it?
if {$len > $maxlen} {
set maxlen $len
set maxes [list $i]
} elseif {$len == $maxlen} {
lappend maxes $i
}
# Update the cache with what we have learned
foreach n $seq {
if {$n < $l2} {lset done $n $len}
incr len -1
}
}
# Output code
puts "max length: $maxlen"
foreach c $maxes {puts $c}
puts "Sample max-len sequence:"
set seq {}
# Rerun the sequence generator for printing; faster for large limits
for {set seed [lindex $c 0]} {$seed ni $seq} {set seed [nextterm $seed]} {
lappend seq $seed
puts "\t$seed"
}
}} 1000000 |
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).
| #Picat | Picat | import ordset.
go =>
A = ["John", "Serena", "Bob", "Mary", "Serena"].new_ordset(),
B = ["Jim", "Mary", "John", "Jim", "Bob"].new_ordset(),
println(symmetric_difference=symmetric_difference(A,B)),
println(symmetric_difference2=symmetric_difference2(A,B)),
println(subtractAB=subtract(A,B)),
println(subtractBA=subtract(B,A)),
println(union=union(A,B)),
println(intersection=intersection(A,B)),
nl.
symmetric_difference(A,B) = union(subtract(A,B), subtract(B,A)).
% variant
symmetric_difference2(A,B) = subtract(union(A,B), intersection(B,A)). |
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).
| #PicoLisp | PicoLisp | (de symdiff (A B)
(uniq (conc (diff A B) (diff B A))) ) |
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
| #NetRexx | NetRexx | /* NetRexx */
options replace format comments java crossref symbols
numeric digits 20
runSample(arg)
return
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/*
+ Kelvin Celsius Fahrenheit Rankine Delisle Newton Réaumur Rømer
K T T-273.15 T*9/5-459.67 T*9/5 (373.15-T)*3/2 (T-273.15)*33/100 (T-273.15)*4/5 (T-273.15)*21/40+7.5
C T+273.15 T T*9/5+32 (T+273.15)*9/5 (100-T)*3/2 T*33/100 T*4/5 T*21/40+7.5
F (T+459.67)*5/9 (T-32)*5/9 T T+459.67 (212-T)*5/6 (T-32)*11/60 (T-32)*4/9 (T-32)*7/24+7.5
R T*5/9 (T-491.67)*5/9 T-459.67 T (671.67-T)*5/6 (T-491.67)*11/60 (T-491.67)*4/9 (T-491.67)*7/24+7.5
De 373.15-T*2/3 100-T*2/3 212-T*6/5 671.67-T*6/5 T 33-T*11/50 80-T*8/15 60-T*7/20
N T*100/33+273.15 T*100/33 T*60/11+32 T*60/11+491.67 (33-T)*50/11 T T*80/33 T*35/22+7.5
Ré T*5/4+273.15 T*5/4 T*9/4+32 T*9/4+491.67 (80-T)*15/8 T*33/80 T T*21/32+7.5
Rø (T-7.5)*40/21+273.15 (T-7.5)*40/21 (T-7.5)*24/7+32 (T-7.5)*24/7+491.67 (60-T)*20/7 (T-7.5)*22/35 (T-7.5)*32/21 T
*/
method temperatureConversion(scaleFrom, scaleTo, T) public static
parse 'KELVIN CELSIUS FAHRENHEIT RANKINE DELISLE NEWTON REAUMUR ROEMER' -
KELVIN CELSIUS FAHRENHEIT RANKINE DELISLE NEWTON REAUMUR ROEMER .
scaleFrom = scaleFrom.upper()
scaleTo = scaleTo.upper()
select label sF case scaleFrom
when KELVIN then do
select case scaleTo
when KELVIN then val = T
when CELSIUS then val = T - 273.15
when FAHRENHEIT then val = T * 9 / 5 - 459.67
when RANKINE then val = T * 9 / 5
when DELISLE then val = (373.15 - T) * 3 / 2
when NEWTON then val = (T - 273.15) * 33 / 100
when REAUMUR then val = (T - 273.15) * 4 / 5
when ROEMER then val = (T - 273.15) * 21 / 40 + 7.5
otherwise signal IllegalArgumentException(scaleFrom',' scaleTo',' T)
end
end
when CELSIUS then do
select case scaleTo
when KELVIN then val = T + 273.15
when CELSIUS then val = T
when FAHRENHEIT then val = T * 9 / 5 + 32
when RANKINE then val = (T + 273.15) * 9 / 5
when DELISLE then val = (100 - T) * 3 / 2
when NEWTON then val = T * 33 / 100
when REAUMUR then val = T * 4 / 5
when ROEMER then val = T * 21 / 40 + 7.5
otherwise signal IllegalArgumentException(scaleFrom',' scaleTo',' T)
end
end
when FAHRENHEIT then do
select case scaleTo
when KELVIN then val = (T + 459.67) * 5 / 9
when CELSIUS then val = (T - 32) * 5 / 9
when FAHRENHEIT then val = T
when RANKINE then val = T + 459.67
when DELISLE then val = (212 - T) * 5 / 6
when NEWTON then val = (T - 32) * 11 / 60
when REAUMUR then val = (T - 32) * 4 / 9
when ROEMER then val = (T - 32) * 7 / 24 + 7.5
otherwise signal IllegalArgumentException(scaleFrom',' scaleTo',' T)
end
end
when RANKINE then do
select case scaleTo
when KELVIN then val = T * 5 / 9
when CELSIUS then val = (T - 491.67) * 5 / 9
when FAHRENHEIT then val = T - 459.67
when RANKINE then val = T
when DELISLE then val = (671.67 - T) * 5 / 6
when NEWTON then val = (T - 491.67) * 11 / 60
when REAUMUR then val = (T - 491.67) * 4 / 9
when ROEMER then val = (T - 491.67) * 7 / 24 + 7.5
otherwise signal IllegalArgumentException(scaleFrom',' scaleTo',' T)
end
end
when DELISLE then do
select case scaleTo
when KELVIN then val = 373.15 - T * 2 / 3
when CELSIUS then val = 100 - T * 2 / 3
when FAHRENHEIT then val = 212 - T * 6 / 5
when RANKINE then val = 671.67 - T * 6 / 5
when DELISLE then val = T
when NEWTON then val = 33 - T * 11 / 50
when REAUMUR then val = 80 - T * 8 / 15
when ROEMER then val = 60 - T * 7 / 20
otherwise signal IllegalArgumentException(scaleFrom',' scaleTo',' T)
end
end
when NEWTON then do
select case scaleTo
when KELVIN then val = T * 100 / 33 + 273.15
when CELSIUS then val = T * 100 / 33
when FAHRENHEIT then val = T * 60 / 11 + 32
when RANKINE then val = T * 60 / 11 + 491.67
when DELISLE then val = (33 - T) * 50 / 11
when NEWTON then val = T
when REAUMUR then val = T * 80 / 33
when ROEMER then val = T * 35 / 22 + 7.5
otherwise signal IllegalArgumentException(scaleFrom',' scaleTo',' T)
end
end
when REAUMUR then do
select case scaleTo
when KELVIN then val = T * 5 / 4 + 273.15
when CELSIUS then val = T * 5 / 4
when FAHRENHEIT then val = T * 9 / 4 + 32
when RANKINE then val = T * 9 / 4 + 491.67
when DELISLE then val = (80 - T) * 15 / 8
when NEWTON then val = T * 33 / 80
when REAUMUR then val = T
when ROEMER then val = T * 21 / 32 + 7.5
otherwise signal IllegalArgumentException(scaleFrom',' scaleTo',' T)
end
end
when ROEMER then do
select case scaleTo
when KELVIN then val = (T - 7.5) * 40 / 21 + 273.15
when CELSIUS then val = (T - 7.5) * 40 / 21
when FAHRENHEIT then val = (T - 7.5) * 24 / 7 + 32
when RANKINE then val = (T - 7.5) * 24 / 7 + 491.67
when DELISLE then val = (60 - T) * 20 / 7
when NEWTON then val = (T - 7.5) * 22 / 35
when REAUMUR then val = (T - 7.5) * 32 / 21
when ROEMER then val = T
otherwise signal IllegalArgumentException(scaleFrom',' scaleTo',' T)
end
end
otherwise
signal IllegalArgumentException(scaleFrom',' scaleTo',' T)
end sF
return val
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
method runSample(arg) public static
tlist = [ -
/* C....... F....... K....... R.......*/ -
' 5500.00 9932.00 5773.15 10391.67', -
' 300.00 572.00 573.15 1031.67', -
' 200.00 392.00 473.15 851.67', -
' 100.00 212.00 373.15 671.67', -
' 37.00 98.60 310.15 558.27', -
' 0.00 32.00 273.15 491.67', -
' -100.00 -148.00 173.15 311.67', -
' -200.00 -328.00 73.15 131.67', -
' -252.15 -421.87 21.00 37.80', -
' -273.15 -459.67 0.00 0.00' -
]
parse 'CELSIUS FAHRENHEIT KELVIN RANKINE' CELSIUS FAHRENHEIT KELVIN RANKINE .
loop temp over tlist
parse temp ttC ttF ttK ttR .
say ' C....... F....... K....... R.......'
say 'C ' -
temperatureConversion(CELSIUS, CELSIUS, ttC).format(5, 2) -
temperatureConversion(CELSIUS, FAHRENHEIT, ttC).format(5, 2) -
temperatureConversion(CELSIUS, KELVIN, ttC).format(5, 2) -
temperatureConversion(CELSIUS, RANKINE, ttC).format(5, 2)
say 'F ' -
temperatureConversion(FAHRENHEIT, CELSIUS, ttF).format(5, 2) -
temperatureConversion(FAHRENHEIT, FAHRENHEIT, ttF).format(5, 2) -
temperatureConversion(FAHRENHEIT, KELVIN, ttF).format(5, 2) -
temperatureConversion(FAHRENHEIT, RANKINE, ttF).format(5, 2)
say 'K ' -
temperatureConversion(KELVIN, CELSIUS, ttK).format(5, 2) -
temperatureConversion(KELVIN, FAHRENHEIT, ttK).format(5, 2) -
temperatureConversion(KELVIN, KELVIN, ttK).format(5, 2) -
temperatureConversion(KELVIN, RANKINE, ttK).format(5, 2)
say 'R ' -
temperatureConversion(RANKINE, CELSIUS, ttR).format(5, 2) -
temperatureConversion(RANKINE, FAHRENHEIT, ttR).format(5, 2) -
temperatureConversion(RANKINE, KELVIN, ttR).format(5, 2) -
temperatureConversion(RANKINE, RANKINE, ttR).format(5, 2)
say
end temp
return
|
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)
| #LiveCode | LiveCode | put the system time |
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)
| #Locomotive_Basic | Locomotive Basic | print time
print time/300;"s since last reboot" |
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.
| #TXR | TXR | ;; Syntactic sugar for calling reduce-left
(defmacro reduce-with ((acc init item sequence) . body)
^(reduce-left (lambda (,acc ,item) ,*body) ,sequence ,init))
;; Macro similar to clojure's ->> and ->
(defmacro opchain (val . ops)
^[[chain ,*[mapcar [iffi consp (op cons 'op)] ops]] ,val])
;; Reduce integer to a list of integers representing its decimal digits.
(defun digits (n)
(if (< n 10)
(list n)
(opchain n tostring list-str (mapcar (op - @1 #\0)))))
(defun dcount (ds)
(digits (length ds)))
;; Perform a look-say step like (1 2 2) --"one 1, two 2's"-> (1 1 2 2).
(defun summarize-prev (ds)
(opchain ds copy (sort @1 >) (partition-by identity)
(mapcar [juxt dcount first]) flatten))
;; Take a starting digit string and iterate the look-say steps,
;; to generate the whole sequence, which ends when convergence is reached.
(defun convergent-sequence (ds)
(reduce-with (cur-seq nil ds [giterate true summarize-prev ds])
(if (member ds cur-seq)
(return-from convergent-sequence cur-seq)
(nconc cur-seq (list ds)))))
;; A candidate sequence is one which begins with montonically
;; decreasing digits. We don't bother with (9 0 9 0) or (9 0 0 9);
;; which yield identical sequences to (9 9 0 0).
(defun candidate-seq (n)
(let ((ds (digits n)))
(if [apply >= ds]
(convergent-sequence ds))))
;; Discover the set of longest sequences.
(defun find-longest (limit)
(reduce-with (max-seqs nil new-seq [mapcar candidate-seq (range 1 limit)])
(let ((cmp (- (opchain max-seqs first length) (length new-seq))))
(cond ((> cmp 0) max-seqs)
((< cmp 0) (list new-seq))
(t (nconc max-seqs (list new-seq)))))))
(defvar *results* (find-longest 1000000))
(each ((result *results*))
(flet ((strfy (list) ;; (strfy '((1 2 3 4) (5 6 7 8))) -> ("1234" "5678")
(mapcar [chain (op mapcar tostring) cat-str] list)))
(let* ((seed (first result))
(seeds (opchain seed perm uniq (remove-if zerop @1 first))))
(put-line `Seed value(s): @(strfy seeds)`)
(put-line)
(put-line `Iterations: @(length result)`)
(put-line)
(put-line `Sequence: @(strfy 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).
| #Pike | Pike | > multiset(string) A = (< "John", "Serena", "Bob", "Mary", "Bob", "Serena" >);
> multiset(string) B = (< "Jim", "Mary", "Mary", "John", "Bob", "Jim" >);
> A^B;
Result: (< "Bob", "Serena", "Serena", "Mary", "Jim", "Jim" >) |
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
| #Never | Never |
func KtoC(k : float) -> float { k - 273.15 }
func KtoF(k : float) -> float { k * 1.8 - 459.67 }
func KtoR(k : float) -> float { k * 1.8 }
func convertK(k : float) -> int {
prints("K " + k + "\n");
prints("C " + KtoC(k) + "\n");
prints("F " + KtoF(k) + "\n");
prints("R " + KtoR(k) + "\n");
0
}
func main(k : float) -> int {
convertK(k);
0
}
|
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)
| #Logo | Logo |
to time
output first first shell [date +%s]
end
make "start time
wait 300 ; 60ths of a second
print time - :start ; 5 |
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)
| #Lua | Lua | print(os.date()) |
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.
| #Wren | Wren | import "/seq" for Lst
import "/math" for Nums
var limit = 1e6
var selfRefSeq = Fn.new { |s|
var sb = ""
for (d in "9876543210") {
if (s.contains(d)) {
var count = s.count { |c| c == d }
sb = sb + "%(count)%(d)"
}
}
return sb
}
var permute // recursive
permute = Fn.new { |input|
if (input.count == 1) return [input]
var perms = []
var toInsert = input[0]
for (perm in permute.call(input[1..-1])) {
for (i in 0..perm.count) {
var newPerm = perm.toList
newPerm.insert(i, toInsert)
perms.add(newPerm)
}
}
return perms
}
var sieve = List.filled(limit, 0)
var elements = []
for (n in 1...limit) {
if (sieve[n] == 0) {
elements.clear()
var next = n.toString
elements.add(next)
while (true) {
next = selfRefSeq.call(next)
if (elements.contains(next)) {
var size = elements.count
sieve[n] = size
if (n > 9) {
var perms = permute.call(n.toString.toList).map { |p| p.join("") }.toList
perms = Lst.distinct(perms)
for (perm in perms) {
if (perm[0] != "0") {
var k = Num.fromString(perm.join(""))
sieve[k] = size
}
}
}
break
}
elements.add(next)
}
}
}
var maxIterations = Nums.max(sieve)
for (n in 1...limit) {
if (sieve[n] >= maxIterations) {
System.print("%(n) -> Iterations = %(maxIterations)")
var next = n.toString
for (i in 1..maxIterations) {
System.print(next)
next = selfRefSeq.call(next)
}
System.print()
}
} |
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).
| #PL.2FI | PL/I | /* PL/I ***************************************************************
* 17.08.2013 Walter Pachl
**********************************************************************/
*process source attributes xref;
sd: Proc Options(main);
Dcl a(4) Char(20) Var Init('John','Bob','Mary','Serena');
Dcl b(4) Char(20) Var Init('Jim','Mary','John','Bob');
Call match(a,b);
Call match(b,a);
match: Proc(x,y);
Dcl (x(*),y(*)) Char(*) Var;
Dcl (i,j) Bin Fixed(31);
Do i=1 To hbound(x);
Do j=1 To hbound(y);
If x(i)=y(j) Then Leave;
End;
If j>hbound(y) Then
Put Edit(x(i))(Skip,a);
End;
End;
End; |
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
| #NewLISP | NewLISP |
(define (to-celsius k)
(- k 273.15)
)
(define (to-fahrenheit k)
(- (* k 1.8) 459.67)
)
(define (to-rankine k)
(* k 1.8)
)
(define (kelvinConversion k)
(if (number? k)
(println k " kelvin is equivalent to:\n"
(to-celsius k) " celsius\n"
(to-fahrenheit k) " fahrenheit\n"
(to-rankine k) " rankine")
(println "Please enter a number only, with no º or letter. ")
)
)
|
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)
| #M2000_Interpreter | M2000 Interpreter |
print str$(now,"long time"), time$(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)
| #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | Print[DateList[]]
Print[AbsoluteTime[]] |
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.
| #zkl | zkl | N:=0d1_000_001;
fcn lookAndJustSaying(seed){ // numeric String --> numeric String
"9876543210".pump(String,'wrap(n){
(s:=seed.inCommon(n)) and String(s.len(),n) or ""
});
}
fcn sequence(seed){ // numeric string --> sequence until it repeats
seq:=L();
while(not seq.holds(seed)){ seq.append(seed); seed=lookAndJustSaying(seed); }
seq
}
fcn decending(str) //--> True if digits are in descending (or equal) order
{ (not str.walker().zipWith('<,str[1,*]).filter1()) }
szs:=List.createLong(25); max:=0;
foreach seed in (N){
z:=seed.toString();
if(decending(z)){ // 321 generates same sequence as 312,132,123,213
len:=sequence(z).len();
if(len>max) szs.clear();
if(len>=max){ szs.append(seed.toString()); max=len; }
}
}
// List permutations of longest seeds
// ("9900"-->(((9,0,0,9),...))-->((9,0,0,9),...)-->("9009"...)
// -->remove numbers w/leading zeros-->remove dups
zs:=szs.apply(Utils.Helpers.permute).flatten().apply("concat")
.filter(fcn(s){ s[0]!="0" }) : Utils.Helpers.listUnique(_);
println(max," iterations for ",zs.concat(", "));
zs.pump(Console.println,sequence,T("concat",", ")); |
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).
| #PowerShell | PowerShell | $A = @( "John"
"Bob"
"Mary"
"Serena" )
$B = @( "Jim"
"Mary"
"John"
"Bob" )
# Full commandlet name and full parameter names
Compare-Object -ReferenceObject $A -DifferenceObject $B
# Same commandlet using an alias and positional parameters
Compare $A $B
# A - B
Compare $A $B | Where SideIndicator -eq "<=" | Select -ExpandProperty InputObject
# B - A
Compare $A $B | Where SideIndicator -eq "=>" | Select -ExpandProperty InputObject |
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
| #Nim | Nim | import rdstdin, strutils, strfmt
while true:
let k = parseFloat readLineFromStdin "K ? "
echo "{:g} Kelvin = {:g} Celsius = {:g} Fahrenheit = {:g} Rankine degrees".fmt(
k, k - 273.15, k * 1.8 - 459.67, k * 1.8) |
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)
| #MATLAB_.2F_Octave | MATLAB / Octave | datestr(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)
| #Maxima | Maxima | /* Time and date in a formatted string */
timedate();
"2012-08-27 20:26:23+10:00"
/* Time in seconds elapsed since 1900/1/1 0:0:0 */
absolute_real_time();
/* Time in seconds since Maxima was started */
elapsed_real_time();
elapsed_run_time(); |
http://rosettacode.org/wiki/Sum_of_elements_below_main_diagonal_of_matrix | Sum of elements below main diagonal of matrix | Task
Find and display the sum of elements that are below the main diagonal of a matrix.
The matrix should be a square matrix.
─── Matrix to be used: ───
[[1,3,7,8,10],
[2,4,16,14,4],
[3,1,9,18,11],
[12,14,17,18,20],
[7,1,3,9,5]]
| #11l | 11l | F sumBelowDiagonal(m)
V result = 0
L(i) 1 .< m.len
L(j) 0 .< i
result += m[i][j]
R result
V m = [[ 1, 3, 7, 8, 10],
[ 2, 4, 16, 14, 4],
[ 3, 1, 9, 18, 11],
[12, 14, 17, 18, 20],
[ 7, 1, 3, 9, 5]]
print(sumBelowDiagonal(m)) |
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).
| #Prolog | Prolog | sym_diff :-
A = ['John', 'Serena', 'Bob', 'Mary', 'Serena'],
B = ['Jim', 'Mary', 'John', 'Jim', 'Bob'],
format('A : ~w~n', [A]),
format('B : ~w~n', [B]),
list_to_set(A, SA),
list_to_set(B, SB),
format('set from A : ~w~n', [SA]),
format('set from B : ~w~n', [SB]),
subtract(SA, SB, DAB),
format('difference A\\B : ~w~n', [DAB]),
subtract(SB, SA, DBA),
format('difference B\\A : ~w~n', [DBA]),
union(DAB, DBA, Diff),
format('symetric difference : ~w~n', [Diff]). |
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
| #Objeck | Objeck |
class Temperature {
function : Main(args : String[]) ~ Nil {
k := System.IO.Console->ReadString()->ToFloat();
c := KelvinToCelsius(k);
f := KelvinToFahrenheit(k);
r := KelvinToRankine(k);
"K: {$k}"->PrintLine();
"C: {$c}"->PrintLine();
"F: {$f}"->PrintLine();
"R: {$r}"->PrintLine();
}
function : KelvinToCelsius(k : Float) ~ Float {
return k - 273.15;
}
function : KelvinToFahrenheit(k : Float) ~ Float {
return k * 1.8 - 459.67;
}
function : KelvinToRankine(k : Float) ~ Float {
return k * 1.8;
}
}
|
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)
| #min | min | now datetime puts! |
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)
| #Modula-2 | Modula-2 |
MODULE Mytime;
FROM SysClock IMPORT
GetClock, DateTime;
FROM STextIO IMPORT
WriteString, WriteLn;
FROM FormatDT IMPORT
DateTimeToString;
VAR
CurrentTime: DateTime;
DateStr, TimeStr: ARRAY [0 .. 20] OF CHAR;
BEGIN
GetClock(CurrentTime);
DateTimeToString(CurrentTime, DateStr, TimeStr);
WriteString("Current time: ");
WriteString(DateStr);
WriteString(" ");
WriteString(TimeStr);
WriteLn;
END Mytime.
|
http://rosettacode.org/wiki/Sum_of_elements_below_main_diagonal_of_matrix | Sum of elements below main diagonal of matrix | Task
Find and display the sum of elements that are below the main diagonal of a matrix.
The matrix should be a square matrix.
─── Matrix to be used: ───
[[1,3,7,8,10],
[2,4,16,14,4],
[3,1,9,18,11],
[12,14,17,18,20],
[7,1,3,9,5]]
| #Action.21 | Action! | PROC PrintMatrix(INT ARRAY m BYTE size)
BYTE x,y
INT v
FOR y=0 TO size-1
DO
FOR x=0 TO size-1
DO
v=m(x+y*size)
IF v<10 THEN Put(32) FI
PrintB(v) Put(32)
OD
PutE()
OD
RETURN
INT FUNC SumBelowDiagonal(INT ARRAY m BYTE size)
BYTE x,y
INT sum
sum=0
FOR y=1 TO size-1
DO
FOR x=0 TO y-1
DO
sum==+m(x+y*size)
OD
OD
RETURN (sum)
PROC Main()
INT sum
INT ARRAY m=[
1 3 7 8 10
2 4 16 14 4
3 1 9 18 11
12 14 17 18 20
7 1 3 9 5]
PrintE("Matrix")
PrintMatrix(m,5)
PutE()
sum=SumBelowDiagonal(m,5)
PrintF("Sum below diagonal is %I",sum)
RETURN |
http://rosettacode.org/wiki/Sum_of_elements_below_main_diagonal_of_matrix | Sum of elements below main diagonal of matrix | Task
Find and display the sum of elements that are below the main diagonal of a matrix.
The matrix should be a square matrix.
─── Matrix to be used: ───
[[1,3,7,8,10],
[2,4,16,14,4],
[3,1,9,18,11],
[12,14,17,18,20],
[7,1,3,9,5]]
| #Ada | Ada | with Ada.Text_Io;
with Ada.Numerics.Generic_Real_Arrays;
procedure Sum_Below_Diagonals is
type Real is new Float;
package Real_Arrays
is new Ada.Numerics.Generic_Real_Arrays (Real);
function Sum_Below_Diagonal (M : Real_Arrays.Real_Matrix) return Real
with Pre => M'Length (1) = M'Length (2)
is
Sum : Real := 0.0;
begin
for Row in 0 .. M'Length (1) - 1 loop
for Col in 0 .. Row - 1 loop
Sum := Sum + M (M'First (1) + Row,
M'First (2) + Col);
end loop;
end loop;
return Sum;
end Sum_Below_Diagonal;
M : constant Real_Arrays.Real_Matrix :=
(( 1.0, 3.0, 7.0, 8.0, 10.0),
( 2.0, 4.0, 16.0, 14.0, 4.0),
( 3.0, 1.0, 9.0, 18.0, 11.0),
(12.0, 14.0, 17.0, 18.0, 20.0),
( 7.0, 1.0, 3.0, 9.0, 5.0));
Sum : constant Real := Sum_Below_Diagonal (M);
package Real_Io is new Ada.Text_Io.Float_Io (Real);
use Ada.Text_Io, Real_Io;
begin
Put ("Sum below diagonal: ");
Put (Sum, Exp => 0, Aft => 1);
New_Line;
end Sum_Below_Diagonals; |
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).
| #PureBasic | PureBasic | Dim A.s(3)
Dim B.s(3)
A(0)="John": A(1)="Bob": A(2)="Mary": A(3)="Serena"
B(0)="Jim": B(1)="Mary":B(2)="John": B(3)="Bob"
For a=0 To ArraySize(A()) ; A-B
For b=0 To ArraySize(B())
If A(a)=B(b)
Break
ElseIf b=ArraySize(B())
Debug A(a)
EndIf
Next b
Next a
For b=0 To ArraySize(B()) ; B-A
For a=0 To ArraySize(A())
If A(a)=B(b)
Break
ElseIf a=ArraySize(A())
Debug B(b)
EndIf
Next a
Next b |
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
| #Objective-C | Objective-C | #import <Foundation/Foundation.h>
int main(int argc, const char * argv[])
{
@autoreleasepool {
if(argc > 1)
{
NSString *arg1 = [NSString stringWithCString:argv[1] encoding:NSUTF8StringEncoding];
// encoding shouldn't matter in this case
double kelvin = [arg1 doubleValue];
NSLog(@"K %.2f",kelvin);
NSLog(@"C %.2f\n", kelvin - 273.15);
NSLog(@"F %.2f\n", (kelvin * 1.8) - 459.67);
NSLog(@"R %.2f", kelvin * 1.8);
}
}
return 0;
} |
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)
| #Modula-3 | Modula-3 | MODULE MyTime EXPORTS Main;
IMPORT IO, FmtTime, Time;
BEGIN
IO.Put("Current time: " & FmtTime.Long(Time.Now()) & "\n");
END MyTime. |
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)
| #MUMPS | MUMPS | SYSTIME
NEW PH
SET PH=$PIECE($HOROLOG,",",2)
WRITE "The system time is ",PH\3600,":",PH\60#60,":",PH#60
KILL PH
QUIT |
http://rosettacode.org/wiki/Sum_of_elements_below_main_diagonal_of_matrix | Sum of elements below main diagonal of matrix | Task
Find and display the sum of elements that are below the main diagonal of a matrix.
The matrix should be a square matrix.
─── Matrix to be used: ───
[[1,3,7,8,10],
[2,4,16,14,4],
[3,1,9,18,11],
[12,14,17,18,20],
[7,1,3,9,5]]
| #ALGOL_68 | ALGOL 68 | BEGIN # sum the elements below the main diagonal of a matrix #
# returns the sum of the elements below the main diagonal #
# of m, m must be a square matrix #
OP LOWERSUM = ( [,]INT m )INT:
IF 1 LWB m /= 2 LWB m OR 1 UPB m /= 2 UPB m THEN
# the matrix isn't square #
print( ( "Matrix must be suare for LOWERSUM", newline ) );
stop
ELSE
# have a square matrix #
INT sum := 0;
FOR r FROM 1 LWB m + 1 TO 1 UPB m DO
FOR c FROM 1 LWB m TO r - 1 DO
sum +:= m[ r, c ]
OD
OD;
sum
FI; # LOWERSUM #
# task test case #
print( ( whole( LOWERSUM [,]INT( ( 1, 3, 7, 8, 10 )
, ( 2, 4, 16, 14, 4 )
, ( 3, 1, 9, 18, 11 )
, ( 12, 14, 17, 18, 20 )
, ( 7, 1, 3, 9, 5 )
)
, 0
)
, newline
)
)
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).
| #Python | Python | >>> setA = {"John", "Bob", "Mary", "Serena"}
>>> setB = {"Jim", "Mary", "John", "Bob"}
>>> setA ^ setB # symmetric difference of A and B
{'Jim', 'Serena'}
>>> setA - setB # elements in A that are not in B
{'Serena'}
>>> setB - setA # elements in B that are not in A
{'Jim'}
>>> setA | setB # elements in A or B (union)
{'John', 'Bob', 'Jim', 'Serena', 'Mary'}
>>> setA & setB # elements in both A and B (intersection)
{'Bob', 'John', 'Mary'} |
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
| #OCaml | OCaml |
let print_temp s t =
print_string s;
print_endline (string_of_float t);;
let kelvin_to_celsius k =
k -. 273.15;;
let kelvin_to_fahrenheit k =
(kelvin_to_celsius k)*. 9./.5. +. 32.00;;
let kelvin_to_rankine k =
(kelvin_to_celsius k)*. 9./.5. +. 491.67;;
print_endline "Enter a temperature in Kelvin please:";
let k = read_float () in
print_temp "K " k;
print_temp "C " (kelvin_to_celsius k);
print_temp "F " (kelvin_to_fahrenheit k);
print_temp "R " (kelvin_to_rankine k);;
|
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)
| #Nanoquery | Nanoquery | import Nanoquery.Util
println new(Date).getTime() |
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)
| #Neko | Neko | /**
<doc>
<h2>System time</h2>
<p>Neko uses Int32 to store system date/time values.
And lib C strftime style formatting for converting to string form</p>
</doc>
*/
var date_now = $loader.loadprim("std@date_now", 0)
var date_format = $loader.loadprim("std@date_format", 2)
var now = date_now()
$print(now, " ", date_format(now, "%T"), "\n") |
http://rosettacode.org/wiki/Sum_of_elements_below_main_diagonal_of_matrix | Sum of elements below main diagonal of matrix | Task
Find and display the sum of elements that are below the main diagonal of a matrix.
The matrix should be a square matrix.
─── Matrix to be used: ───
[[1,3,7,8,10],
[2,4,16,14,4],
[3,1,9,18,11],
[12,14,17,18,20],
[7,1,3,9,5]]
| #ALGOL_W | ALGOL W | begin % sum the elements below the main diagonal of a matrix %
% returns the sum of the elements below the main diagonal %
% of m, m must have bounds lb :: ub, lb :: ub %
integer procedure lowerSum ( integer array m ( *, * )
; integer value lb, ub
) ;
begin
integer sum;
sum := 0;
for r := lb + 1 until ub do begin
for c := lb until r - 1 do sum := sum + m( r, c )
end for_r;
sum
end lowerSum ;
begin % task test case %
integer array m ( 1 :: 5, 1 :: 5 );
integer r, c;
r := 1; c := 0; for v := 1, 3, 7, 8, 10 do begin c := c + 1; m( r, c ) := v end;
r := 2; c := 0; for v := 2, 4, 16, 14, 4 do begin c := c + 1; m( r, c ) := v end;
r := 3; c := 0; for v := 3, 1, 9, 18, 11 do begin c := c + 1; m( r, c ) := v end;
r := 4; c := 0; for v := 12, 14, 17, 18, 20 do begin c := c + 1; m( r, c ) := v end;
r := 5; c := 0; for v := 7, 1, 3, 9, 5 do begin c := c + 1; m( r, c ) := v end;
write( i_w := 1, lowerSum( m, 1, 5 ) )
end
end. |
http://rosettacode.org/wiki/Sum_of_elements_below_main_diagonal_of_matrix | Sum of elements below main diagonal of matrix | Task
Find and display the sum of elements that are below the main diagonal of a matrix.
The matrix should be a square matrix.
─── Matrix to be used: ───
[[1,3,7,8,10],
[2,4,16,14,4],
[3,1,9,18,11],
[12,14,17,18,20],
[7,1,3,9,5]]
| #APL | APL | sum_below_diagonal ← +/(∊⊢×(>/¨⍳∘⍴)) |
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).
| #Quackery | Quackery | [ $ "rosetta/bitwisesets.qky" loadfile ] now!
( i.e. using the Quackery code for sets at
http://rosettacode.org/wiki/Set#Indexed_Bitmaps )
set{ John Bob Mary Serena }set is A ( --> { )
set{ Jim Mary John Bob }set is B ( --> { )
say "A \ B is " A B difference echoset cr
say "B \ A is " B A difference echoset cr
say "(A \ B) U (B \ A) is "
A B difference B A difference union echoset cr
say "(A U B) \ (A n B) is "
A B union A B intersection difference echoset cr
say "Using built-in symmetric difference: "
A B symmdiff echoset cr |
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).
| #R | R | a <- c( "John", "Bob", "Mary", "Serena" )
b <- c( "Jim", "Mary", "John", "Bob" )
c(setdiff(b, a), setdiff(a, b))
a <- c("John", "Serena", "Bob", "Mary", "Serena")
b <- c("Jim", "Mary", "John", "Jim", "Bob")
c(setdiff(b, a), setdiff(a, b)) |
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
| #Oforth | Oforth | : kelvinToCelsius 273.15 - ;
: kelvinToFahrenheit 1.8 * 459.67 - ;
: kelvinToRankine 1.8 * ;
: testTemp(n)
n kelvinToCelsius println
n kelvinToFahrenheit println
n kelvinToRankine println ; |
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)
| #Nemerle | Nemerle | System.Console.Write(System.DateTime.Now); |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.