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/Ordered_words | Ordered words | An ordered word is a word in which the letters appear in alphabetic order.
Examples include abbey and dirt.
Task[edit]
Find and display all the ordered words in the dictionary unixdict.txt that have the longest word length.
(Examples that access the dictionary file locally assume that you have downloaded this file yourself.)
The display needs to be shown on this page.
Related tasks
Word plays
Ordered words
Palindrome detection
Semordnilap
Anagrams
Anagrams/Deranged anagrams
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Rust | Rust | const FILE: &'static str = include_str!("./unixdict.txt");
fn is_ordered(s: &str) -> bool {
let mut prev = '\x00';
for c in s.to_lowercase().chars() {
if c < prev {
return false;
}
prev = c;
}
return true;
}
fn find_longest_ordered_words(dict: Vec<&str>) -> Vec<&str> {
let mut result = Vec::new();
let mut longest_length = 0;
for s in dict.into_iter() {
if is_ordered(&s) {
let n = s.len();
if n > longest_length {
longest_length = n;
result.truncate(0);
}
if n == longest_length {
result.push(s);
}
}
}
return result;
}
fn main() {
let lines = FILE.lines().collect();
let longest_ordered = find_longest_ordered_words(lines);
for s in longest_ordered.iter() {
println!("{}", s.to_string());
}
} |
http://rosettacode.org/wiki/Palindrome_detection | Palindrome detection | A palindrome is a phrase which reads the same backward and forward.
Task[edit]
Write a function or program that checks whether a given sequence of characters (or, if you prefer, bytes)
is a palindrome.
For extra credit:
Support Unicode characters.
Write a second function (possibly as a wrapper to the first) which detects inexact palindromes, i.e. phrases that are palindromes if white-space and punctuation is ignored and case-insensitive comparison is used.
Hints
It might be useful for this task to know how to reverse a string.
This task's entries might also form the subjects of the task Test a function.
Related tasks
Word plays
Ordered words
Palindrome detection
Semordnilap
Anagrams
Anagrams/Deranged anagrams
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Smalltalk | Smalltalk | isPalindrome := [:aString |
str := (aString select: [:chr| chr isAlphaNumeric]) collect: [:chr | chr asLowercase].
str = str reversed.
].
|
http://rosettacode.org/wiki/Number_names | Number names | Task
Show how to spell out a number in English.
You can use a preexisting implementation or roll your own, but you should support inputs up to at least one million (or the maximum value of your language's default bounded integer type, if that's less).
Support for inputs other than positive integers (like zero, negative integers, and floating-point numbers) is optional.
Related task
Spelling of ordinal numbers.
| #FreeBASIC | FreeBASIC | dim shared as string*9 lows(0 to 19) = {"", "one", "two", "three", "four",_
"five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve",_
"thirteen", "fourteen", "fifteen", "sixteen", "seventeen",_
"eighteen", "nineteen"}
dim shared as string*7 tens(0 to 9) = {"", "", "twenty", "thirty", "forty",_
"fifty", "sixty", "seventy", "eighty", "ninety"}
dim shared as string*8 lev(0 to 3) = {"", "thousand", "million", "billion"}
function numname_int( byval n as integer ) as string
if n = 0 then return "zero"
if n < 0 then return "negative " + numname_int( -n )
dim as integer t = -1, lasttwo, hundreds
redim as integer triples(0 to 0)
dim as string ret, tripname
while n > 0
t += 1
triples(t) = n mod 1000
n \= 1000
wend
for i as integer = t to 0 step -1
tripname = ""
if triples(i) = 0 then continue for
lasttwo = triples(i) mod 100
hundreds = triples(i)\100
if lasttwo < 20 then
tripname = lows(lasttwo) + tripname + " "
else
tripname = tens(lasttwo\10) + "-" + lows(lasttwo mod 10) + " " + tripname
end if
if hundreds > 0 then
if lasttwo > 0 then tripname = " and " + tripname
tripname = lows(hundreds)+" hundred" + tripname
end if
if i=0 and t>0 and hundreds = 0 then tripname = " and " + tripname
tripname += lev(i)+" "
ret = ltrim(ret) + ltrim(tripname)
next i
return ltrim(rtrim(ret))
end function
function numname( n as double ) as string
if n=int(n) then return numname_int(int(n))
dim as string prefix = numname_int( int(abs(n)) )+" point "
dim as string decdig = str(abs(n)-int(abs(n))), ret
if n < 0 then prefix = "negative "+prefix
ret = prefix
for i as uinteger = 3 to len(decdig)
ret = ret + numname(val(mid(decdig,i,1)))+" "
next i
return ltrim(rtrim(ret))
end function
print numname(0)
print numname(1.0)
print numname(-1.7)
print numname(910000)
print numname(987654)
print numname(100000017)
|
http://rosettacode.org/wiki/Number_reversal_game | Number reversal game | Task
Given a jumbled list of the numbers 1 to 9 that are definitely not in
ascending order.
Show the list, and then ask the player how many digits from the
left to reverse.
Reverse those digits, then ask again, until all the digits end up in ascending order.
The score is the count of the reversals needed to attain the ascending order.
Note: Assume the player's input does not need extra validation.
Related tasks
Sorting algorithms/Pancake sort
Pancake sorting.
Topswops
| #Forth | Forth | include random.fs
variable flips
create nums 9 cells allot
: .array ( addr len -- ) 0 ?do dup @ . cell+ loop drop ;
: shuffle ( addr len -- )
2 swap do
dup i random cells +
over @ over @ swap
rot ! over !
cell+
-1 +loop drop ;
: sorted? ( addr len -- )
1- cells bounds ?do
i 2@ < if unloop false exit then
cell +loop true ;
: init
0 flips !
nums 10 1 do
i over ! cell+
loop drop
begin nums 9 shuffle nums 9 sorted? 0= until
cr nums 9 .array ;
: reverse ( addr len -- )
1- cells bounds
begin 2dup >
while over @ over @ >r over ! over r> swap !
cell+ swap 1 cells - swap
repeat 2drop ;
: flip ( n -- )
dup 2 10 within 0= if . ." must be within 2 to 9" exit then
nums swap reverse
1 flips +!
nums 9 sorted? if
cr ." Got it in " flips @ . ." tries!"
else
cr nums 9 .array
then ;
init
1 2 8 5 7 6 9 4 3 ok
7 flip
9 6 7 5 8 2 1 4 3 ok
|
http://rosettacode.org/wiki/Null_object | Null object |
Null (or nil) is the computer science concept of an undefined or unbound object.
Some languages have an explicit way to access the null object, and some don't.
Some languages distinguish the null object from undefined values, and some don't.
Task
Show how to access null in your language by checking to see if an object is equivalent to the null object.
This task is not about whether a variable is defined. The task is about "null"-like values in various languages, which may or may not be related to the defined-ness of variables in your language.
| #Logo | Logo | to test :thing
if empty? :thing [print [list or word is empty]]
end
print empty? [] ; true
print empty? "|| ; true |
http://rosettacode.org/wiki/Null_object | Null object |
Null (or nil) is the computer science concept of an undefined or unbound object.
Some languages have an explicit way to access the null object, and some don't.
Some languages distinguish the null object from undefined values, and some don't.
Task
Show how to access null in your language by checking to see if an object is equivalent to the null object.
This task is not about whether a variable is defined. The task is about "null"-like values in various languages, which may or may not be related to the defined-ness of variables in your language.
| #Lua | Lua |
isnil = (object == nil)
print(isnil)
|
http://rosettacode.org/wiki/One-dimensional_cellular_automata | One-dimensional cellular automata | Assume an array of cells with an initial distribution of live and dead cells,
and imaginary cells off the end of the array having fixed values.
Cells in the next generation of the array are calculated based on the value of the cell and its left and right nearest neighbours in the current generation.
If, in the following table, a live cell is represented by 1 and a dead cell by 0 then to generate the value of the cell at a particular index in the array of cellular values you use the following table:
000 -> 0 #
001 -> 0 #
010 -> 0 # Dies without enough neighbours
011 -> 1 # Needs one neighbour to survive
100 -> 0 #
101 -> 1 # Two neighbours giving birth
110 -> 1 # Needs one neighbour to survive
111 -> 0 # Starved to death.
| #jq | jq | # The 1-d cellular automaton:
def next:
# Conveniently, jq treats null as 0 when it comes to addition
# so there is no need to fiddle with the boundaries
. as $old
| reduce range(0; length) as $i
([];
($old[$i-1] + $old[$i+1]) as $s
| if $s == 0 then .[$i] = 0
elif $s == 1 then .[$i] = (if $old[$i] == 1 then 1 else 0 end)
else .[$i] = (if $old[$i] == 1 then 0 else 1 end)
end);
# pretty-print an array:
def pp: reduce .[] as $i (""; . + (if $i == 0 then " " else "*" end));
# continue until quiescence:
def go: recurse(. as $prev | next | if . == $prev then empty else . end) | pp;
# Example:
[0,1,1,1,0,1,1,0,1,0,1,0,1,0,1,0,0,1,0,0] | go |
http://rosettacode.org/wiki/One-dimensional_cellular_automata | One-dimensional cellular automata | Assume an array of cells with an initial distribution of live and dead cells,
and imaginary cells off the end of the array having fixed values.
Cells in the next generation of the array are calculated based on the value of the cell and its left and right nearest neighbours in the current generation.
If, in the following table, a live cell is represented by 1 and a dead cell by 0 then to generate the value of the cell at a particular index in the array of cellular values you use the following table:
000 -> 0 #
001 -> 0 #
010 -> 0 # Dies without enough neighbours
011 -> 1 # Needs one neighbour to survive
100 -> 0 #
101 -> 1 # Two neighbours giving birth
110 -> 1 # Needs one neighbour to survive
111 -> 0 # Starved to death.
| #Julia | Julia |
function next_gen(a::BitArray{1}, isperiodic=false)
b = copy(a)
if isperiodic
ncnt = prepend!(a[1:end-1], [a[end]]) + append!(a[2:end], [a[1]])
else
ncnt = prepend!(a[1:end-1], [false]) + append!(a[2:end], [false])
end
b[ncnt .== 0] = false
b[ncnt .== 2] = ~b[ncnt .== 2]
return b
end
function show_gen(a::BitArray{1})
s = join([i ? "\u2588" : " " for i in a], "")
s = "\u25ba"*s*"\u25c4"
end
hi = 70
a = bitrand(hi)
b = falses(hi)
println("A 1D Cellular Atomaton with ", hi, " cells and empty bounds.")
while any(a) && any(a .!= b)
println(" ", show_gen(a))
b = copy(a)
a = next_gen(a)
end
a = bitrand(hi)
b = falses(hi)
println()
println("A 1D Cellular Atomaton with ", hi, " cells and periodic bounds.")
while any(a) && any(a .!= b)
println(" ", show_gen(a))
b = copy(a)
a = next_gen(a, true)
end
|
http://rosettacode.org/wiki/Numerical_integration | Numerical integration | Write functions to calculate the definite integral of a function ƒ(x) using all five of the following methods:
rectangular
left
right
midpoint
trapezium
Simpson's
composite
Your functions should take in the upper and lower bounds (a and b), and the number of approximations to make in that range (n).
Assume that your example already has a function that gives values for ƒ(x) .
Simpson's method is defined by the following pseudo-code:
Pseudocode: Simpson's method, composite
procedure quad_simpson_composite(f, a, b, n)
h := (b - a) / n
sum1 := f(a + h/2)
sum2 := 0
loop on i from 1 to (n - 1)
sum1 := sum1 + f(a + h * i + h/2)
sum2 := sum2 + f(a + h * i)
answer := (h / 6) * (f(a) + f(b) + 4*sum1 + 2*sum2)
Demonstrate your function by showing the results for:
ƒ(x) = x3, where x is [0,1], with 100 approximations. The exact result is 0.25 (or 1/4)
ƒ(x) = 1/x, where x is [1,100], with 1,000 approximations. The exact result is 4.605170+ (natural log of 100)
ƒ(x) = x, where x is [0,5000], with 5,000,000 approximations. The exact result is 12,500,000
ƒ(x) = x, where x is [0,6000], with 6,000,000 approximations. The exact result is 18,000,000
See also
Active object for integrating a function of real time.
Special:PrefixIndex/Numerical integration for other integration methods.
| #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | leftRect[f_, a_Real, b_Real, N_Integer] :=
Module[{sum = 0, dx = (b - a)/N, x = a, n = N} ,
For[n = N, n > 0, n--, x += dx; sum += f[x];];
Return [ sum*dx ]]
rightRect[f_, a_Real, b_Real, N_Integer] :=
Module[{sum = 0, dx = (b - a)/N, x = a + (b - a)/N, n = N} ,
For[n = N, n > 0, n--, x += dx; sum += f[x];];
Return [ sum*dx ]]
midRect[f_, a_Real, b_Real, N_Integer] :=
Module[{sum = 0, dx = (b - a)/N, x = a + (b - a)/(2 N), n = N} ,
For[n = N, n > 0, n--, x += dx; sum += f[x];];
Return [ sum*dx ]]
trapezium[f_, a_Real, b_Real, N_Integer] :=
Module[{sum = f[a], dx = (b - a)/N, x = a, n = N} ,
For[n = 1, n < N, n++, x += dx; sum += 2 f[x];];
sum += f[b];
Return [ 0.5*sum*dx ]]
simpson[f_, a_Real, b_Real, N_Integer] :=
Module[{sum1 = f[a + (b - a)/(2 N)], sum2 = 0, dx = (b - a)/N, x = a, n = N} ,
For[n = 1, n < N, n++, sum1 += f[a + dx*n + dx/2];
sum2 += f[a + dx*n];];
Return [(dx/6)*(f[a] + f[b] + 4*sum1 + 2*sum2)]] |
http://rosettacode.org/wiki/Old_lady_swallowed_a_fly | Old lady swallowed a fly | Task
Present a program which emits the lyrics to the song I Knew an Old Lady Who Swallowed a Fly, taking advantage of the repetitive structure of the song's lyrics.
This song has multiple versions with slightly different lyrics, so all these programs might not emit identical output.
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
| #Ruby | Ruby | descriptions = {
:fly => "I don't know why S",
:spider => "That wriggled and jiggled and tickled inside her.",
:bird => "Quite absurd T",
:cat => "Fancy that, S",
:dog => "What a hog, S",
:goat => "She opened her throat T",
:cow => "I don't know how S",
:horse => "She's dead, of course.",
}
animals = descriptions.keys
animals.each_with_index do |animal, idx|
puts "There was an old lady who swallowed a #{animal}."
d = descriptions[animal]
case d[-1]
when "S" then d[-1] = "she swallowed a #{animal}."
when "T" then d[-1] = "to swallow a #{animal}."
end
puts d
break if animal == :horse
idx.downto(1) do |i|
puts "She swallowed the #{animals[i]} to catch the #{animals[i-1]}."
case animals[i-1]
when :spider, :fly then puts descriptions[animals[i-1]]
end
end
print "Perhaps she'll die.\n\n"
end |
http://rosettacode.org/wiki/Ordered_words | Ordered words | An ordered word is a word in which the letters appear in alphabetic order.
Examples include abbey and dirt.
Task[edit]
Find and display all the ordered words in the dictionary unixdict.txt that have the longest word length.
(Examples that access the dictionary file locally assume that you have downloaded this file yourself.)
The display needs to be shown on this page.
Related tasks
Word plays
Ordered words
Palindrome detection
Semordnilap
Anagrams
Anagrams/Deranged anagrams
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Scala | Scala | val wordsAll = scala.io.Source.fromURL("http://www.puzzlers.org/pub/wordlists/unixdict.txt").getLines.toSeq
/**
* Given a sequence of words return a sub-sequence of the
* words that have characters in sorted order.
*/
def orderedWords( words:Seq[String] ) : Seq[(String)] = {
def isOrdered( s:String ) : Boolean =
(s.foldLeft( (true,'@') ){
case ((false,_),_) => return false
case ((true,prev),c) => ((prev <= c),c)
})._1
wordsAll.filter( isOrdered(_) ).toSeq
}
val ww = orderedWords( wordsAll ).sortBy( -_.length )
println( ww.takeWhile( _.length == ww.head.length ).mkString("\n") ) |
http://rosettacode.org/wiki/Palindrome_detection | Palindrome detection | A palindrome is a phrase which reads the same backward and forward.
Task[edit]
Write a function or program that checks whether a given sequence of characters (or, if you prefer, bytes)
is a palindrome.
For extra credit:
Support Unicode characters.
Write a second function (possibly as a wrapper to the first) which detects inexact palindromes, i.e. phrases that are palindromes if white-space and punctuation is ignored and case-insensitive comparison is used.
Hints
It might be useful for this task to know how to reverse a string.
This task's entries might also form the subjects of the task Test a function.
Related tasks
Word plays
Ordered words
Palindrome detection
Semordnilap
Anagrams
Anagrams/Deranged anagrams
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
| #SNOBOL4 | SNOBOL4 | define('pal(str)') :(pal_end)
pal str notany(&ucase &lcase) = :s(pal)
str = replace(str,&ucase,&lcase)
leq(str,reverse(str)) :s(return)f(freturn)
pal_end
define('palchk(str)tf') :(palchk_end)
palchk output = str;
tf = 'False'; tf = pal(str) 'True'
output = 'Palindrome: ' tf :(return)
palchk_end
* # Test and display
palchk('Able was I ere I saw Elba')
palchk('In girum imus nocte et consumimur igni')
palchk('The quick brown fox jumped over the lazy dogs')
end |
http://rosettacode.org/wiki/Number_names | Number names | Task
Show how to spell out a number in English.
You can use a preexisting implementation or roll your own, but you should support inputs up to at least one million (or the maximum value of your language's default bounded integer type, if that's less).
Support for inputs other than positive integers (like zero, negative integers, and floating-point numbers) is optional.
Related task
Spelling of ordinal numbers.
| #Fortran | Fortran | program spell
implicit none
integer :: e
integer :: i
integer :: m
integer :: n
character (9), dimension (19), parameter :: small = &
& (/'one ', 'two ', 'three ', 'four ', &
& 'five ', 'six ', 'seven ', 'eight ', &
& 'nine ', 'ten ', 'eleven ', 'twelve ', &
& 'thirteen ', 'fourteen ', 'fifteen ', 'sixteen ', &
& 'seventeen', 'eighteen ', 'nineteen '/)
character (7), dimension (2 : 9), parameter :: tens = &
& (/'twenty ', 'thirty ', 'forty ', 'fifty ', 'sixty ', &
& 'seventy', 'eighty ', 'ninety '/)
character (8), dimension (3), parameter :: big = &
& (/'thousand', 'million ', 'billion '/)
character (256) :: r
do
read (*, *, iostat = i) n
if (i /= 0) then
exit
end if
if (n == 0) then
r = 'zero'
else
r = ''
m = abs (n)
e = 0
do
if (m == 0) then
exit
end if
if (modulo (m, 1000) > 0) then
if (e > 0) then
r = trim (big (e)) // ' ' // r
end if
if (modulo (m, 100) > 0) then
if (modulo (m, 100) < 20) then
r = trim (small (modulo (m, 100))) // ' ' // r
else
if (modulo (m, 10) > 0) then
r = trim (small (modulo (m, 10))) // ' ' // r
r = trim (tens (modulo (m, 100) / 10)) // '-' // r
else
r = trim (tens (modulo (m, 100) / 10)) // ' ' // r
end if
end if
end if
if (modulo (m, 1000) / 100 > 0) then
r = 'hundred' // ' ' // r
r = trim (small (modulo (m, 1000) / 100)) // ' ' // r
end if
end if
m = m / 1000
e = e + 1
end do
if (n < 0) then
r = 'negative' // ' ' // r
end if
end if
write (*, '(a)') trim (r)
end do
end program spell |
http://rosettacode.org/wiki/Number_reversal_game | Number reversal game | Task
Given a jumbled list of the numbers 1 to 9 that are definitely not in
ascending order.
Show the list, and then ask the player how many digits from the
left to reverse.
Reverse those digits, then ask again, until all the digits end up in ascending order.
The score is the count of the reversals needed to attain the ascending order.
Note: Assume the player's input does not need extra validation.
Related tasks
Sorting algorithms/Pancake sort
Pancake sorting.
Topswops
| #Fortran | Fortran | program Reversal_game
implicit none
integer :: list(9) = (/ 1, 2, 3, 4, 5, 6, 7, 8, 9 /)
integer :: pos, attempts = 0
call random_seed
do while (sorted(list))
call Shuffle(list)
end do
write(*, "(9i5)") list
write(*,*)
do while (.not. Sorted(list))
write(*, "(a)", advance="no") "How many numbers from the left do you want to reverse? : "
read*, pos
attempts = attempts + 1
list(1:pos) = list(pos:1:-1)
write(*, "(9i5)") list
write(*,*)
end do
write(*,*)
write(*, "(a,i0,a)") "Congratulations! Solved in ", attempts, " attempts"
contains
subroutine Shuffle(a)
integer, intent(inout) :: a(:)
integer :: i, randpos, temp
real :: r
do i = size(a), 2, -1
call random_number(r)
randpos = int(r * i) + 1
temp = a(randpos)
a(randpos) = a(i)
a(i) = temp
end do
end subroutine
function Sorted(a)
logical :: Sorted
integer, intent(in) :: a(:)
integer :: i
do i = 1, size(a)-1
if(list(i+1) /= list(i)+1) then
Sorted = .false.
return
end if
end do
Sorted = .true.
end function
end program |
http://rosettacode.org/wiki/Null_object | Null object |
Null (or nil) is the computer science concept of an undefined or unbound object.
Some languages have an explicit way to access the null object, and some don't.
Some languages distinguish the null object from undefined values, and some don't.
Task
Show how to access null in your language by checking to see if an object is equivalent to the null object.
This task is not about whether a variable is defined. The task is about "null"-like values in various languages, which may or may not be related to the defined-ness of variables in your language.
| #M2000_Interpreter | M2000 Interpreter |
Module CheckWord {
Declare Alfa "WORD.APPLICATION"
Declare Alfa Nothing
Print Type$(Alfa)="Nothing"
Try ok {
Declare Alfa "WORD.APPLICATION"
\\ we can't declare again Alfa
}
If Not Ok Then Print Error$ ' return Bad Object declaration
}
CheckWord
|
http://rosettacode.org/wiki/Null_object | Null object |
Null (or nil) is the computer science concept of an undefined or unbound object.
Some languages have an explicit way to access the null object, and some don't.
Some languages distinguish the null object from undefined values, and some don't.
Task
Show how to access null in your language by checking to see if an object is equivalent to the null object.
This task is not about whether a variable is defined. The task is about "null"-like values in various languages, which may or may not be related to the defined-ness of variables in your language.
| #Maple | Maple | a := NULL;
a :=
is (NULL = ());
true
if a = NULL then
print (NULL);
end if;
|
http://rosettacode.org/wiki/Null_object | Null object |
Null (or nil) is the computer science concept of an undefined or unbound object.
Some languages have an explicit way to access the null object, and some don't.
Some languages distinguish the null object from undefined values, and some don't.
Task
Show how to access null in your language by checking to see if an object is equivalent to the null object.
This task is not about whether a variable is defined. The task is about "null"-like values in various languages, which may or may not be related to the defined-ness of variables in your language.
| #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | x=Null; |
http://rosettacode.org/wiki/One-dimensional_cellular_automata | One-dimensional cellular automata | Assume an array of cells with an initial distribution of live and dead cells,
and imaginary cells off the end of the array having fixed values.
Cells in the next generation of the array are calculated based on the value of the cell and its left and right nearest neighbours in the current generation.
If, in the following table, a live cell is represented by 1 and a dead cell by 0 then to generate the value of the cell at a particular index in the array of cellular values you use the following table:
000 -> 0 #
001 -> 0 #
010 -> 0 # Dies without enough neighbours
011 -> 1 # Needs one neighbour to survive
100 -> 0 #
101 -> 1 # Two neighbours giving birth
110 -> 1 # Needs one neighbour to survive
111 -> 0 # Starved to death.
| #K | K | f:{2=+/(0,x,0)@(!#x)+/:!3} |
http://rosettacode.org/wiki/Numerical_integration | Numerical integration | Write functions to calculate the definite integral of a function ƒ(x) using all five of the following methods:
rectangular
left
right
midpoint
trapezium
Simpson's
composite
Your functions should take in the upper and lower bounds (a and b), and the number of approximations to make in that range (n).
Assume that your example already has a function that gives values for ƒ(x) .
Simpson's method is defined by the following pseudo-code:
Pseudocode: Simpson's method, composite
procedure quad_simpson_composite(f, a, b, n)
h := (b - a) / n
sum1 := f(a + h/2)
sum2 := 0
loop on i from 1 to (n - 1)
sum1 := sum1 + f(a + h * i + h/2)
sum2 := sum2 + f(a + h * i)
answer := (h / 6) * (f(a) + f(b) + 4*sum1 + 2*sum2)
Demonstrate your function by showing the results for:
ƒ(x) = x3, where x is [0,1], with 100 approximations. The exact result is 0.25 (or 1/4)
ƒ(x) = 1/x, where x is [1,100], with 1,000 approximations. The exact result is 4.605170+ (natural log of 100)
ƒ(x) = x, where x is [0,5000], with 5,000,000 approximations. The exact result is 12,500,000
ƒ(x) = x, where x is [0,6000], with 6,000,000 approximations. The exact result is 18,000,000
See also
Active object for integrating a function of real time.
Special:PrefixIndex/Numerical integration for other integration methods.
| #MATLAB_.2F_Octave | MATLAB / Octave | function integral = leftRectIntegration(f,a,b,n)
format long;
width = (b-a)/n; %calculate the width of each devision
x = linspace(a,b,n); %define x-axis
integral = width * sum( f(x(1:n-1)) );
end |
http://rosettacode.org/wiki/Old_lady_swallowed_a_fly | Old lady swallowed a fly | Task
Present a program which emits the lyrics to the song I Knew an Old Lady Who Swallowed a Fly, taking advantage of the repetitive structure of the song's lyrics.
This song has multiple versions with slightly different lyrics, so all these programs might not emit identical output.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Rust | Rust | enum Action {Once, Every, Die}
use Action::*;
fn main() {
let animals = [ ("horse" , Die , "She's dead, of course!")
, ("donkey", Once , "It was rather wonky. To swallow a donkey.")
, ("cow" , Once , "I don't know how. To swallow a cow.")
, ("goat" , Once , "She just opened her throat. To swallow a goat.")
, ("pig" , Once , "Her mouth was so big. To swallow a pig.")
, ("dog" , Once , "What a hog. To swallow a dog.")
, ("cat" , Once , "Fancy that. To swallow a cat.")
, ("bird" , Once , "Quite absurd. To swallow a bird.")
, ("spider", Once , "That wriggled and jiggled and tickled inside her.")
, ("fly" , Every, "I don't know why she swallowed the fly.")
];
for (i, a) in animals.iter().enumerate().rev() {
println!("There was an old lady who swallowed a {}\n{}", a.0, a.2);
if let Die = a.1 {break}
for (swallowed, to_catch) in animals[i..].iter().zip(&animals[i+1..]) {
println!("She swallowed the {} to catch the {}.", swallowed.0, to_catch.0);
if let Every = to_catch.1 {
println!("{}", to_catch.2);
}
}
println!("Perhaps she'll die.\n");
}
} |
http://rosettacode.org/wiki/Old_lady_swallowed_a_fly | Old lady swallowed a fly | Task
Present a program which emits the lyrics to the song I Knew an Old Lady Who Swallowed a Fly, taking advantage of the repetitive structure of the song's lyrics.
This song has multiple versions with slightly different lyrics, so all these programs might not emit identical output.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Scala | Scala | case class Verse(animal: String, remark: String, die: Boolean = false, always: Boolean = false)
val verses = List(
Verse("horse", "She’s dead, of course!", die = true),
Verse("donkey", "It was rather wonky. To swallow a donkey."),
Verse("cow", "I don’t know how. To swallow a cow."),
Verse("goat", "She just opened her throat. To swallow a goat."),
Verse("pig", "Her mouth was so big. To swallow a pig."),
Verse("dog", "What a hog. To swallow a dog."),
Verse("cat", "Fancy that. To swallow a cat."),
Verse("bird", "Quite absurd. To swallow a bird."),
Verse("spider", "That wriggled and jiggled and tickled inside her."),
Verse("fly", "I don’t know why she swallowed the fly.", always = true)
)
for (i <- 1 to verses.size; verse = verses takeRight i; starting = verse.head) {
println(s"There was an old lady who swallowed a ${starting.animal},")
println(starting.remark)
if (!starting.die) {
for (List(it, next) <- verse.sliding(2,1)) {
println(s"She swallowed the ${it.animal} to catch the ${next.animal},")
if (next.always) println(next.remark)
}
println("Perhaps she’ll die!")
println
}
} |
http://rosettacode.org/wiki/Ordered_words | Ordered words | An ordered word is a word in which the letters appear in alphabetic order.
Examples include abbey and dirt.
Task[edit]
Find and display all the ordered words in the dictionary unixdict.txt that have the longest word length.
(Examples that access the dictionary file locally assume that you have downloaded this file yourself.)
The display needs to be shown on this page.
Related tasks
Word plays
Ordered words
Palindrome detection
Semordnilap
Anagrams
Anagrams/Deranged anagrams
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Scheme | Scheme |
(define sorted-words
(let ((port (open-input-file "unixdict.txt")))
(let loop ((char (read-char port)) (word '()) (result '(())))
(cond
((eof-object? char)
(reverse (map (lambda (word) (apply string word)) result)))
((eq? #\newline char)
(loop (read-char port) '()
(let ((best-length (length (car result))) (word-length (length word)))
(cond
((or (< word-length best-length) (not (apply char>=? word))) result)
((> word-length best-length) (list (reverse word)))
(else (cons (reverse word) result))))))
(else (loop (read-char port) (cons char word) result))))))
(map (lambda (x)
(begin
(display x)
(newline)))
sorted-words)
|
http://rosettacode.org/wiki/Palindrome_detection | Palindrome detection | A palindrome is a phrase which reads the same backward and forward.
Task[edit]
Write a function or program that checks whether a given sequence of characters (or, if you prefer, bytes)
is a palindrome.
For extra credit:
Support Unicode characters.
Write a second function (possibly as a wrapper to the first) which detects inexact palindromes, i.e. phrases that are palindromes if white-space and punctuation is ignored and case-insensitive comparison is used.
Hints
It might be useful for this task to know how to reverse a string.
This task's entries might also form the subjects of the task Test a function.
Related tasks
Word plays
Ordered words
Palindrome detection
Semordnilap
Anagrams
Anagrams/Deranged anagrams
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #SQL | SQL | SET @txt = REPLACE('In girum imus nocte et consumimur igni', ' ', '');
SELECT REVERSE(@txt) = @txt; |
http://rosettacode.org/wiki/Number_names | Number names | Task
Show how to spell out a number in English.
You can use a preexisting implementation or roll your own, but you should support inputs up to at least one million (or the maximum value of your language's default bounded integer type, if that's less).
Support for inputs other than positive integers (like zero, negative integers, and floating-point numbers) is optional.
Related task
Spelling of ordinal numbers.
| #Go | Go | package main
import "fmt"
func main() {
for _, n := range []int64{12, 1048576, 9e18, -2, 0} {
fmt.Println(say(n))
}
}
var small = [...]string{"zero", "one", "two", "three", "four", "five", "six",
"seven", "eight", "nine", "ten", "eleven", "twelve", "thirteen",
"fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen"}
var tens = [...]string{"", "", "twenty", "thirty", "forty",
"fifty", "sixty", "seventy", "eighty", "ninety"}
var illions = [...]string{"", " thousand", " million", " billion",
" trillion", " quadrillion", " quintillion"}
func say(n int64) string {
var t string
if n < 0 {
t = "negative "
// Note, for math.MinInt64 this leaves n negative.
n = -n
}
switch {
case n < 20:
t += small[n]
case n < 100:
t += tens[n/10]
s := n % 10
if s > 0 {
t += "-" + small[s]
}
case n < 1000:
t += small[n/100] + " hundred"
s := n % 100
if s > 0 {
t += " " + say(s)
}
default:
// work right-to-left
sx := ""
for i := 0; n > 0; i++ {
p := n % 1000
n /= 1000
if p > 0 {
ix := say(p) + illions[i]
if sx != "" {
ix += " " + sx
}
sx = ix
}
}
t += sx
}
return t
} |
http://rosettacode.org/wiki/Number_reversal_game | Number reversal game | Task
Given a jumbled list of the numbers 1 to 9 that are definitely not in
ascending order.
Show the list, and then ask the player how many digits from the
left to reverse.
Reverse those digits, then ask again, until all the digits end up in ascending order.
The score is the count of the reversals needed to attain the ascending order.
Note: Assume the player's input does not need extra validation.
Related tasks
Sorting algorithms/Pancake sort
Pancake sorting.
Topswops
| #FreeBASIC | FreeBASIC | package main
import (
"fmt"
"math/rand"
"sort"
"time"
)
func main() {
rand.Seed(time.Now().UnixNano())
var k []int
for {
k = rand.Perm(9)
for i, r := range k {
if r == 0 {
k[i] = 9
}
}
if !sort.IntsAreSorted(k) {
break
}
}
fmt.Println("Sort digits by reversing a number of digits on the left.")
var n, score int
for {
fmt.Print("Digits: ", k, ". How many to reverse? ")
i, _ := fmt.Scanln(&n)
score++
if i == 0 || n < 2 || n > 9 {
fmt.Println("\n(Enter a number from 2 to 9)")
continue
}
for l, r := 0, n-1; l < r; l, r = l+1, r-1 {
k[l], k[r] = k[r], k[l]
}
if sort.IntsAreSorted(k) {
fmt.Print("Digits: ", k, ".\n")
fmt.Print("Your score: ", score, ". Good job.\n")
return
}
}
} |
http://rosettacode.org/wiki/Null_object | Null object |
Null (or nil) is the computer science concept of an undefined or unbound object.
Some languages have an explicit way to access the null object, and some don't.
Some languages distinguish the null object from undefined values, and some don't.
Task
Show how to access null in your language by checking to see if an object is equivalent to the null object.
This task is not about whether a variable is defined. The task is about "null"-like values in various languages, which may or may not be related to the defined-ness of variables in your language.
| #MATLAB_.2F_Octave | MATLAB / Octave | a = []; b='';
isempty(a)
isempty(b)
if (a)
1,
else,
0
end; |
http://rosettacode.org/wiki/Null_object | Null object |
Null (or nil) is the computer science concept of an undefined or unbound object.
Some languages have an explicit way to access the null object, and some don't.
Some languages distinguish the null object from undefined values, and some don't.
Task
Show how to access null in your language by checking to see if an object is equivalent to the null object.
This task is not about whether a variable is defined. The task is about "null"-like values in various languages, which may or may not be related to the defined-ness of variables in your language.
| #Maxima | Maxima | if obj == undefined then print "Obj is undefined" |
http://rosettacode.org/wiki/One-dimensional_cellular_automata | One-dimensional cellular automata | Assume an array of cells with an initial distribution of live and dead cells,
and imaginary cells off the end of the array having fixed values.
Cells in the next generation of the array are calculated based on the value of the cell and its left and right nearest neighbours in the current generation.
If, in the following table, a live cell is represented by 1 and a dead cell by 0 then to generate the value of the cell at a particular index in the array of cellular values you use the following table:
000 -> 0 #
001 -> 0 #
010 -> 0 # Dies without enough neighbours
011 -> 1 # Needs one neighbour to survive
100 -> 0 #
101 -> 1 # Two neighbours giving birth
110 -> 1 # Needs one neighbour to survive
111 -> 0 # Starved to death.
| #Kotlin | Kotlin | // version 1.1.4-3
val trans = "___#_##_"
fun v(cell: StringBuilder, i: Int) = if (cell[i] != '_') 1 else 0
fun evolve(cell: StringBuilder, backup: StringBuilder): Boolean {
val len = cell.length - 2
var diff = 0
for (i in 1 until len) {
/* use left, self, right as binary number bits for table index */
backup[i] = trans[v(cell, i - 1) * 4 + v(cell, i) * 2 + v(cell, i + 1)]
diff += if (backup[i] != cell[i]) 1 else 0
}
cell.setLength(0)
cell.append(backup)
return diff != 0
}
fun main(args: Array<String>) {
val c = StringBuilder("_###_##_#_#_#_#__#__")
val b = StringBuilder("____________________")
do {
println(c.substring(1))
}
while (evolve(c,b))
} |
http://rosettacode.org/wiki/Numerical_integration | Numerical integration | Write functions to calculate the definite integral of a function ƒ(x) using all five of the following methods:
rectangular
left
right
midpoint
trapezium
Simpson's
composite
Your functions should take in the upper and lower bounds (a and b), and the number of approximations to make in that range (n).
Assume that your example already has a function that gives values for ƒ(x) .
Simpson's method is defined by the following pseudo-code:
Pseudocode: Simpson's method, composite
procedure quad_simpson_composite(f, a, b, n)
h := (b - a) / n
sum1 := f(a + h/2)
sum2 := 0
loop on i from 1 to (n - 1)
sum1 := sum1 + f(a + h * i + h/2)
sum2 := sum2 + f(a + h * i)
answer := (h / 6) * (f(a) + f(b) + 4*sum1 + 2*sum2)
Demonstrate your function by showing the results for:
ƒ(x) = x3, where x is [0,1], with 100 approximations. The exact result is 0.25 (or 1/4)
ƒ(x) = 1/x, where x is [1,100], with 1,000 approximations. The exact result is 4.605170+ (natural log of 100)
ƒ(x) = x, where x is [0,5000], with 5,000,000 approximations. The exact result is 12,500,000
ƒ(x) = x, where x is [0,6000], with 6,000,000 approximations. The exact result is 18,000,000
See also
Active object for integrating a function of real time.
Special:PrefixIndex/Numerical integration for other integration methods.
| #Maxima | Maxima | right_rect(e, x, a, b, n) := block([h: (b - a) / n, s: 0],
for i from 1 thru n do s: s + subst(x = a + i * h, e),
s * h)$
left_rect(e, x, a, b, n) := block([h: (b - a) / n, s: 0],
for i from 1 thru n do s: s + subst(x = a + (i - 1) * h, e),
s * h)$
mid_rect(e, x, a, b, n) := block([h: (b - a) / n, s: 0],
for i from 1 thru n do s: s + subst(x = a + (i - 1/2) * h, e),
s * h)$
trapezium(e, x, a, b, n) := block([h: (b - a) / n, s: 0],
for i from 1 thru n - 1 do s: s + subst(x = a + i * h, e),
((subst(x = a, e) + subst(x = b, e)) / 2 + s) * h)$
simpson(e, x, a, b, n) := block([h: (b - a) / n, s: 0],
for i from 1 thru n do
s: s + subst(x = a + i * h, e) + 2 * subst(x = a + (i - 1/2) * h, e),
(subst(x = a, e) - subst(x = b, e) + 2 * s) * h / 6)$
/* some tests */
simpson(log(x), x, 1, 2, 20), bfloat;
2 * log(2) - 1 - %, bfloat;
trapezium(1/x, x, 1, 100, 10000) - log(100), bfloat; |
http://rosettacode.org/wiki/Old_lady_swallowed_a_fly | Old lady swallowed a fly | Task
Present a program which emits the lyrics to the song I Knew an Old Lady Who Swallowed a Fly, taking advantage of the repetitive structure of the song's lyrics.
This song has multiple versions with slightly different lyrics, so all these programs might not emit identical output.
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
| #Scratch | Scratch | $ include "seed7_05.s7i";
const array array string: verses is [] (
[] ("fly", "I don't know why she swallowed the fly."),
[] ("spider", "That wriggled and jiggled and tickled inside her."),
[] ("bird", "Quite absurd. To swallow a bird."),
[] ("cat", "Fancy that. To swallow a cat."),
[] ("dog", "What a hog. To swallow a dog."),
[] ("pig", "Her mouth was so big. To swallow a pig."),
[] ("goat", "She just opened her throat. To swallow a goat."),
[] ("cow", "I don't know how. To swallow a cow."),
[] ("donkey", "It was rather wonky. To swallow a donkey."),
[] ("horse", "She's dead, of course!"));
const proc: main is func
local
var integer: verseNumber is 0;
var integer: animal is 0;
begin
for key verseNumber range verses do
writeln("There was an old lady who swallowed a " <& verses[verseNumber][1] <& ",");
writeln(verses[verseNumber][2]);
if verseNumber <> length(verses) then
for animal range verseNumber downto 2 do
writeln("She swallowed the " <& verses[animal][1] <& " to catch the " <& verses[pred(animal)][1] <& ",");
end for;
if verseNumber <> 1 then
writeln(verses[1][2]);
end if;
writeln("Perhaps she'll die!");
writeln;
end if;
end for;
end func; |
http://rosettacode.org/wiki/Old_lady_swallowed_a_fly | Old lady swallowed a fly | Task
Present a program which emits the lyrics to the song I Knew an Old Lady Who Swallowed a Fly, taking advantage of the repetitive structure of the song's lyrics.
This song has multiple versions with slightly different lyrics, so all these programs might not emit identical output.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Seed7 | Seed7 | $ include "seed7_05.s7i";
const array array string: verses is [] (
[] ("fly", "I don't know why she swallowed the fly."),
[] ("spider", "That wriggled and jiggled and tickled inside her."),
[] ("bird", "Quite absurd. To swallow a bird."),
[] ("cat", "Fancy that. To swallow a cat."),
[] ("dog", "What a hog. To swallow a dog."),
[] ("pig", "Her mouth was so big. To swallow a pig."),
[] ("goat", "She just opened her throat. To swallow a goat."),
[] ("cow", "I don't know how. To swallow a cow."),
[] ("donkey", "It was rather wonky. To swallow a donkey."),
[] ("horse", "She's dead, of course!"));
const proc: main is func
local
var integer: verseNumber is 0;
var integer: animal is 0;
begin
for key verseNumber range verses do
writeln("There was an old lady who swallowed a " <& verses[verseNumber][1] <& ",");
writeln(verses[verseNumber][2]);
if verseNumber <> length(verses) then
for animal range verseNumber downto 2 do
writeln("She swallowed the " <& verses[animal][1] <& " to catch the " <& verses[pred(animal)][1] <& ",");
end for;
if verseNumber <> 1 then
writeln(verses[1][2]);
end if;
writeln("Perhaps she'll die!");
writeln;
end if;
end for;
end func; |
http://rosettacode.org/wiki/Ordered_words | Ordered words | An ordered word is a word in which the letters appear in alphabetic order.
Examples include abbey and dirt.
Task[edit]
Find and display all the ordered words in the dictionary unixdict.txt that have the longest word length.
(Examples that access the dictionary file locally assume that you have downloaded this file yourself.)
The display needs to be shown on this page.
Related tasks
Word plays
Ordered words
Palindrome detection
Semordnilap
Anagrams
Anagrams/Deranged anagrams
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Seed7 | Seed7 | $ include "seed7_05.s7i";
const func boolean: isOrdered (in string: word) is func
result
var boolean: ordered is TRUE;
local
var integer: index is 0;
begin
for index range 1 to pred(length(word)) do
if word[index] > word[succ(index)] then
ordered := FALSE;
end if;
end for;
end func;
const proc: write (in array string: wordList) is func
local
var string: word is "";
begin
for word range wordList do
writeln(word);
end for;
end func;
const proc: main is func
local
var file: dictionary is STD_NULL;
var string: word is "";
var integer: length is 0;
var array string: wordList is 0 times "";
begin
dictionary := open("unixdict.txt", "r");
if dictionary <> STD_NULL then
readln(dictionary, word);
while not eof(dictionary) do
if isOrdered(lower(word)) then
if length(word) > length then
length := length(word);
wordList := [] (word);
elsif length(word) = length then
wordList &:= word;
end if;
end if;
readln(dictionary, word);
end while;
close(dictionary);
end if;
write(wordList);
end func; |
http://rosettacode.org/wiki/Ordered_words | Ordered words | An ordered word is a word in which the letters appear in alphabetic order.
Examples include abbey and dirt.
Task[edit]
Find and display all the ordered words in the dictionary unixdict.txt that have the longest word length.
(Examples that access the dictionary file locally assume that you have downloaded this file yourself.)
The display needs to be shown on this page.
Related tasks
Word plays
Ordered words
Palindrome detection
Semordnilap
Anagrams
Anagrams/Deranged anagrams
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Sidef | Sidef | var words = [[]]
var file = %f'unixdict.txt'
file.open_r(\var fh, \var err) ->
|| die "Can't open file #{file}: $#{err}"
fh.each { |line|
line.trim!
if (line == line.sort) {
words[line.length] := [] << line
}
}
say words[-1].join(' ') |
http://rosettacode.org/wiki/Palindrome_detection | Palindrome detection | A palindrome is a phrase which reads the same backward and forward.
Task[edit]
Write a function or program that checks whether a given sequence of characters (or, if you prefer, bytes)
is a palindrome.
For extra credit:
Support Unicode characters.
Write a second function (possibly as a wrapper to the first) which detects inexact palindromes, i.e. phrases that are palindromes if white-space and punctuation is ignored and case-insensitive comparison is used.
Hints
It might be useful for this task to know how to reverse a string.
This task's entries might also form the subjects of the task Test a function.
Related tasks
Word plays
Ordered words
Palindrome detection
Semordnilap
Anagrams
Anagrams/Deranged anagrams
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Swift | Swift | import Foundation
// Allow for easy character checking
extension String {
subscript (i: Int) -> String {
return String(Array(self)[i])
}
}
func isPalindrome(str:String) -> Bool {
if (count(str) == 0 || count(str) == 1) {
return true
}
let removeRange = Range<String.Index>(start: advance(str.startIndex, 1), end: advance(str.endIndex, -1))
if (str[0] == str[count(str) - 1]) {
return isPalindrome(str.substringWithRange(removeRange))
}
return false
} |
http://rosettacode.org/wiki/Number_names | Number names | Task
Show how to spell out a number in English.
You can use a preexisting implementation or roll your own, but you should support inputs up to at least one million (or the maximum value of your language's default bounded integer type, if that's less).
Support for inputs other than positive integers (like zero, negative integers, and floating-point numbers) is optional.
Related task
Spelling of ordinal numbers.
| #Groovy | Groovy | def divMod(BigInteger number, BigInteger divisor) {
def qr = number.divideAndRemainder(divisor)
[div:qr[0], remainder:qr[1]]
}
def toText(value) {
value = value as BigInteger
def units = ['zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten',
'eleven', 'twelve', 'thirteen', 'fourteen', 'fifteen', 'sixteen', 'seventeen', 'eighteen', 'nineteen']
def tens = ['', '', 'twenty', 'thirty', 'forty', 'fifty', 'sixty', 'seventy', 'eighty', 'ninety']
def big = ['', 'thousand'] + ['m', 'b', 'tr', 'quadr', 'quint', 'sext', 'sept', 'oct', 'non', 'dec'].collect { "${it}illion"}
if (value < 0) {
"negative ${toText(-value)}"
} else if (value < 20) {
units[value]
} else if (value < 100) {
divMod(value, 10).with { "${tens[div]} ${units[remainder]}".replace(' zero', '') }
} else if (value < 1000) {
divMod(value, 100).with { "${toText(div)} hundred and ${toText(remainder)}".replace(' and zero', '') }
} else {
def chunks = []
while (value != 0) {
divMod(value, 1000).with {
chunks << remainder
value = div
}
}
if (chunks.size() > big.size()) {
throw new IllegalArgumentException("Number overflow")
}
def text = []
(0..<chunks.size()).each { index ->
if (chunks[index] > 0) {
text << "${toText(chunks[index])}${index == 0 ? '' : ' ' + big[index]}"
if (index == 0 && chunks[index] < 100) {
text << "and"
}
}
}
text.reverse().join(', ').replace(', and,', ' and')
}
}
// Add this method to all Numbers
Number.metaClass.toText = { toText(delegate) }
println toText(29)
println 40.toText()
println toText(401)
println 9003.toText()
println toText(8011673)
println 8000100.toText()
println 4629436.toText()
948623487512387455323784623842314234.toText().split(',').each { println it.trim() }
def verifyToText(expected, value) {
println "Checking '$expected' == $value"
def actual = value.toText()
assert expected == actual
}
verifyToText 'nineteen', 19
verifyToText 'one thousand, two hundred and thirty four', 1234
verifyToText 'twenty three million, four hundred and fifty nine thousand, six hundred and twelve', 23459612
verifyToText 'one thousand, nine hundred and ninety nine', 1999
verifyToText 'negative six hundred and one', -601
verifyToText 'twelve billion and nineteen', 12000000019
verifyToText 'negative one billion, two hundred and thirty four million, five hundred and sixty seven thousand, eight hundred and ninety', -1234567890
verifyToText 'one hundred and one', 101
verifyToText 'one thousand and one', 1001
verifyToText 'one million, one hundred and one', 1000101
verifyToText 'one million and forty five', 1000045
verifyToText 'one million and fifteen', 1000015
verifyToText 'one billion, forty five thousand and one', 1000045001 |
http://rosettacode.org/wiki/Number_reversal_game | Number reversal game | Task
Given a jumbled list of the numbers 1 to 9 that are definitely not in
ascending order.
Show the list, and then ask the player how many digits from the
left to reverse.
Reverse those digits, then ask again, until all the digits end up in ascending order.
The score is the count of the reversals needed to attain the ascending order.
Note: Assume the player's input does not need extra validation.
Related tasks
Sorting algorithms/Pancake sort
Pancake sorting.
Topswops
| #Go | Go | package main
import (
"fmt"
"math/rand"
"sort"
"time"
)
func main() {
rand.Seed(time.Now().UnixNano())
var k []int
for {
k = rand.Perm(9)
for i, r := range k {
if r == 0 {
k[i] = 9
}
}
if !sort.IntsAreSorted(k) {
break
}
}
fmt.Println("Sort digits by reversing a number of digits on the left.")
var n, score int
for {
fmt.Print("Digits: ", k, ". How many to reverse? ")
i, _ := fmt.Scanln(&n)
score++
if i == 0 || n < 2 || n > 9 {
fmt.Println("\n(Enter a number from 2 to 9)")
continue
}
for l, r := 0, n-1; l < r; l, r = l+1, r-1 {
k[l], k[r] = k[r], k[l]
}
if sort.IntsAreSorted(k) {
fmt.Print("Digits: ", k, ".\n")
fmt.Print("Your score: ", score, ". Good job.\n")
return
}
}
} |
http://rosettacode.org/wiki/Null_object | Null object |
Null (or nil) is the computer science concept of an undefined or unbound object.
Some languages have an explicit way to access the null object, and some don't.
Some languages distinguish the null object from undefined values, and some don't.
Task
Show how to access null in your language by checking to see if an object is equivalent to the null object.
This task is not about whether a variable is defined. The task is about "null"-like values in various languages, which may or may not be related to the defined-ness of variables in your language.
| #MAXScript | MAXScript | if obj == undefined then print "Obj is undefined" |
http://rosettacode.org/wiki/Null_object | Null object |
Null (or nil) is the computer science concept of an undefined or unbound object.
Some languages have an explicit way to access the null object, and some don't.
Some languages distinguish the null object from undefined values, and some don't.
Task
Show how to access null in your language by checking to see if an object is equivalent to the null object.
This task is not about whether a variable is defined. The task is about "null"-like values in various languages, which may or may not be related to the defined-ness of variables in your language.
| #Modula-3 | Modula-3 | VAR foo := NIL |
http://rosettacode.org/wiki/One-dimensional_cellular_automata | One-dimensional cellular automata | Assume an array of cells with an initial distribution of live and dead cells,
and imaginary cells off the end of the array having fixed values.
Cells in the next generation of the array are calculated based on the value of the cell and its left and right nearest neighbours in the current generation.
If, in the following table, a live cell is represented by 1 and a dead cell by 0 then to generate the value of the cell at a particular index in the array of cellular values you use the following table:
000 -> 0 #
001 -> 0 #
010 -> 0 # Dies without enough neighbours
011 -> 1 # Needs one neighbour to survive
100 -> 0 #
101 -> 1 # Two neighbours giving birth
110 -> 1 # Needs one neighbour to survive
111 -> 0 # Starved to death.
| #Liberty_BASIC | Liberty BASIC | ' [RC] 'One-dimensional cellular automata'
' does not wrap so fails for some rules
rule$ ="00010110" ' Rule 22 decimal
state$ ="0011101101010101001000"
for j =1 to 20
print state$
oldState$ =state$
state$ ="0"
for k =2 to len( oldState$) -1
NHood$ =mid$( oldState$, k -1, 3) ' pick 3 char neighbourhood and turn binary string to decimal
vNHood =0
for kk =3 to 1 step -1
vNHood =vNHood +val( mid$( NHood$, kk, 1)) *2^( 3 -kk)
next kk
' .... & use it to index into rule$ to find appropriate new value
state$ =state$ +mid$( rule$, vNHood +1, 1)
next k
state$ =state$ +"0"
next j
end |
http://rosettacode.org/wiki/Numerical_integration | Numerical integration | Write functions to calculate the definite integral of a function ƒ(x) using all five of the following methods:
rectangular
left
right
midpoint
trapezium
Simpson's
composite
Your functions should take in the upper and lower bounds (a and b), and the number of approximations to make in that range (n).
Assume that your example already has a function that gives values for ƒ(x) .
Simpson's method is defined by the following pseudo-code:
Pseudocode: Simpson's method, composite
procedure quad_simpson_composite(f, a, b, n)
h := (b - a) / n
sum1 := f(a + h/2)
sum2 := 0
loop on i from 1 to (n - 1)
sum1 := sum1 + f(a + h * i + h/2)
sum2 := sum2 + f(a + h * i)
answer := (h / 6) * (f(a) + f(b) + 4*sum1 + 2*sum2)
Demonstrate your function by showing the results for:
ƒ(x) = x3, where x is [0,1], with 100 approximations. The exact result is 0.25 (or 1/4)
ƒ(x) = 1/x, where x is [1,100], with 1,000 approximations. The exact result is 4.605170+ (natural log of 100)
ƒ(x) = x, where x is [0,5000], with 5,000,000 approximations. The exact result is 12,500,000
ƒ(x) = x, where x is [0,6000], with 6,000,000 approximations. The exact result is 18,000,000
See also
Active object for integrating a function of real time.
Special:PrefixIndex/Numerical integration for other integration methods.
| #Nim | Nim | type Function = proc(x: float): float
type Rule = proc(f: Function; x, h: float): float
proc leftRect(f: Function; x, h: float): float =
f(x)
proc midRect(f: Function; x, h: float): float =
f(x + h/2.0)
proc rightRect(f: Function; x, h: float): float =
f(x + h)
proc trapezium(f: Function; x, h: float): float =
(f(x) + f(x+h)) / 2.0
proc simpson(f: Function, x, h: float): float =
(f(x) + 4.0*f(x+h/2.0) + f(x+h)) / 6.0
proc cube(x: float): float =
x * x * x
proc reciprocal(x: float): float =
1.0 / x
proc identity(x: float): float =
x
proc integrate(f: Function; a, b: float; steps: int; meth: Rule): float =
let h = (b-a) / float(steps)
for i in 0 ..< steps:
result += meth(f, a+float(i)*h, h)
result = h * result
for fName, a, b, steps, fun in items(
[("cube", 0, 1, 100, cube),
("reciprocal", 1, 100, 1000, reciprocal),
("identity", 0, 5000, 5_000_000, identity),
("identity", 0, 6000, 6_000_000, identity)]):
for rName, rule in items({"leftRect": leftRect, "midRect": midRect,
"rightRect": rightRect, "trapezium": trapezium, "simpson": simpson}):
echo fName, " integrated using ", rName
echo " from ", a, " to ", b, " (", steps, " steps) = ",
integrate(fun, float(a), float(b), steps, rule) |
http://rosettacode.org/wiki/Old_lady_swallowed_a_fly | Old lady swallowed a fly | Task
Present a program which emits the lyrics to the song I Knew an Old Lady Who Swallowed a Fly, taking advantage of the repetitive structure of the song's lyrics.
This song has multiple versions with slightly different lyrics, so all these programs might not emit identical output.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Sidef | Sidef | var victims = [
:fly: " I don't know why S—",
:spider: " That wriggled and jiggled and tickled inside her.",
:bird: " How absurd, T!",
:cat: " Fancy that, S!",
:dog: " What a hog, T!",
:goat: " She just opened her throat, and in walked the goat!",
:cow: " I don't know how S!",
:horse: " She's dead, of course...",
];
var history = ["I guess she'll die...\n"];
victims.each { |pair|
var (victim, verse) = pair...;
say "There was an old lady who swallowed a #{victim}...";
verse.sub!(/\bS\b/, "she swallowed the #{victim}");
verse.sub!(/\bT\b/, "to swallow a #{victim}!");
say verse;
verse ~~ /dead/ && break;
history[0].sub!(/^X/, "She swallowed the #{victim}");
history.each{.say};
history.len < 5 && history.unshift(verse);
history.unshift("X to catch the #{victim},");
}; |
http://rosettacode.org/wiki/Ordered_words | Ordered words | An ordered word is a word in which the letters appear in alphabetic order.
Examples include abbey and dirt.
Task[edit]
Find and display all the ordered words in the dictionary unixdict.txt that have the longest word length.
(Examples that access the dictionary file locally assume that you have downloaded this file yourself.)
The display needs to be shown on this page.
Related tasks
Word plays
Ordered words
Palindrome detection
Semordnilap
Anagrams
Anagrams/Deranged anagrams
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Simula | Simula | BEGIN
BOOLEAN PROCEDURE ISORDERED(W); TEXT W;
BEGIN
BOOLEAN B;
B := TRUE;
W.SETPOS(1);
IF W.MORE THEN
BEGIN
CHARACTER CURR, LAST;
CURR := W.GETCHAR;
WHILE W.MORE AND B DO
BEGIN
LAST := CURR;
CURR := W.GETCHAR;
B := LAST <= CURR;
END;
END;
ISORDERED := B;
END;
REF (INFILE) INF;
INTEGER LONGEST;
TEXT W;
COMMENT FIND LONGEST LENGTH;
INF :- NEW INFILE("unixdict.txt");
INF.OPEN(BLANKS(132));
WHILE NOT INF.LASTITEM DO
BEGIN
W :- COPY(INF.IMAGE).STRIP;
IF ISORDERED(W) THEN
IF W.LENGTH > LONGEST THEN
LONGEST := W.LENGTH;
INF.INIMAGE;
END;
INF.CLOSE;
COMMENT OUTPUT ORDRERED WORDS OF LONGEST LENGTH;
INF :- NEW INFILE("unixdict.txt");
INF.OPEN(BLANKS(132));
WHILE NOT INF.LASTITEM DO
BEGIN
W :- COPY(INF.IMAGE).STRIP;
IF W.LENGTH = LONGEST AND THEN ISORDERED(W) THEN
BEGIN
OUTTEXT(W);
OUTIMAGE;
END;
INF.INIMAGE;
END;
INF.CLOSE;
END.
|
http://rosettacode.org/wiki/Palindrome_detection | Palindrome detection | A palindrome is a phrase which reads the same backward and forward.
Task[edit]
Write a function or program that checks whether a given sequence of characters (or, if you prefer, bytes)
is a palindrome.
For extra credit:
Support Unicode characters.
Write a second function (possibly as a wrapper to the first) which detects inexact palindromes, i.e. phrases that are palindromes if white-space and punctuation is ignored and case-insensitive comparison is used.
Hints
It might be useful for this task to know how to reverse a string.
This task's entries might also form the subjects of the task Test a function.
Related tasks
Word plays
Ordered words
Palindrome detection
Semordnilap
Anagrams
Anagrams/Deranged anagrams
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Tailspin | Tailspin |
templates palindrome
[$...] -> #
when <=$(last..first:-1)> do '$...;' !
end palindrome
[['rotor', 'racecar', 'level', 'rosetta']... -> palindrome ] -> !OUT::write
|
http://rosettacode.org/wiki/Number_names | Number names | Task
Show how to spell out a number in English.
You can use a preexisting implementation or roll your own, but you should support inputs up to at least one million (or the maximum value of your language's default bounded integer type, if that's less).
Support for inputs other than positive integers (like zero, negative integers, and floating-point numbers) is optional.
Related task
Spelling of ordinal numbers.
| #Haskell | Haskell | import Data.List (intercalate, unfoldr)
spellInteger :: Integer -> String
spellInteger n
| n < 0 = "negative " ++ spellInteger (-n)
| n < 20 = small n
| n < 100 = let (a, b) = n `divMod` 10
in tens a ++ nonzero '-' b
| n < 1000 = let (a, b) = n `divMod` 100
in small a ++ " hundred" ++ nonzero ' ' b
| otherwise = intercalate ", " $ map big $ reverse $
filter ((/= 0) . snd) $ zip [0..] $ unfoldr uff n
where nonzero :: Char -> Integer -> String
nonzero _ 0 = ""
nonzero c n = c : spellInteger n
uff :: Integer -> Maybe (Integer, Integer)
uff 0 = Nothing
uff n = Just $ uncurry (flip (,)) $ n `divMod` 1000
small, tens :: Integer -> String
small = (["zero", "one", "two", "three", "four", "five",
"six", "seven", "eight", "nine", "ten", "eleven",
"twelve", "thirteen", "fourteen", "fifteen", "sixteen",
"seventeen", "eighteen", "nineteen"] !!) . fromEnum
tens = ([undefined, undefined, "twenty", "thirty", "forty",
"fifty", "sixty", "seventy", "eighty", "ninety"] !!) .
fromEnum
big :: (Int, Integer) -> String
big (0, n) = spellInteger n
big (1, n) = spellInteger n ++ " thousand"
big (e, n) = spellInteger n ++ ' ' : (l !! e) ++ "illion"
where l = [undefined, undefined, "m", "b", "tr", "quadr",
"quint", "sext", "sept", "oct", "non", "dec"] |
http://rosettacode.org/wiki/Number_reversal_game | Number reversal game | Task
Given a jumbled list of the numbers 1 to 9 that are definitely not in
ascending order.
Show the list, and then ask the player how many digits from the
left to reverse.
Reverse those digits, then ask again, until all the digits end up in ascending order.
The score is the count of the reversals needed to attain the ascending order.
Note: Assume the player's input does not need extra validation.
Related tasks
Sorting algorithms/Pancake sort
Pancake sorting.
Topswops
| #Groovy | Groovy | sorted = [*(1..9)]
arr = sorted.clone()
void flipstart(n) { arr[0..<n] = arr[0..<n].reverse() }
int steps = 0
while (arr==sorted) Collections.shuffle(arr)
while (arr!=sorted) {
println arr.join(' ')
print 'Reverse how many? '
def flipcount = System.in.readLine()
flipstart( flipcount.toInteger() )
steps += 1
}
println "Done! That took you ${steps} steps" |
http://rosettacode.org/wiki/Null_object | Null object |
Null (or nil) is the computer science concept of an undefined or unbound object.
Some languages have an explicit way to access the null object, and some don't.
Some languages distinguish the null object from undefined values, and some don't.
Task
Show how to access null in your language by checking to see if an object is equivalent to the null object.
This task is not about whether a variable is defined. The task is about "null"-like values in various languages, which may or may not be related to the defined-ness of variables in your language.
| #MUMPS | MUMPS |
CACHE>WRITE $DATA(VARI)
0
CACHE>SET VARI="HELLO" WRITE $DATA(VARI)
1
CACHE>NEW VARI WRITE $DATA(VARI) ;Change to a new scope
0
CACHE 1S1>SET VARI(1,2)="DOWN" WRITE $DATA(VARI)
10
CACHE 1S1>WRITE $DATA(VARI(1))
10
CACHE 1S1>WRITE $D(VARI(1,2))
1
CACHE 1S1>SET VARI(1)="UP" WRITE $DATA(VARI(1))
11
<CACHE 1S1>QUIT ;Leave the scope
<CACHE>W $DATA(VARI)," ",VARI
1 HELLO
|
http://rosettacode.org/wiki/Null_object | Null object |
Null (or nil) is the computer science concept of an undefined or unbound object.
Some languages have an explicit way to access the null object, and some don't.
Some languages distinguish the null object from undefined values, and some don't.
Task
Show how to access null in your language by checking to see if an object is equivalent to the null object.
This task is not about whether a variable is defined. The task is about "null"-like values in various languages, which may or may not be related to the defined-ness of variables in your language.
| #Nanoquery | Nanoquery | $x = $null
if ($x = $null)
println "x is null"
else
println "x is not null"
end if |
http://rosettacode.org/wiki/One-dimensional_cellular_automata | One-dimensional cellular automata | Assume an array of cells with an initial distribution of live and dead cells,
and imaginary cells off the end of the array having fixed values.
Cells in the next generation of the array are calculated based on the value of the cell and its left and right nearest neighbours in the current generation.
If, in the following table, a live cell is represented by 1 and a dead cell by 0 then to generate the value of the cell at a particular index in the array of cellular values you use the following table:
000 -> 0 #
001 -> 0 #
010 -> 0 # Dies without enough neighbours
011 -> 1 # Needs one neighbour to survive
100 -> 0 #
101 -> 1 # Two neighbours giving birth
110 -> 1 # Needs one neighbour to survive
111 -> 0 # Starved to death.
| #Locomotive_Basic | Locomotive Basic | 10 MODE 1:n=10:READ w:DIM x(w+1),x2(w+1):FOR i=1 to w:READ x(i):NEXT
20 FOR k=1 TO n
30 FOR j=1 TO w
40 IF x(j) THEN PRINT "#"; ELSE PRINT "_";
50 IF x(j-1)+x(j)+x(j+1)=2 THEN x2(j)=1 ELSE x2(j)=0
60 NEXT:PRINT
70 FOR j=1 TO w:x(j)=x2(j):NEXT
80 NEXT
90 DATA 20,0,1,1,1,0,1,1,0,1,0,1,0,1,0,1,0,0,1,0,0 |
http://rosettacode.org/wiki/Numerical_integration | Numerical integration | Write functions to calculate the definite integral of a function ƒ(x) using all five of the following methods:
rectangular
left
right
midpoint
trapezium
Simpson's
composite
Your functions should take in the upper and lower bounds (a and b), and the number of approximations to make in that range (n).
Assume that your example already has a function that gives values for ƒ(x) .
Simpson's method is defined by the following pseudo-code:
Pseudocode: Simpson's method, composite
procedure quad_simpson_composite(f, a, b, n)
h := (b - a) / n
sum1 := f(a + h/2)
sum2 := 0
loop on i from 1 to (n - 1)
sum1 := sum1 + f(a + h * i + h/2)
sum2 := sum2 + f(a + h * i)
answer := (h / 6) * (f(a) + f(b) + 4*sum1 + 2*sum2)
Demonstrate your function by showing the results for:
ƒ(x) = x3, where x is [0,1], with 100 approximations. The exact result is 0.25 (or 1/4)
ƒ(x) = 1/x, where x is [1,100], with 1,000 approximations. The exact result is 4.605170+ (natural log of 100)
ƒ(x) = x, where x is [0,5000], with 5,000,000 approximations. The exact result is 12,500,000
ƒ(x) = x, where x is [0,6000], with 6,000,000 approximations. The exact result is 18,000,000
See also
Active object for integrating a function of real time.
Special:PrefixIndex/Numerical integration for other integration methods.
| #OCaml | OCaml | let integrate f a b steps meth =
let h = (b -. a) /. float_of_int steps in
let rec helper i s =
if i >= steps then s
else helper (succ i) (s +. meth f (a +. h *. float_of_int i) h)
in
h *. helper 0 0. |
http://rosettacode.org/wiki/Old_lady_swallowed_a_fly | Old lady swallowed a fly | Task
Present a program which emits the lyrics to the song I Knew an Old Lady Who Swallowed a Fly, taking advantage of the repetitive structure of the song's lyrics.
This song has multiple versions with slightly different lyrics, so all these programs might not emit identical output.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Tcl | Tcl | package require Tcl 8.6
puts [zlib inflate [binary decode base64 "
7VRNa8MwDL3nV2inXkZ+xDa29taxws5q7NZuPSvYDib/fnJKPxwXBoNCx3KTn56t
p6dEC9hbioAWyAgwKHqIisBHNIaiFICwMX1dLUCQnYUDO6oevJIXrMCngbeUTmHr
U3pmDAgt64ov/1jEt1pIV1crhQGi09utSbgVsLuIg272KdbWMx1UuvFRCDm8BYGg
wdCos7hbN/Gknair904HCbj2HZ9gdaKcCKXihOd6j37cUXfPGOrqFW3T81sc560N
2VItw7nUP23BC23r6jN9ogiK49yCIVuqZTiX+i+sWmo2Y86lv6gLCiLyEwRrPTZt
4JW6Gc5FT+ZemPtGxy53nQ9ArbSMq6RFOSr+zTM915DwXP00jd8sRoqjIoqR0XpM
nCtGcDITPI3qxgvc7mWqE4aN5DCknyYy2hfL/MC85lzKjMybxnsP452T83JQNPMg
JIpHoA001DH88A0=
"]] |
http://rosettacode.org/wiki/Old_lady_swallowed_a_fly | Old lady swallowed a fly | Task
Present a program which emits the lyrics to the song I Knew an Old Lady Who Swallowed a Fly, taking advantage of the repetitive structure of the song's lyrics.
This song has multiple versions with slightly different lyrics, so all these programs might not emit identical output.
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
| #TXR | TXR | @(deffilter abbr
("IK" "I know an old lady who swallowed a") ("SW" "She swallowed the")
("SS" "she swallowed") ("CA" "to catch the") ("XX" "Perhaps she'll die")
("C" "cow") ("G" "goat") ("D" "dog") ("T" "cat") ("R" "bird")
("S " "spider ") ("F" "fly"))
@(bind lastverse
("IK C"
"I don't know how SS the C"
"SW C CA G"
"SW G CA D"
"SW D CA T"
"SW T CA R"
"SW R CA S"
"SW S CA F"
"But I don't know why SS that F"
"XX"
""
"IK horse"
"She's alive and well of course!"))
@(bind animal_line
("G: Opened her throat and down went the G!"
"D: What a hog to swallow a D!"
"T: Imagine that! She swallowed a T!"
"R: How absurd to swallow a R!"
"S: That wriggled and jiggled and tickled inside her"
"F: But I don't know why SS the F"))
@(define expand_backwards (song lengthened_song done))
@ (local line2 line3 verse rest animal previous_animal previous_animal_verse)
@ (next :list song)
@ (cases)
IK @animal
@line2
SW @animal CA @previous_animal
@ (maybe)
But @(skip)F
@ (end)
@ (collect)
@ verse
@ (until)
@ (end)
@ (collect)
@ rest
@ (end)
@ (next :list animal_line)
@ (skip)
@previous_animal: @previous_animal_verse
@ (output :into lengthened_song)
IK @previous_animal
@previous_animal_verse
@ (repeat)
@ verse
@ (end)
@ (repeat)
@ song
@ (end)
@ (end)
@ (bind done nil)
@ (or)
IK @(skip)
@line2
XX
@ (bind lengthened_song song)
@ (bind done t)
@ (end)
@(end)
@(define expand_song (in out))
@ (local lengthened done)
@ (expand_backwards in lengthened done)
@ (cases)
@ (bind done nil)
@ (expand_song lengthened out)
@ (or)
@ (bind out lengthened)
@ (end)
@(end)
@(expand_song lastverse song)
@(output :filter abbr)
@ (repeat)
@song
@ (end)
@(end) |
http://rosettacode.org/wiki/Ordered_words | Ordered words | An ordered word is a word in which the letters appear in alphabetic order.
Examples include abbey and dirt.
Task[edit]
Find and display all the ordered words in the dictionary unixdict.txt that have the longest word length.
(Examples that access the dictionary file locally assume that you have downloaded this file yourself.)
The display needs to be shown on this page.
Related tasks
Word plays
Ordered words
Palindrome detection
Semordnilap
Anagrams
Anagrams/Deranged anagrams
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Smalltalk | Smalltalk | |file dict r t|
file := FileStream open: 'unixdict.txt' mode: FileStream read.
dict := Set new.
"load the whole dict into the set before, 'filter' later"
[ file atEnd ] whileFalse: [
dict add: (file upTo: Character nl) ].
"find those with the sorted letters, and sort them by length"
r := ((dict
select: [ :w | (w asOrderedCollection sort) = (w asOrderedCollection) ] )
asSortedCollection: [:a :b| (a size) > (b size) ] ).
"get those that have length = to the max length, and sort alphabetically"
r := (r select: [:w| (w size) = ((r at: 1) size)]) asSortedCollection.
r do: [:e| e displayNl]. |
http://rosettacode.org/wiki/Palindrome_detection | Palindrome detection | A palindrome is a phrase which reads the same backward and forward.
Task[edit]
Write a function or program that checks whether a given sequence of characters (or, if you prefer, bytes)
is a palindrome.
For extra credit:
Support Unicode characters.
Write a second function (possibly as a wrapper to the first) which detects inexact palindromes, i.e. phrases that are palindromes if white-space and punctuation is ignored and case-insensitive comparison is used.
Hints
It might be useful for this task to know how to reverse a string.
This task's entries might also form the subjects of the task Test a function.
Related tasks
Word plays
Ordered words
Palindrome detection
Semordnilap
Anagrams
Anagrams/Deranged anagrams
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Tcl | Tcl | package require Tcl 8.5
proc palindrome {s} {
return [expr {$s eq [string reverse $s]}]
} |
http://rosettacode.org/wiki/Number_names | Number names | Task
Show how to spell out a number in English.
You can use a preexisting implementation or roll your own, but you should support inputs up to at least one million (or the maximum value of your language's default bounded integer type, if that's less).
Support for inputs other than positive integers (like zero, negative integers, and floating-point numbers) is optional.
Related task
Spelling of ordinal numbers.
| #HicEst | HicEst | SUBROUTINE NumberToWords(number)
CHARACTER outP*255, small*130, tens*80, big*80
REAL :: decimal_places = 7
INIT( APPENDIX("#literals"), small, tens, big)
num = ABS( INT(number) )
order = 0
outP = ' '
DO i = 1, num + 1
tmp = MOD(num, 100)
IF(tmp > 19) THEN
EDIT(Text=tens, ITeM=INT(MOD(tmp/10, 10)), Parse=medium)
IF( MOD(tmp, 10) ) THEN
EDIT(Text=small, ITeM=MOD(tmp,10)+1, Parse=mini)
outP = medium // '-' // mini // ' ' // outP
ELSE
outP = medium // ' ' // outP
ENDIF
ELSEIF(tmp > 0) THEN
EDIT(Text=small, ITeM=tmp+1, Parse=mini)
outP = mini // ' '// outP
ELSEIF(number == 0) THEN
outP = 'zero'
ENDIF
tmp = INT(MOD(num, 1000) / 100)
IF(tmp) THEN
EDIT(Text=small, ITeM=tmp+1, Parse=oneto19)
outP = oneto19 // ' hundred ' // outP
ENDIF
num = INT(num /1000)
IF( num == 0) THEN
IF(number < 0) outP = 'minus ' // outP
fraction = ABS( MOD(number, 1) )
IF(fraction) WRITE(Text=outP, APPend) ' point'
DO j = 1, decimal_places
IF( fraction >= 10^(-decimal_places) ) THEN
num = INT( 10.01 * fraction )
EDIT(Text=small, ITeM=num+1, Parse=digit)
WRITE(Text=outP, APPend) ' ', digit
fraction = 10*fraction - num
ENDIF
ENDDO
OPEN(FIle="temp.txt", APPend)
WRITE(FIle="temp.txt", Format='F10, " = ", A', CLoSe=1) number, outP
RETURN
ENDIF
order = order + 1
EDIT(Text=big, ITeM=order, Parse=kilo)
IF( MOD(num, 1000) ) outP = kilo // ' and '// outP
ENDDO
END
CALL NumberToWords( 0 )
CALL NumberToWords( 1234 )
CALL NumberToWords( 1234/100 )
CALL NumberToWords( 10000000 + 1.2 )
CALL NumberToWords( 2^15 )
CALL NumberToWords( 0.001 )
CALL NumberToWords( -EXP(1) )
#literals
SMALL= zero one two three four five six seven eight nine ten &
eleven twelve thirteen fourteen fifteen sixteen seventeen eighteen nineteen
TENS=ten twenty thirty forty fifty sixty seventy eighty ninety
BIG=thousand million billion trillion quadrillion |
http://rosettacode.org/wiki/Number_reversal_game | Number reversal game | Task
Given a jumbled list of the numbers 1 to 9 that are definitely not in
ascending order.
Show the list, and then ask the player how many digits from the
left to reverse.
Reverse those digits, then ask again, until all the digits end up in ascending order.
The score is the count of the reversals needed to attain the ascending order.
Note: Assume the player's input does not need extra validation.
Related tasks
Sorting algorithms/Pancake sort
Pancake sorting.
Topswops
| #Haskell | Haskell | import Data.List
import Control.Arrow
import Rosetta.Knuthshuffle
numberRevGame = do
let goal = [1..9]
shuffle xs =
if xs /= goal then return xs
else shuffle =<< knuthShuffle xs
prefixFlipAt k = uncurry (++). first reverse. splitAt k
prompt r ry = do
putStr $ show r ++ ". " ++ concatMap (flip (++) " ". show) ry
++ " How many to flip? "
answ <- getLine
let n = read answ
if n<10 && 0<n then return n
else do
putStrLn "Error. The number should be between 0 and 10. Try again"
prompt r ry
playNRG r nrs =
if nrs == goal then do
putStrLn $ "The answer is: " ++ concatMap (flip (++) " ". show) nrs
putStrLn $ "It took you " ++ show r ++ " attempts to sort the numbers."
putStrLn ""
else do
answ <- prompt r nrs
playNRG (succ r) (prefixFlipAt answ nrs)
start <- shuffle goal
playNRG 1 start |
http://rosettacode.org/wiki/Null_object | Null object |
Null (or nil) is the computer science concept of an undefined or unbound object.
Some languages have an explicit way to access the null object, and some don't.
Some languages distinguish the null object from undefined values, and some don't.
Task
Show how to access null in your language by checking to see if an object is equivalent to the null object.
This task is not about whether a variable is defined. The task is about "null"-like values in various languages, which may or may not be related to the defined-ness of variables in your language.
| #Neko | Neko | /**
<doc>
<p>Neko uses <i>null</i> for undefined variables,
and also as a programmer accessible value.</p>
<p>The <i>null</i> value can be treated as a boolean value with the
builtin $istrue, and tests as false.</p>
</doc>
*/
var n = null
if n == null $print("n is null\n")
if $not($istrue(n)) $print("and tests as boolean false\n") |
http://rosettacode.org/wiki/Null_object | Null object |
Null (or nil) is the computer science concept of an undefined or unbound object.
Some languages have an explicit way to access the null object, and some don't.
Some languages distinguish the null object from undefined values, and some don't.
Task
Show how to access null in your language by checking to see if an object is equivalent to the null object.
This task is not about whether a variable is defined. The task is about "null"-like values in various languages, which may or may not be related to the defined-ness of variables in your language.
| #NetRexx | NetRexx | /* NetRexx */
options replace format comments java crossref symbols binary
robject = Rexx -- create an object for which the value is undefined
say String.valueOf(robject) -- will report the text "null"
if robject = null then say 'Really, it''s "null"!'
|
http://rosettacode.org/wiki/One-dimensional_cellular_automata | One-dimensional cellular automata | Assume an array of cells with an initial distribution of live and dead cells,
and imaginary cells off the end of the array having fixed values.
Cells in the next generation of the array are calculated based on the value of the cell and its left and right nearest neighbours in the current generation.
If, in the following table, a live cell is represented by 1 and a dead cell by 0 then to generate the value of the cell at a particular index in the array of cellular values you use the following table:
000 -> 0 #
001 -> 0 #
010 -> 0 # Dies without enough neighbours
011 -> 1 # Needs one neighbour to survive
100 -> 0 #
101 -> 1 # Two neighbours giving birth
110 -> 1 # Needs one neighbour to survive
111 -> 0 # Starved to death.
| #Logo | Logo | make "cell_list [0 1 1 1 0 1 1 0 1 0 1 0 1 0 1 0 0 1 0 0]
make "generations 9
to evolve :n
ifelse :n=1 [make "nminus1 item :cell_count :cell_list][make "nminus1 item :n-1 :cell_list]
ifelse :n=:cell_count[make "nplus1 item 1 :cell_list][make "nplus1 item :n+1 :cell_list]
ifelse ((item :n :cell_list)=0) [
ifelse (and (:nminus1=1) (:nplus1=1)) [output 1][output (item :n :cell_list)]
][
ifelse (and (:nminus1=1) (:nplus1=1)) [output 0][
ifelse and (:nminus1=0) (:nplus1=0) [output 0][output (item :n :cell_list)]]
]
end
to CA_1D :cell_list :generations
make "cell_count count :cell_list
(print ")
make "printout "
repeat :cell_count [
make "printout word :printout ifelse (item repcount :cell_list)=1 ["#]["_]
]
(print "Generation "0: :printout)
repeat :generations [
(make "cell_list_temp [])
repeat :cell_count[
(make "cell_list_temp (lput (evolve repcount) :cell_list_temp))
]
make "cell_list :cell_list_temp
make "printout "
repeat :cell_count [
make "printout word :printout ifelse (item repcount :cell_list)=1 ["#]["_]
]
(print "Generation word repcount ": :printout)
]
end
CA_1D :cell_list :generations |
http://rosettacode.org/wiki/One-dimensional_cellular_automata | One-dimensional cellular automata | Assume an array of cells with an initial distribution of live and dead cells,
and imaginary cells off the end of the array having fixed values.
Cells in the next generation of the array are calculated based on the value of the cell and its left and right nearest neighbours in the current generation.
If, in the following table, a live cell is represented by 1 and a dead cell by 0 then to generate the value of the cell at a particular index in the array of cellular values you use the following table:
000 -> 0 #
001 -> 0 #
010 -> 0 # Dies without enough neighbours
011 -> 1 # Needs one neighbour to survive
100 -> 0 #
101 -> 1 # Two neighbours giving birth
110 -> 1 # Needs one neighbour to survive
111 -> 0 # Starved to death.
| #Lua | Lua | num_iterations = 9
f = { 0, 1, 1, 1, 0, 1, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 0, 1, 0, 0 }
function Output( f, l )
io.write( l, ": " )
for i = 1, #f do
local c
if f[i] == 1 then c = '#' else c = '_' end
io.write( c )
end
print ""
end
Output( f, 0 )
for l = 1, num_iterations do
local g = {}
for i = 2, #f-1 do
if f[i-1] + f[i+1] == 1 then
g[i] = f[i]
elseif f[i] == 0 and f[i-1] + f[i+1] == 2 then
g[i] = 1
else
g[i] = 0
end
end
if f[1] == 1 and f[2] == 1 then g[1] = 1 else g[1] = 0 end
if f[#f] == 1 and f[#f-1] == 1 then g[#f] = 1 else g[#f] = 0 end
f, g = g, f
Output( f, l )
end |
http://rosettacode.org/wiki/Numerical_integration | Numerical integration | Write functions to calculate the definite integral of a function ƒ(x) using all five of the following methods:
rectangular
left
right
midpoint
trapezium
Simpson's
composite
Your functions should take in the upper and lower bounds (a and b), and the number of approximations to make in that range (n).
Assume that your example already has a function that gives values for ƒ(x) .
Simpson's method is defined by the following pseudo-code:
Pseudocode: Simpson's method, composite
procedure quad_simpson_composite(f, a, b, n)
h := (b - a) / n
sum1 := f(a + h/2)
sum2 := 0
loop on i from 1 to (n - 1)
sum1 := sum1 + f(a + h * i + h/2)
sum2 := sum2 + f(a + h * i)
answer := (h / 6) * (f(a) + f(b) + 4*sum1 + 2*sum2)
Demonstrate your function by showing the results for:
ƒ(x) = x3, where x is [0,1], with 100 approximations. The exact result is 0.25 (or 1/4)
ƒ(x) = 1/x, where x is [1,100], with 1,000 approximations. The exact result is 4.605170+ (natural log of 100)
ƒ(x) = x, where x is [0,5000], with 5,000,000 approximations. The exact result is 12,500,000
ƒ(x) = x, where x is [0,6000], with 6,000,000 approximations. The exact result is 18,000,000
See also
Active object for integrating a function of real time.
Special:PrefixIndex/Numerical integration for other integration methods.
| #PARI.2FGP | PARI/GP | rectLeft(f, a, b, n)={
sum(i=0,n-1,f(a+(b-a)*i/n), 0.)*(b-a)/n
};
rectMid(f, a, b, n)={
sum(i=1,n,f(a+(b-a)*(i-.5)/n), 0.)*(b-a)/n
};
rectRight(f, a, b, n)={
sum(i=1,n,f(a+(b-a)*i/n), 0.)*(b-a)/n
};
trapezoidal(f, a, b, n)={
sum(i=1,n-1,f(a+(b-a)*i/n), f(a)/2+f(b)/2.)*(b-a)/n
};
Simpson(f, a, b, n)={
my(h=(b - a)/n, s);
s = 2*sum(i=1,n-1,
2*f(a + h * (i+1/2)) + f(a + h * i)
, 0.) + 4*f(a + h/2) + f(a) + f(b);
s * h / 6
};
test(f, a, b, n)={
my(v=[rectLeft, rectMid, rectRight, trapezoidal, Simpson]);
print("Testing function "f" on ",[a,b]," with "n" intervals:");
for(i=1,#v, print("\t"v[i](f, a, b, n)))
};
# \\ Turn on timer
test(x->x^3, 0, 1, 100)
test(x->1/x, 1, 100, 1000)
test(x->x, 0, 5000, 5000000)
test(x->x, 0, 6000, 6000000) |
http://rosettacode.org/wiki/Old_lady_swallowed_a_fly | Old lady swallowed a fly | Task
Present a program which emits the lyrics to the song I Knew an Old Lady Who Swallowed a Fly, taking advantage of the repetitive structure of the song's lyrics.
This song has multiple versions with slightly different lyrics, so all these programs might not emit identical output.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #UNIX_Shell | UNIX Shell | animals=(fly spider bird cat dog pig goat cow donkey horse)
comments=("I don't know why she swallowed that fly"
"That wriggled and jiggled and tickled inside her"
"Quite absurd, to swallow a bird"
"How about that, to swallow a cat"
"What a hog, to swallow a dog"
"Her mouth was so big to swallow a pig"
"She just opened her throat to swallow a goat."
"I don't know how she swallowed a cow."
"It was rather wonky to swallow a donkey"
"She's dead, of course!")
include=(2 2 1 1 1 1 1 1 1 0)
for (( i=0; i<${#animals[@]}; ++i )); do
echo "There was an old lady who swallowed a ${animals[i]}"
echo "${comments[i]}"
if (( include[i] )); then
if (( i )); then
for (( j=i-1; j>=0; --j )); do
echo "She swallowed the ${animals[j+1]} to catch the ${animals[j]}"
if (( include[j] > 1 )); then
echo "${comments[j]}"
fi
done
fi
echo "Perhaps she'll die"
echo
fi
done |
http://rosettacode.org/wiki/Old_lady_swallowed_a_fly | Old lady swallowed a fly | Task
Present a program which emits the lyrics to the song I Knew an Old Lady Who Swallowed a Fly, taking advantage of the repetitive structure of the song's lyrics.
This song has multiple versions with slightly different lyrics, so all these programs might not emit identical output.
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
| #Ursa | Ursa | decl string<> reason creatures comments
append "She swallowed the " " to catch the " reason
append "fly" "spider" "bird" "cat" "dog" "goat" "cow" "horse" creatures
append "I don't know why she swallowed that fly.\nPerhaps she'll die\n" comments
append "That wiggled and jiggled and tickled inside her" comments
append "How absurd, to swallow a bird" comments
append "Imagine that. She swallowed a cat" comments
append "What a hog to swallow a dog" comments
append "She just opened her throat and swallowed that goat" comments
append "I don't know how she swallowed that cow" comments
append "She's dead of course" comments
decl int max
set max (size creatures)
for (decl int i) (< i max) (inc i)
out "There was an old lady who swallowed a " creatures<i> endl console
out comments<i> endl console
decl int j
for (set j i) (and (> j 0) (< i (- max 1))) (dec j)
out reason<0> creatures<j> reason<1> creatures<(int (- j 1))> endl console
if (= j 1)
out comments<(int (- j 1))> endl console
end if
end for
end for
in string console |
http://rosettacode.org/wiki/Ordered_words | Ordered words | An ordered word is a word in which the letters appear in alphabetic order.
Examples include abbey and dirt.
Task[edit]
Find and display all the ordered words in the dictionary unixdict.txt that have the longest word length.
(Examples that access the dictionary file locally assume that you have downloaded this file yourself.)
The display needs to be shown on this page.
Related tasks
Word plays
Ordered words
Palindrome detection
Semordnilap
Anagrams
Anagrams/Deranged anagrams
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
| #SPL | SPL | words = #.split(#.readtext("unixdict.txt","ascii"),#.lf)
max = 0
> i, 1..#.size(words,1)
word = words[i]
wordb = #.array(word)
wordbc = #.size(wordb,1)
> j, 3..wordbc,2
<< wordb[j]<wordb[j-2]
<
>> j!>wordbc|wordbc<max
? wordbc>max, result = ""
? wordbc>max, max = wordbc
result += word+#.crlf
<
#.output(result) |
http://rosettacode.org/wiki/Ordered_words | Ordered words | An ordered word is a word in which the letters appear in alphabetic order.
Examples include abbey and dirt.
Task[edit]
Find and display all the ordered words in the dictionary unixdict.txt that have the longest word length.
(Examples that access the dictionary file locally assume that you have downloaded this file yourself.)
The display needs to be shown on this page.
Related tasks
Word plays
Ordered words
Palindrome detection
Semordnilap
Anagrams
Anagrams/Deranged anagrams
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
| #Standard_ML | Standard ML | fun isOrdered s =
let
fun loop (i, c) =
let
val c' = String.sub (s, i)
in
c <= c' andalso loop (i + 1, c')
end
handle Subscript => true
in
loop (0, #"\^@")
end
fun longestOrdereds (s, prev as (len, lst)) =
let
val len' = size s
in
if len' >= len andalso isOrdered s then
if len' = len then (len, s :: lst) else (len', [s])
else
prev
end
val () = print ((String.concatWith " "
o #2
o foldr longestOrdereds (0, [])
o String.tokens Char.isSpace
o TextIO.inputAll) TextIO.stdIn ^ "\n") |
http://rosettacode.org/wiki/Palindrome_detection | Palindrome detection | A palindrome is a phrase which reads the same backward and forward.
Task[edit]
Write a function or program that checks whether a given sequence of characters (or, if you prefer, bytes)
is a palindrome.
For extra credit:
Support Unicode characters.
Write a second function (possibly as a wrapper to the first) which detects inexact palindromes, i.e. phrases that are palindromes if white-space and punctuation is ignored and case-insensitive comparison is used.
Hints
It might be useful for this task to know how to reverse a string.
This task's entries might also form the subjects of the task Test a function.
Related tasks
Word plays
Ordered words
Palindrome detection
Semordnilap
Anagrams
Anagrams/Deranged anagrams
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
| #TUSCRIPT | TUSCRIPT |
$$ MODE TUSCRIPT
pal ="ingirumimusnocteetconsumimurigni"
pal_r=TURN(pal)
SELECT pal
CASE $pal_r
PRINT "true"
DEFAULT
PRINT/ERROR "untrue"
ENDSELECT
|
http://rosettacode.org/wiki/Number_names | Number names | Task
Show how to spell out a number in English.
You can use a preexisting implementation or roll your own, but you should support inputs up to at least one million (or the maximum value of your language's default bounded integer type, if that's less).
Support for inputs other than positive integers (like zero, negative integers, and floating-point numbers) is optional.
Related task
Spelling of ordinal numbers.
| #Icon_and_Unicon | Icon and Unicon | link numbers # commas, spell
procedure main(arglist)
every x := !arglist do
write(commas(x), " -> ",spell(x))
end |
http://rosettacode.org/wiki/Number_reversal_game | Number reversal game | Task
Given a jumbled list of the numbers 1 to 9 that are definitely not in
ascending order.
Show the list, and then ask the player how many digits from the
left to reverse.
Reverse those digits, then ask again, until all the digits end up in ascending order.
The score is the count of the reversals needed to attain the ascending order.
Note: Assume the player's input does not need extra validation.
Related tasks
Sorting algorithms/Pancake sort
Pancake sorting.
Topswops
| #HicEst | HicEst | WRITE(Messagebox) "You took ", Reversals(), " attempts"
FUNCTION Reversals()
DIMENSION digits(9), temp(9)
digits = 0
DO i = 1, 9 ! create the shuffled digits
1 x = CEILING( RAN(9) )
IF( INDEX(digits, x) ) GOTO 1 ! HicEst has no WHILE
digits(i) = x
ENDDO
DO Reversals = 1, 1E6 ! HicEst needs an upper bound
DLG(NameEdit=Flips, DNum, MIn=0, MAx=9, Text=digits)
DO j = 1, Flips/2
swap = digits(j)
digits(j) = digits(Flips+1-j)
digits(Flips+1-j) = swap
ENDDO
temp = digits($+1) > digits($) ! $ = left side index
IF( SUM(temp) == 8 ) RETURN
ENDDO
END |
http://rosettacode.org/wiki/Null_object | Null object |
Null (or nil) is the computer science concept of an undefined or unbound object.
Some languages have an explicit way to access the null object, and some don't.
Some languages distinguish the null object from undefined values, and some don't.
Task
Show how to access null in your language by checking to see if an object is equivalent to the null object.
This task is not about whether a variable is defined. The task is about "null"-like values in various languages, which may or may not be related to the defined-ness of variables in your language.
| #NewLISP | NewLISP |
#! /usr/local/bin/newlisp
(setq myobject nil)
(println (nil? myobject))
(exit)
|
http://rosettacode.org/wiki/Null_object | Null object |
Null (or nil) is the computer science concept of an undefined or unbound object.
Some languages have an explicit way to access the null object, and some don't.
Some languages distinguish the null object from undefined values, and some don't.
Task
Show how to access null in your language by checking to see if an object is equivalent to the null object.
This task is not about whether a variable is defined. The task is about "null"-like values in various languages, which may or may not be related to the defined-ness of variables in your language.
| #Nim | Nim | let s: pointer = nil
{.experimental: "notnil".}
let ns: pointer not nil = nil # Compile time error |
http://rosettacode.org/wiki/Null_object | Null object |
Null (or nil) is the computer science concept of an undefined or unbound object.
Some languages have an explicit way to access the null object, and some don't.
Some languages distinguish the null object from undefined values, and some don't.
Task
Show how to access null in your language by checking to see if an object is equivalent to the null object.
This task is not about whether a variable is defined. The task is about "null"-like values in various languages, which may or may not be related to the defined-ness of variables in your language.
| #Oberon-2 | Oberon-2 |
MODULE Null;
IMPORT
Out;
TYPE
Object = POINTER TO ObjectDesc;
ObjectDesc = RECORD
END;
VAR
o: Object; (* default initialization to NIL *)
BEGIN
IF o = NIL THEN Out.String("o is NIL"); Out.Ln END
END Null.
|
http://rosettacode.org/wiki/One-dimensional_cellular_automata | One-dimensional cellular automata | Assume an array of cells with an initial distribution of live and dead cells,
and imaginary cells off the end of the array having fixed values.
Cells in the next generation of the array are calculated based on the value of the cell and its left and right nearest neighbours in the current generation.
If, in the following table, a live cell is represented by 1 and a dead cell by 0 then to generate the value of the cell at a particular index in the array of cellular values you use the following table:
000 -> 0 #
001 -> 0 #
010 -> 0 # Dies without enough neighbours
011 -> 1 # Needs one neighbour to survive
100 -> 0 #
101 -> 1 # Two neighbours giving birth
110 -> 1 # Needs one neighbour to survive
111 -> 0 # Starved to death.
| #M4 | M4 | divert(-1)
define(`set',`define(`$1[$2]',`$3')')
define(`get',`defn(`$1[$2]')')
define(`setrange',`ifelse(`$3',`',$2,`define($1[$2],$3)`'setrange($1,
incr($2),shift(shift(shift($@))))')')
dnl throw in sentinels at each end (0 and size+1) to make counting easy
define(`new',`set($1,size,eval($#-1))`'setrange($1,1,
shift($@))`'set($1,0,0)`'set($1,$#,0)')
define(`for',
`ifelse($#,0,``$0'',
`ifelse(eval($2<=$3),1,
`pushdef(`$1',$2)$4`'popdef(`$1')$0(`$1',incr($2),$3,`$4')')')')
define(`show',
`for(`k',1,get($1,size),`get($1,k) ')')
dnl swap(`a',a,`b') using arg stack for temp
define(`swap',`define(`$1',$3)`'define(`$3',$2)')
define(`nalive',
`eval(get($1,decr($2))+get($1,incr($2)))')
setrange(`live',0,0,1,0)
setrange(`dead',0,0,0,1)
define(`nv',
`ifelse(get($1,z),0,`get(dead,$3)',`get(live,$3)')')
define(`evolve',
`for(`z',1,get($1,size),
`set($2,z,nv($1,z,nalive($1,z)))')')
new(`a',0,1,1,1,0,1,1,0,1,0,1,0,1,0,1,0,0,1,0,0)
set(`b',size,get(`a',size))`'set(`b',0,0)`'set(`b',incr(get(`a',size)),0)
define(`x',`a')
define(`y',`b')
divert
for(`j',1,10,
`show(x)`'evolve(`x',`y')`'swap(`x',x,`y')
')`'show(x) |
http://rosettacode.org/wiki/One-dimensional_cellular_automata | One-dimensional cellular automata | Assume an array of cells with an initial distribution of live and dead cells,
and imaginary cells off the end of the array having fixed values.
Cells in the next generation of the array are calculated based on the value of the cell and its left and right nearest neighbours in the current generation.
If, in the following table, a live cell is represented by 1 and a dead cell by 0 then to generate the value of the cell at a particular index in the array of cellular values you use the following table:
000 -> 0 #
001 -> 0 #
010 -> 0 # Dies without enough neighbours
011 -> 1 # Needs one neighbour to survive
100 -> 0 #
101 -> 1 # Two neighbours giving birth
110 -> 1 # Needs one neighbour to survive
111 -> 0 # Starved to death.
| #Mathematica_.2F_Wolfram_Language | Mathematica / Wolfram Language | CellularAutomaton[{{0,0,_}->0,{0,1,0}->0,{0,1,1}->1,{1,0,0}->0,{1,0,1}->1,{1,1,0}->1,{1,1,1}->0},{{1,1,1,0,1,1,0,1,0,1,0,1,0,1,0,0,1},0},12]
Print @@@ (% /. {1 -> "#", 0 -> "."}); |
http://rosettacode.org/wiki/Numerical_integration | Numerical integration | Write functions to calculate the definite integral of a function ƒ(x) using all five of the following methods:
rectangular
left
right
midpoint
trapezium
Simpson's
composite
Your functions should take in the upper and lower bounds (a and b), and the number of approximations to make in that range (n).
Assume that your example already has a function that gives values for ƒ(x) .
Simpson's method is defined by the following pseudo-code:
Pseudocode: Simpson's method, composite
procedure quad_simpson_composite(f, a, b, n)
h := (b - a) / n
sum1 := f(a + h/2)
sum2 := 0
loop on i from 1 to (n - 1)
sum1 := sum1 + f(a + h * i + h/2)
sum2 := sum2 + f(a + h * i)
answer := (h / 6) * (f(a) + f(b) + 4*sum1 + 2*sum2)
Demonstrate your function by showing the results for:
ƒ(x) = x3, where x is [0,1], with 100 approximations. The exact result is 0.25 (or 1/4)
ƒ(x) = 1/x, where x is [1,100], with 1,000 approximations. The exact result is 4.605170+ (natural log of 100)
ƒ(x) = x, where x is [0,5000], with 5,000,000 approximations. The exact result is 12,500,000
ƒ(x) = x, where x is [0,6000], with 6,000,000 approximations. The exact result is 18,000,000
See also
Active object for integrating a function of real time.
Special:PrefixIndex/Numerical integration for other integration methods.
| #Pascal | Pascal | function RectLeft(function f(x: real): real; xl, xr: real): real;
begin
RectLeft := f(xl)
end;
function RectMid(function f(x: real): real; xl, xr: real) : real;
begin
RectMid := f((xl+xr)/2)
end;
function RectRight(function f(x: real): real; xl, xr: real): real;
begin
RectRight := f(xr)
end;
function Trapezium(function f(x: real): real; xl, xr: real): real;
begin
Trapezium := (f(xl) + f(xr))/2
end;
function Simpson(function f(x: real): real; xl, xr: real): real;
begin
Simpson := (f(xl) + 4*f((xl+xr)/2) + f(xr))/6
end;
function integrate(function method(function f(x: real): real; xl, xr: real): real;
function f(x: real): real;
a, b: real;
n: integer);
var
integral, h: real;
k: integer;
begin
integral := 0;
h := (b-a)/n;
for k := 0 to n-1 do
begin
integral := integral + method(f, a + k*h, a + (k+1)*h)
end;
integrate := integral
end; |
http://rosettacode.org/wiki/Old_lady_swallowed_a_fly | Old lady swallowed a fly | Task
Present a program which emits the lyrics to the song I Knew an Old Lady Who Swallowed a Fly, taking advantage of the repetitive structure of the song's lyrics.
This song has multiple versions with slightly different lyrics, so all these programs might not emit identical output.
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
| #Vlang | Vlang | const (
name = 0
lyric = 1
animals = [
["fly", "I don't know why she swallowed a fly. Perhaps she'll die."],
["spider", "That wiggled and jiggled and tickled inside her."],
["bird", "How absurd, to swallow a bird."],
["cat", "Imagine that, she swallowed a cat."],
["dog", "What a hog, to swallow a dog."],
["goat", "She just opened her throat and swallowed that goat."],
["cow", "I don't know how she swallowed that cow."],
["horse", "She's dead, of course."],
]
)
fn main() {
for i, animal in animals {
println("There was an old lady who swallowed a ${animal[name]},")
if i > 0 {
println(animal[lyric])
}
// Swallowing the last animal signals her death, cutting the
// lyrics short.
if i+1 == animals.len {
break
}
for j := i; j > 0; j-- {
println("She swallowed the ${animals[j][name]} to catch the ${animals[j-1][name]},")
}
println("${animals[0][lyric]}\n")
}
} |
http://rosettacode.org/wiki/Old_lady_swallowed_a_fly | Old lady swallowed a fly | Task
Present a program which emits the lyrics to the song I Knew an Old Lady Who Swallowed a Fly, taking advantage of the repetitive structure of the song's lyrics.
This song has multiple versions with slightly different lyrics, so all these programs might not emit identical output.
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 animals = ["fly", "spider", "bird", "cat","dog", "goat", "cow", "horse"]
var phrases = [
"",
"That wriggled and jiggled and tickled inside her",
"How absurd to swallow a bird",
"Fancy that to swallow a cat",
"What a hog, to swallow a dog",
"She just opened her throat and swallowed a goat",
"I don't know how she swallowed a cow",
"\n ...She's dead of course"
]
var sing = Fn.new {
for (i in 0..7) {
System.print("There was an old lady who swallowed a %(animals[i]);")
if (i > 0) System.print("%(phrases[i])!")
if (i == 7) return
System.print()
if (i > 0) {
for (j in i..1) {
System.write(" She swallowed the %(animals[j]) to catch the %(animals[j - 1])")
System.print((j < 3) ? ";" :",")
if (j == 2) System.print(" %(phrases[1])!")
}
}
System.print(" I don't know why she swallowed a fly - Perhaps she'll die!\n")
}
}
sing.call() |
http://rosettacode.org/wiki/Ordered_words | Ordered words | An ordered word is a word in which the letters appear in alphabetic order.
Examples include abbey and dirt.
Task[edit]
Find and display all the ordered words in the dictionary unixdict.txt that have the longest word length.
(Examples that access the dictionary file locally assume that you have downloaded this file yourself.)
The display needs to be shown on this page.
Related tasks
Word plays
Ordered words
Palindrome detection
Semordnilap
Anagrams
Anagrams/Deranged anagrams
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Swift | Swift | import Foundation
guard
let url = NSURL(string: "http://www.puzzlers.org/pub/wordlists/unixdict.txt"),
let input = try? NSString(contentsOfURL: url,encoding: NSUTF8StringEncoding) as String
else { exit(EXIT_FAILURE) }
let words = input.componentsSeparatedByCharactersInSet(NSCharacterSet.newlineCharacterSet())
let group: ([Int: [String]], String) -> [Int: [String]] = {
var d = $0; let g = d[$1.characters.count] ?? []
d[$1.characters.count] = g + [$1]
return d
}
let ordered: ([String], String) -> [String] = {
guard String($1.characters.sort()) == $1 else { return $0 }
return $0 + [$1]
}
let groups = words
.reduce([String](), combine: ordered)
.reduce([Int: [String]](), combine: group)
guard
let maxLength = groups.keys.maxElement(),
let maxLengthGroup = groups[maxLength]
else { exit(EXIT_FAILURE) }
maxLengthGroup.forEach { print($0) }
|
http://rosettacode.org/wiki/Ordered_words | Ordered words | An ordered word is a word in which the letters appear in alphabetic order.
Examples include abbey and dirt.
Task[edit]
Find and display all the ordered words in the dictionary unixdict.txt that have the longest word length.
(Examples that access the dictionary file locally assume that you have downloaded this file yourself.)
The display needs to be shown on this page.
Related tasks
Word plays
Ordered words
Palindrome detection
Semordnilap
Anagrams
Anagrams/Deranged anagrams
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Tcl | Tcl | package require http
# Pick the ordered words (of maximal length) from a list
proc chooseOrderedWords list {
set len 0
foreach word $list {
# Condition to determine whether a word is ordered; are its characters
# in sorted order?
if {$word eq [join [lsort [split $word ""]] ""]} {
if {[string length $word] > $len} {
set len [string length $word]
set orderedOfMaxLen {}
}
if {[string length $word] == $len} {
lappend orderedOfMaxLen $word
}
}
}
return $orderedOfMaxLen
}
# Get the dictionary and print the ordered words from it
set t [http::geturl "http://www.puzzlers.org/pub/wordlists/unixdict.txt"]
puts [chooseOrderedWords [http::data $t]]
http::cleanup $t |
http://rosettacode.org/wiki/Palindrome_detection | Palindrome detection | A palindrome is a phrase which reads the same backward and forward.
Task[edit]
Write a function or program that checks whether a given sequence of characters (or, if you prefer, bytes)
is a palindrome.
For extra credit:
Support Unicode characters.
Write a second function (possibly as a wrapper to the first) which detects inexact palindromes, i.e. phrases that are palindromes if white-space and punctuation is ignored and case-insensitive comparison is used.
Hints
It might be useful for this task to know how to reverse a string.
This task's entries might also form the subjects of the task Test a function.
Related tasks
Word plays
Ordered words
Palindrome detection
Semordnilap
Anagrams
Anagrams/Deranged anagrams
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
| #TypeScript | TypeScript | const detectNonLetterRegexp=/[^A-ZÀ-ÞЀ-Я]/g;
function stripDiacritics(phrase:string){
return phrase.normalize('NFD').replace(/[\u0300-\u036f]/g, "")
}
function isPalindrome(phrase:string){
const TheLetters = stripDiacritics(phrase.toLocaleUpperCase().replace(detectNonLetterRegexp, ''));
const middlePosition = TheLetters.length/2;
const leftHalf = TheLetters.substr(0, middlePosition);
const rightReverseHalf = TheLetters.substr(-middlePosition).split('').reverse().join('');
return leftHalf == rightReverseHalf;
}
console.log(isPalindrome('Sueño que esto no es un palíndromo'))
console.log(isPalindrome('Dábale arroz a la zorra el abad!'))
console.log(isPalindrome('Я иду с мечем судия'))
|
http://rosettacode.org/wiki/Number_names | Number names | Task
Show how to spell out a number in English.
You can use a preexisting implementation or roll your own, but you should support inputs up to at least one million (or the maximum value of your language's default bounded integer type, if that's less).
Support for inputs other than positive integers (like zero, negative integers, and floating-point numbers) is optional.
Related task
Spelling of ordinal numbers.
| #Inform_7 | Inform 7 | say 32767 in words; |
http://rosettacode.org/wiki/Number_reversal_game | Number reversal game | Task
Given a jumbled list of the numbers 1 to 9 that are definitely not in
ascending order.
Show the list, and then ask the player how many digits from the
left to reverse.
Reverse those digits, then ask again, until all the digits end up in ascending order.
The score is the count of the reversals needed to attain the ascending order.
Note: Assume the player's input does not need extra validation.
Related tasks
Sorting algorithms/Pancake sort
Pancake sorting.
Topswops
| #Icon_and_Unicon | Icon and Unicon | procedure main(cq) # Number Reversal Game
local x,nums,R,flips
$define PROTECT ["WIN","ASK"]
$define MAGIC ["xyzzy","abracadabra","hocus","pocus","presto","changeo","open","sesame","irs"]
put(cq,"game") # start command queue - use command line
rule := string(&digits--'0') # ruler and move commands
every put(protected := [], map(!PROTECT)) # protected commands
every put(magic := [], !MAGIC)
while x := get(cq) | "MOVE" do { # command from queue or ask for move
case x of {
"help" | "h" | "?" : # --- start of user facing commands ---
write("Input a position. The list will be flipped left to right at that point.\n",
"You win when the list is sorted.\n",
"Commands:\n",
" help, h, ? - shows this\n",
" new, g - new game\n",
" ruler, r - shows a ruler\n",
" show, s - shows the list\n",
" <n> - flips the list at ruler position n\n",
" quit, q - quit\n",
"and various magic words.\n"
) & put(cq,"rule")
"game" | "g" | "new" : {
put(cq,"help")
flips := 0
nums := rule
until nums ~== rule do
every !nums :=: ?nums # shuffle
}
"rule" | "ruler" | "r" :
put(cq,"show") & every writes(" " || " " | !(if /mirror then rule else reverse(rule)) | "\n")
"show" | "s" :
every writes(" " || "=" | !nums | " =\n")
!rule : { # 0 - 9 for flipping
if /mirror then nums[1+:x] := reverse(nums[1+:x])
else nums[0-:x] := reverse(nums[0-:x])
flips +:= 1
put(cq,if nums == rule then "WIN" else "show")
}
"quit" | "q" :
break write("Goodbye.")
!magic: # --- start of magic
write("That has no power here. Try again!")
"magic" | "mirror" | "m" : {
mirror := if /mirror then 1 else &null
write("Wait! What is this? The writing has reversed.")
}
!protected: # --- Start of internal (upper case) and protected commands
put(cq,?rule) & write("Tisk, Tisk, don't try and cheat. Take a random penalty flip!")
"MOVE" :
put(cq,ask("Command? : ") )
"WIN" :
put(cq,"ASK") & write("Congratulations you won in ",flips," flips!")
"ASK" :
put(cq,case ask("Play another game? : ") of { "y"|"yes" : "game"; "n"|"no" : "quit"; default : "ASK" } )
default: # --- say what?
write("Sorry I don't know that command, try help?")
}
}
end
procedure ask(s) #: ask for input with prompt s and return the 1st word in lower case
writes(\s)
map(trim(read())) ? return tab(upto(' ')|0)
end
|
http://rosettacode.org/wiki/Null_object | Null object |
Null (or nil) is the computer science concept of an undefined or unbound object.
Some languages have an explicit way to access the null object, and some don't.
Some languages distinguish the null object from undefined values, and some don't.
Task
Show how to access null in your language by checking to see if an object is equivalent to the null object.
This task is not about whether a variable is defined. The task is about "null"-like values in various languages, which may or may not be related to the defined-ness of variables in your language.
| #Objeck | Objeck |
# here "object" is a reference
if(object = Nil) {
"object is null"->PrintLine();
};
|
http://rosettacode.org/wiki/Null_object | Null object |
Null (or nil) is the computer science concept of an undefined or unbound object.
Some languages have an explicit way to access the null object, and some don't.
Some languages distinguish the null object from undefined values, and some don't.
Task
Show how to access null in your language by checking to see if an object is equivalent to the null object.
This task is not about whether a variable is defined. The task is about "null"-like values in various languages, which may or may not be related to the defined-ness of variables in your language.
| #Objective-C | Objective-C | // here "object" is an object pointer
if (object == nil) {
NSLog("object is nil");
} |
http://rosettacode.org/wiki/One-dimensional_cellular_automata | One-dimensional cellular automata | Assume an array of cells with an initial distribution of live and dead cells,
and imaginary cells off the end of the array having fixed values.
Cells in the next generation of the array are calculated based on the value of the cell and its left and right nearest neighbours in the current generation.
If, in the following table, a live cell is represented by 1 and a dead cell by 0 then to generate the value of the cell at a particular index in the array of cellular values you use the following table:
000 -> 0 #
001 -> 0 #
010 -> 0 # Dies without enough neighbours
011 -> 1 # Needs one neighbour to survive
100 -> 0 #
101 -> 1 # Two neighbours giving birth
110 -> 1 # Needs one neighbour to survive
111 -> 0 # Starved to death.
| #MATLAB_.2F_Octave | MATLAB / Octave | function one_dim_cell_automata(v,n)
V='_#';
while n>=0;
disp(V(v+1));
n = n-1;
v = filter([1,1,1],1,[0,v,0]);
v = v(3:end)==2;
end;
end |
http://rosettacode.org/wiki/Numerical_integration | Numerical integration | Write functions to calculate the definite integral of a function ƒ(x) using all five of the following methods:
rectangular
left
right
midpoint
trapezium
Simpson's
composite
Your functions should take in the upper and lower bounds (a and b), and the number of approximations to make in that range (n).
Assume that your example already has a function that gives values for ƒ(x) .
Simpson's method is defined by the following pseudo-code:
Pseudocode: Simpson's method, composite
procedure quad_simpson_composite(f, a, b, n)
h := (b - a) / n
sum1 := f(a + h/2)
sum2 := 0
loop on i from 1 to (n - 1)
sum1 := sum1 + f(a + h * i + h/2)
sum2 := sum2 + f(a + h * i)
answer := (h / 6) * (f(a) + f(b) + 4*sum1 + 2*sum2)
Demonstrate your function by showing the results for:
ƒ(x) = x3, where x is [0,1], with 100 approximations. The exact result is 0.25 (or 1/4)
ƒ(x) = 1/x, where x is [1,100], with 1,000 approximations. The exact result is 4.605170+ (natural log of 100)
ƒ(x) = x, where x is [0,5000], with 5,000,000 approximations. The exact result is 12,500,000
ƒ(x) = x, where x is [0,6000], with 6,000,000 approximations. The exact result is 18,000,000
See also
Active object for integrating a function of real time.
Special:PrefixIndex/Numerical integration for other integration methods.
| #Perl | Perl | use feature 'say';
sub leftrect {
my($func, $a, $b, $n) = @_;
my $h = ($b - $a) / $n;
my $sum = 0;
for ($_ = $a; $_ < $b; $_ += $h) { $sum += $func->($_) }
$h * $sum
}
sub rightrect {
my($func, $a, $b, $n) = @_;
my $h = ($b - $a) / $n;
my $sum = 0;
for ($_ = $a+$h; $_ < $b+$h; $_ += $h) { $sum += $func->($_) }
$h * $sum
}
sub midrect {
my($func, $a, $b, $n) = @_;
my $h = ($b - $a) / $n;
my $sum = 0;
for ($_ = $a + $h/2; $_ < $b; $_ += $h) { $sum += $func->($_) }
$h * $sum
}
sub trapez {
my($func, $a, $b, $n) = @_;
my $h = ($b - $a) / $n;
my $sum = $func->($a) + $func->($b);
for ($_ = $a+$h; $_ < $b; $_ += $h) { $sum += 2 * $func->($_) }
$h/2 * $sum
}
sub simpsons {
my($func, $a, $b, $n) = @_;
my $h = ($b - $a) / $n;
my $h2 = $h/2;
my $sum1 = $func->($a + $h2);
my $sum2 = 0;
for ($_ = $a+$h; $_ < $b; $_ += $h) {
$sum1 += $func->($_ + $h2);
$sum2 += $func->($_);
}
$h/6 * ($func->($a) + $func->($b) + 4*$sum1 + 2*$sum2)
}
# round where needed, display in a reasonable format
sub sig {
my($value) = @_;
my $rounded;
if ($value < 10) {
$rounded = sprintf '%.6f', $value;
$rounded =~ s/(\.\d*[1-9])0+$/$1/;
$rounded =~ s/\.0+$//;
} else {
$rounded = sprintf "%.1f", $value;
$rounded =~ s/\.0+$//;
}
return $rounded;
}
sub integrate {
my($func, $a, $b, $n, $exact) = @_;
my $f = sub { local $_ = shift; eval $func };
my @res;
push @res, "$func\n in [$a..$b] / $n";
push @res, ' exact result: ' . rnd($exact);
push @res, ' rectangle method left: ' . rnd( leftrect($f, $a, $b, $n));
push @res, ' rectangle method right: ' . rnd(rightrect($f, $a, $b, $n));
push @res, ' rectangle method mid: ' . rnd( midrect($f, $a, $b, $n));
push @res, 'composite trapezoidal rule: ' . rnd( trapez($f, $a, $b, $n));
push @res, ' quadratic simpsons rule: ' . rnd( simpsons($f, $a, $b, $n));
@res;
}
say for integrate('$_ ** 3', 0, 1, 100, 0.25); say '';
say for integrate('1 / $_', 1, 100, 1000, log(100)); say '';
say for integrate('$_', 0, 5_000, 5_000_000, 12_500_000); say '';
say for integrate('$_', 0, 6_000, 6_000_000, 18_000_000); |
http://rosettacode.org/wiki/Old_lady_swallowed_a_fly | Old lady swallowed a fly | Task
Present a program which emits the lyrics to the song I Knew an Old Lady Who Swallowed a Fly, taking advantage of the repetitive structure of the song's lyrics.
This song has multiple versions with slightly different lyrics, so all these programs might not emit identical output.
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
PrintChar equ &BB5A
org &8000
ld ix,VerseTable
ld iy,OldLadyLookup
ld b,8 ;8 verses total
outerloop_song:
push bc
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
;bc = the memory location of Verse1
call loop_meta_PrintString
inc ix
inc ix ;next verse
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
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; SUBROUTINES ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
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
inc bc ;advance past "There was an old lady who..."
jp loop_meta_PrintString
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
PrintString:
ld a,(hl)
or a
ret z
call PrintChar
inc hl
jr PrintString
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; DATA ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
VerseTable:
word Verse1,Verse2,Verse3,Verse4,Verse5,Verse6,Verse7,Verse8
Verse1:
byte 2,4,40,6,40,0 ;fly
Verse2:
byte 2,8,40,10,40,36,8,38,255 ;spider
word Verse1
Verse3:
byte 2,12,40,14,40,36,12,38,255 ;bird
word Verse2
Verse4:
byte 2,16,40,18,40,36,16,38,255 ;cat
word Verse3
Verse5:
byte 2,20,40,22,40,36,20,38,255 ;dog
word Verse4
Verse6:
byte 2,24,40,26,40,36,24,38,255 ;goat
word Verse5
Verse7:
byte 2,28,40,30,40,36,28,38,255 ;cow
word Verse6
Verse8:
byte 2,32,40,34,0 ;horse
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
OldLadyLookup:
word null ;0
word OldLady ;2
word Fly ;4
word Fly2 ;6
word Spider ;8
word Spider2 ;10
word Bird ;12
word Bird2 ;14
word Cat ;16
word Cat2 ;18
word Dog ;20
word Dog2 ;22
word Goat ;24
word Goat2 ;26
word Cow ;28
word Cow2 ;30
word Horse ;32
word Horse2 ;34
word Catch1 ;36
word Catch2 ;38
word Song_NewLine ;40
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
null:
byte 0
OldLady:
byte "There was an old lady who swallowed a ",0
Fly:
byte "fly",0
Fly2:
byte "I don't know why she swallowed a fly, perhaps she'll die.",0
Spider:
byte "spider",0
Spider2:
byte "It wiggled and jiggled and tickled inside her.",0
Bird:
byte "bird",0
Bird2:
byte "How absurd, to swallow a bird.",0
Cat:
byte "cat",0
Cat2:
byte "Imagine that, she swallowed a cat.",0
Dog:
byte "dog",0
Dog2:
byte "What a hog, to swallow a dog.",0
Goat:
byte "goat",0
Goat2:
byte "She just opened her throat and swallowed a goat.",0
Cow:
byte "cow",0
Cow2:
byte "I don't know how she swallowed a cow.",0
Horse:
byte "horse",0
Horse2:
byte "She's dead, of course.",0
Catch1:
byte "She swallowed the ",0
Catch2:
byte " to catch the ",0
Song_NewLine:
byte 13,10,0 ;control codes for a new line. |
http://rosettacode.org/wiki/Ordered_words | Ordered words | An ordered word is a word in which the letters appear in alphabetic order.
Examples include abbey and dirt.
Task[edit]
Find and display all the ordered words in the dictionary unixdict.txt that have the longest word length.
(Examples that access the dictionary file locally assume that you have downloaded this file yourself.)
The display needs to be shown on this page.
Related tasks
Word plays
Ordered words
Palindrome detection
Semordnilap
Anagrams
Anagrams/Deranged anagrams
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
| #TUSCRIPT | TUSCRIPT |
$$ MODE TUSCRIPT
SET data = REQUEST ("http://www.puzzlers.org/pub/wordlists/unixdict.txt")
DICT orderdwords CREATE 99999
COMPILE
LOOP word=data
- "<%" = any token
SET letters=STRINGS (word,":<%:")
SET wordsignatur= ALPHA_SORT (letters)
IF (wordsignatur==letters) THEN
SET wordlength=LENGTH (word)
DICT orderdwords ADD/COUNT word,num,cnt,wordlength
ENDIF
ENDLOOP
DICT orderdwords UNLOAD words,num,cnt,wordlength
SET maxlength=MAX_LENGTH (words)
SET rtable=QUOTES (maxlength)
BUILD R_TABLE maxlength = rtable
SET index=FILTER_INDEX (wordlength,maxlength,-)
SET longestwords=SELECT (words,#index)
PRINT num," ordered words - max length is ",maxlength,":"
LOOP n,w=longestwords
SET n=CONCAT (n,"."), n=CENTER(n,4)
PRINT n,w
ENDLOOP
ENDCOMPILE
|
http://rosettacode.org/wiki/Palindrome_detection | Palindrome detection | A palindrome is a phrase which reads the same backward and forward.
Task[edit]
Write a function or program that checks whether a given sequence of characters (or, if you prefer, bytes)
is a palindrome.
For extra credit:
Support Unicode characters.
Write a second function (possibly as a wrapper to the first) which detects inexact palindromes, i.e. phrases that are palindromes if white-space and punctuation is ignored and case-insensitive comparison is used.
Hints
It might be useful for this task to know how to reverse a string.
This task's entries might also form the subjects of the task Test a function.
Related tasks
Word plays
Ordered words
Palindrome detection
Semordnilap
Anagrams
Anagrams/Deranged anagrams
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #UNIX_Shell | UNIX Shell | if [[ "${text}" == "$(rev <<< "${text}")" ]]; then
echo "Palindrome"
else
echo "Not a palindrome"
fi |
http://rosettacode.org/wiki/Number_names | Number names | Task
Show how to spell out a number in English.
You can use a preexisting implementation or roll your own, but you should support inputs up to at least one million (or the maximum value of your language's default bounded integer type, if that's less).
Support for inputs other than positive integers (like zero, negative integers, and floating-point numbers) is optional.
Related task
Spelling of ordinal numbers.
| #J | J | u=. ;:'one two three four five six seven eight nine'
v=. ;:'ten eleven twelve thirteen fourteen fifteen sixteen seventeen eighteen nineteen'
t=. ;:'twenty thirty forty fifty sixty seventy eighty ninety'
EN100=: '' ; u , v , , t ,&.>/ '';'-',&.>u
z=. '' ; 'thousand' ; (;:'m b tr quadr quint sext sept oct non'),&.> <'illion'
u=. ;:'un duo tre quattuor quin sex septen octo novem'
t=. (;:'dec vigint trigint quadragint quinquagint sexagint septuagint octogint nonagint'),&.><'illion'
ENU=: z , (, t ,~&.>/ '';u) , <'centillion'
en3=: 4 : 0
'p q'=. 0 100#:y
(p{::EN100),((*p)#' hundred'),((p*&*q)#x),q{::EN100
)
en=: 4 : 0
d=. 1000&#.^:_1 y
assert. (0<:y) *. ((=<.)y) *. d <:&# ENU
c=. x&en3&.> (*d)#d
((0=y)#'zero') , (-2+*{:d) }. ; , c,.(<' '),.(ENU{~I.&.|.*d),.<', '
)
uk=: ' and '&en NB. British
us=: ' ' &en NB. American |
http://rosettacode.org/wiki/Number_reversal_game | Number reversal game | Task
Given a jumbled list of the numbers 1 to 9 that are definitely not in
ascending order.
Show the list, and then ask the player how many digits from the
left to reverse.
Reverse those digits, then ask again, until all the digits end up in ascending order.
The score is the count of the reversals needed to attain the ascending order.
Note: Assume the player's input does not need extra validation.
Related tasks
Sorting algorithms/Pancake sort
Pancake sorting.
Topswops
| #Inform_7 | Inform 7 | Number Reversal Game is a room.
The current list is a list of numbers that varies.
When play begins:
now the current list is a shuffled list from 1 to 9;
now the command prompt is "Current list: [current list in brace notation].[line break]How many items to flip? ".
Definition: a list of numbers (called L) is sorted:
repeat with N running from 1 to the number of entries in L:
if entry N in L is not N, no;
yes.
To decide which list of numbers is a shuffled list from (min - number) to (max - number):
let result be a list of numbers;
repeat with N running from min to max:
add N to result;
while true is true:
sort result in random order;
if result is not sorted, decide on result.
Flipping is an action applying to one number. Understand "[number]" as flipping.
Carry out flipping:
let N be the number understood;
let L be the current list;
truncate the current list to the first N entries;
reverse the current list;
truncate L to the last (number of entries in L minus N) entries;
add L to the current list.
Report flipping: say "".
Every turn:
if the current list is sorted, end the story saying "You have won".
This is the new print final score rule:
say "It took you [turn count] flip[s] to sort the list."
The new print final score rule is listed instead of the print final score rule in the for printing the player's obituary rules. |
http://rosettacode.org/wiki/Null_object | Null object |
Null (or nil) is the computer science concept of an undefined or unbound object.
Some languages have an explicit way to access the null object, and some don't.
Some languages distinguish the null object from undefined values, and some don't.
Task
Show how to access null in your language by checking to see if an object is equivalent to the null object.
This task is not about whether a variable is defined. The task is about "null"-like values in various languages, which may or may not be related to the defined-ness of variables in your language.
| #OCaml | OCaml | type 'a option = None | Some of 'a |
http://rosettacode.org/wiki/Null_object | Null object |
Null (or nil) is the computer science concept of an undefined or unbound object.
Some languages have an explicit way to access the null object, and some don't.
Some languages distinguish the null object from undefined values, and some don't.
Task
Show how to access null in your language by checking to see if an object is equivalent to the null object.
This task is not about whether a variable is defined. The task is about "null"-like values in various languages, which may or may not be related to the defined-ness of variables in your language.
| #Oforth | Oforth | null isNull
"abcd" isNull
: testNull { | a | a ifNull: [ "Variable value is null" println ] ; |
http://rosettacode.org/wiki/One-dimensional_cellular_automata | One-dimensional cellular automata | Assume an array of cells with an initial distribution of live and dead cells,
and imaginary cells off the end of the array having fixed values.
Cells in the next generation of the array are calculated based on the value of the cell and its left and right nearest neighbours in the current generation.
If, in the following table, a live cell is represented by 1 and a dead cell by 0 then to generate the value of the cell at a particular index in the array of cellular values you use the following table:
000 -> 0 #
001 -> 0 #
010 -> 0 # Dies without enough neighbours
011 -> 1 # Needs one neighbour to survive
100 -> 0 #
101 -> 1 # Two neighbours giving birth
110 -> 1 # Needs one neighbour to survive
111 -> 0 # Starved to death.
| #Modula-3 | Modula-3 | MODULE Cell EXPORTS Main;
IMPORT IO, Fmt, Word;
VAR culture := ARRAY [0..19] OF INTEGER {0, 1, 1, 1,
0, 1, 1, 0,
1, 0, 1, 0,
1, 0, 1, 0,
0, 1, 0, 0};
PROCEDURE Step(VAR culture: ARRAY OF INTEGER) =
VAR left: INTEGER := 0;
this, right: INTEGER;
BEGIN
FOR i := FIRST(culture) TO LAST(culture) - 1 DO
right := culture[i + 1];
this := culture[i];
culture[i] :=
Word.Or(Word.And(this, Word.Xor(left, right)), Word.And(Word.Not(this), Word.And(left, right)));
left := this;
END;
culture[LAST(culture)] := Word.And(culture[LAST(culture)], Word.Not(left));
END Step;
PROCEDURE Put(VAR culture: ARRAY OF INTEGER) =
BEGIN
FOR i := FIRST(culture) TO LAST(culture) DO
IF culture[i] = 1 THEN
IO.PutChar('#');
ELSE
IO.PutChar('_');
END;
END;
END Put;
BEGIN
FOR i := 0 TO 9 DO
IO.Put("Generation " & Fmt.Int(i) & " ");
Put(culture);
IO.Put("\n");
Step(culture);
END;
END Cell. |
http://rosettacode.org/wiki/Numerical_integration | Numerical integration | Write functions to calculate the definite integral of a function ƒ(x) using all five of the following methods:
rectangular
left
right
midpoint
trapezium
Simpson's
composite
Your functions should take in the upper and lower bounds (a and b), and the number of approximations to make in that range (n).
Assume that your example already has a function that gives values for ƒ(x) .
Simpson's method is defined by the following pseudo-code:
Pseudocode: Simpson's method, composite
procedure quad_simpson_composite(f, a, b, n)
h := (b - a) / n
sum1 := f(a + h/2)
sum2 := 0
loop on i from 1 to (n - 1)
sum1 := sum1 + f(a + h * i + h/2)
sum2 := sum2 + f(a + h * i)
answer := (h / 6) * (f(a) + f(b) + 4*sum1 + 2*sum2)
Demonstrate your function by showing the results for:
ƒ(x) = x3, where x is [0,1], with 100 approximations. The exact result is 0.25 (or 1/4)
ƒ(x) = 1/x, where x is [1,100], with 1,000 approximations. The exact result is 4.605170+ (natural log of 100)
ƒ(x) = x, where x is [0,5000], with 5,000,000 approximations. The exact result is 12,500,000
ƒ(x) = x, where x is [0,6000], with 6,000,000 approximations. The exact result is 18,000,000
See also
Active object for integrating a function of real time.
Special:PrefixIndex/Numerical integration for other integration methods.
| #Phix | Phix | function rect_left(integer rid, atom x, atom /*h*/)
return rid(x)
end function
function rect_mid(integer rid, atom x, atom h)
return rid(x+h/2)
end function
function rect_right(integer rid, atom x, atom h)
return rid(x+h)
end function
function trapezium(integer rid, atom x, atom h)
return (rid(x)+rid(x+h))/2
end function
function simpson(integer rid, atom x, atom h)
return (rid(x)+4*rid(x+h/2)+rid(x+h))/6
end function
function cubed(atom x)
return power(x,3)
end function
function recip(atom x)
return 1/x
end function
function ident(atom x)
return x
end function
function integrate(integer m_id, integer f_id, atom a, atom b, integer steps)
atom accum = 0,
h = (b-a)/steps
for i=0 to steps-1 do
accum += m_id(f_id,a+h*i,h)
end for
return h*accum
end function
function smartp(atom N)
if N=floor(N) then return sprintf("%d",N) end if
string res = sprintf("%12f",round(N,1000000))
if find('.',res) then
res = trim_tail(res,"0")
res = trim_tail(res,".")
end if
return res
end function
procedure test(sequence tests)
string name
atom a, b, steps, rid
printf(1,"Function Range Iterations L-Rect M-Rect R-Rect Trapeze Simpson\n")
for i=1 to length(tests) do
{name,a,b,steps,rid} = tests[i]
printf(1," %-5s %6d - %-5d %10d %12s %12s %12s %12s %12s\n",{name,a,b,steps,
smartp(integrate(rect_left, rid,a,b,steps)),
smartp(integrate(rect_mid, rid,a,b,steps)),
smartp(integrate(rect_right,rid,a,b,steps)),
smartp(integrate(trapezium, rid,a,b,steps)),
smartp(integrate(simpson, rid,a,b,steps))})
end for
end procedure
constant tests = {{"x^3", 0, 1, 100, cubed},
{"1/x", 1, 100, 1000, recip},
{"x", 0, 5000, 5000000, ident},
{"x", 0, 6000, 6000000, ident}}
test(tests)
|
http://rosettacode.org/wiki/Old_lady_swallowed_a_fly | Old lady swallowed a fly | Task
Present a program which emits the lyrics to the song I Knew an Old Lady Who Swallowed a Fly, taking advantage of the repetitive structure of the song's lyrics.
This song has multiple versions with slightly different lyrics, so all these programs might not emit identical output.
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 | var ZLib=Import("zeelib"), MsgHash=Import("zklMsgHash");
text:=
"eJztlE1uwyAQhdflFOOVNyhXyLap1FV7AWKIoaFMBFjIt++M7YVpLfVHilQp2cHMg3l8T+IA"
"54AFVAD0GrzSIxSLkIryHovRoODkRykOoDG0eVYXO0KyZqXKtFt0/WBS4nbrPWhndoKK3w5J"
"F6dNlA/i1aoMJbq+99wIGt5W6+y6M69dSKQHa+JOvHxxMl8GGaFTubNrd9d9xdFFLcUjq45p"
"iJotLP2l22zY5XptdqHxaxjyP8GgcXT4XfUuGLqNdjUO6m/RoHJtdoZ6M9g09lI8j5Ia9AoF"
"lvY1OFJsgaNybXcK4LYA/4Bvj4zlaUgZ8GIC1SzbsBEZN9n/LN5izfXa+hTbPZQ/fxZY+HDB"
"wPMtqesBk2K/+V+QtvI7B3zP7OqZWYzJTI7aBNooLQFPlMdA5aYRH3dS5jc=";
MsgHash.base64decode(text) :
ZLib.Inflator().write(_).close().read().text.println(); |
http://rosettacode.org/wiki/Ordered_words | Ordered words | An ordered word is a word in which the letters appear in alphabetic order.
Examples include abbey and dirt.
Task[edit]
Find and display all the ordered words in the dictionary unixdict.txt that have the longest word length.
(Examples that access the dictionary file locally assume that you have downloaded this file yourself.)
The display needs to be shown on this page.
Related tasks
Word plays
Ordered words
Palindrome detection
Semordnilap
Anagrams
Anagrams/Deranged anagrams
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
| #Ursala | Ursala | #import std
#show+
main = leql@bh$^ eql|= (ordered lleq)*~ unixdict_dot_txt |
http://rosettacode.org/wiki/Ordered_words | Ordered words | An ordered word is a word in which the letters appear in alphabetic order.
Examples include abbey and dirt.
Task[edit]
Find and display all the ordered words in the dictionary unixdict.txt that have the longest word length.
(Examples that access the dictionary file locally assume that you have downloaded this file yourself.)
The display needs to be shown on this page.
Related tasks
Word plays
Ordered words
Palindrome detection
Semordnilap
Anagrams
Anagrams/Deranged anagrams
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 |
Public Sub orderedwords(fname As String)
' find ordered words in dict file that have the longest word length
' fname is the name of the input file
' the words are printed in the immediate window
' this subroutine uses boolean function IsOrdered
Dim word As String 'word to be tested
Dim l As Integer 'length of word
Dim wordlength As Integer 'current longest word length
Dim orderedword() As String 'dynamic array holding the ordered words with the current longest word length
Dim wordsfound As Integer 'length of the array orderedword()
On Error GoTo NotFound 'catch incorrect/missing file name
Open fname For Input As #1
On Error GoTo 0
'initialize
wordsfound = 0
wordlength = 0
'process file line per line
While Not EOF(1)
Line Input #1, word
If IsOrdered(word) Then 'found one, is it equal to or longer than current word length?
l = Len(word)
If l >= wordlength Then 'yes, so add to list or start a new list
If l > wordlength Then 'it's longer, we must start a new list
wordsfound = 1
wordlength = l
Else 'equal length, increase the list size
wordsfound = wordsfound + 1
End If
'add the word to the list
ReDim Preserve orderedword(wordsfound)
orderedword(wordsfound) = word
End If
End If
Wend
Close #1
'print the list
Debug.Print "Found"; wordsfound; "ordered words of length"; wordlength
For i = 1 To wordsfound
Debug.Print orderedword(i)
Next
Exit Sub
NotFound:
debug.print "Error: Cannot find or open file """ & fname & """!"
End Sub
Public Function IsOrdered(someWord As String) As Boolean
'true if letters in word are in ascending (ascii) sequence
Dim l As Integer 'length of someWord
Dim wordLcase As String 'the word in lower case
Dim ascStart As Integer 'ascii code of first char
Dim asc2 As Integer 'ascii code of next char
wordLcase = LCase(someWord) 'convert to lower case
l = Len(someWord)
IsOrdered = True
If l > 0 Then 'this skips empty string - it is considered ordered...
ascStart = Asc(Left$(wordLcase, 1))
For i = 2 To l
asc2 = Asc(Mid$(wordLcase, i, 1))
If asc2 < ascStart Then 'failure!
IsOrdered = False
Exit Function
End If
ascStart = asc2
Next i
End If
End Function
|
http://rosettacode.org/wiki/Palindrome_detection | Palindrome detection | A palindrome is a phrase which reads the same backward and forward.
Task[edit]
Write a function or program that checks whether a given sequence of characters (or, if you prefer, bytes)
is a palindrome.
For extra credit:
Support Unicode characters.
Write a second function (possibly as a wrapper to the first) which detects inexact palindromes, i.e. phrases that are palindromes if white-space and punctuation is ignored and case-insensitive comparison is used.
Hints
It might be useful for this task to know how to reverse a string.
This task's entries might also form the subjects of the task Test a function.
Related tasks
Word plays
Ordered words
Palindrome detection
Semordnilap
Anagrams
Anagrams/Deranged anagrams
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
| #Ursala | Ursala | #import std
palindrome = ~&cixE\letters+ * -:~& ~=`A-~rlp letters |
http://rosettacode.org/wiki/Number_names | Number names | Task
Show how to spell out a number in English.
You can use a preexisting implementation or roll your own, but you should support inputs up to at least one million (or the maximum value of your language's default bounded integer type, if that's less).
Support for inputs other than positive integers (like zero, negative integers, and floating-point numbers) is optional.
Related task
Spelling of ordinal numbers.
| #Java | Java | public enum IntToWords {
;
private static final String[] small = {
"", "one", "two", "three", "four",
"five", "six", "seven", "eight", "nine",
"ten", "eleven", "twelve", "thirteen", "fourteen",
"fifteen", "sixteen", "seventeen", "eighteen", "nineteen"};
private static final String[] tens = {
"", "", "twenty", "thirty", "forty",
"fifty", "sixty", "seventy", "eighty", "ninety"};
private static final String[] big = {
"", "thousand", "million", "billion", "trillion",
"quadrillion", "quintillion"};
public static void main(String[] args) {
System.out.println(int2Text(0));
System.out.println(int2Text(10));
System.out.println(int2Text(30));
System.out.println(int2Text(47));
System.out.println(int2Text(100));
System.out.println(int2Text(999));
System.out.println(int2Text(1000));
System.out.println(int2Text(9999));
System.out.println(int2Text(123_456));
System.out.println(int2Text(900_000_001));
System.out.println(int2Text(1_234_567_890));
System.out.println(int2Text(-987_654_321));
System.out.println(int2Text(Long.MAX_VALUE));
System.out.println(int2Text(Long.MIN_VALUE));
}
public static String int2Text(long number) {
StringBuilder sb = new StringBuilder();
if (number == 0) {
return "zero";
}
long num = -Math.abs(number);
int unit = 1;
while (true) {
int rem100 = (int) -(num % 100);
if (rem100 >= 20) {
if (rem100 % 10 == 0) {
sb.insert(0, tens[rem100 / 10] + " ");
} else {
sb.insert(0, tens[rem100 / 10] + "-" + small[rem100 % 10] + " ");
}
} else if (rem100 != 0) {
sb.insert(0, small[rem100] + " ");
}
int hundreds = (int) -(num % 1000) / 100;
if (hundreds != 0) {
sb.insert(0, small[hundreds] + " hundred ");
}
num /= 1000;
if (num == 0) {
break;
}
int rem1000 = (int) -(num % 1000);
if (rem1000 != 0) {
sb.insert(0, big[unit] + " ");
}
unit++;
}
if (number < 0) {
sb.insert(0, "negative ");
}
return sb.toString().trim();
}
} |
http://rosettacode.org/wiki/Number_reversal_game | Number reversal game | Task
Given a jumbled list of the numbers 1 to 9 that are definitely not in
ascending order.
Show the list, and then ask the player how many digits from the
left to reverse.
Reverse those digits, then ask again, until all the digits end up in ascending order.
The score is the count of the reversals needed to attain the ascending order.
Note: Assume the player's input does not need extra validation.
Related tasks
Sorting algorithms/Pancake sort
Pancake sorting.
Topswops
| #Io | Io | withRange := method( a, z,
Range clone setRange(a,z)
)
sorted := withRange(1,9) asList
numbers := sorted clone shuffle
while( numbers==sorted, numbers = numbers shuffle)
steps :=0
stdin := File standardInput
while( numbers != sorted,
writeln(numbers join(" "))
write("Reverse how many? ")
flipcount := stdin readLine asNumber
withRange(0, ((flipcount-1)/2) floor) foreach( i,
numbers swapIndices(i,flipcount-1-i)
)
steps = steps+1
)
writeln("Done! That took you ", steps, " steps") |
http://rosettacode.org/wiki/Null_object | Null object |
Null (or nil) is the computer science concept of an undefined or unbound object.
Some languages have an explicit way to access the null object, and some don't.
Some languages distinguish the null object from undefined values, and some don't.
Task
Show how to access null in your language by checking to see if an object is equivalent to the null object.
This task is not about whether a variable is defined. The task is about "null"-like values in various languages, which may or may not be related to the defined-ness of variables in your language.
| #Ol | Ol |
if a[i] == .nil then say "Item" i "is missing"
|
Subsets and Splits
Select Specific Languages Codes
Retrieves specific programming language names and codes from training data, providing basic filtering but limited analytical value beyond identifying these particular languages.