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/The_Name_Game | The Name Game | Write a program that accepts a name as input and outputs the lyrics to the Shirley Ellis song "The Name Game".
The regular verse
Unless your name begins with a vowel (A, E, I, O, U), 'B', 'F' or 'M' you don't have to care about special rules.
The verse for the name 'Gary' would be like this:
Gary, Gary, bo-bary
Banana-fana fo-fary
Fee-fi-mo-mary
Gary!
At the end of every line, the name gets repeated without the first letter: Gary becomes ary
If we take (X) as the full name (Gary) and (Y) as the name without the first letter (ary) the verse would look like this:
(X), (X), bo-b(Y)
Banana-fana fo-f(Y)
Fee-fi-mo-m(Y)
(X)!
Vowel as first letter of the name
If you have a vowel as the first letter of your name (e.g. Earl) you do not truncate the name.
The verse looks like this:
Earl, Earl, bo-bearl
Banana-fana fo-fearl
Fee-fi-mo-mearl
Earl!
'B', 'F' or 'M' as first letter of the name
In case of a 'B', an 'F' or an 'M' (e.g. Billy, Felix, Mary) there is a special rule.
The line which would 'rebuild' the name (e.g. bo-billy) is sang without the first letter of the name.
The verse for the name Billy looks like this:
Billy, Billy, bo-illy
Banana-fana fo-filly
Fee-fi-mo-milly
Billy!
For the name 'Felix', this would be right:
Felix, Felix, bo-belix
Banana-fana fo-elix
Fee-fi-mo-melix
Felix!
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #UNIX_Shell | UNIX Shell | #!/usr/bin/env bash
namegame() {
local name=$1 b=b f=f m=m
local rhyme=${name#[^AaEeIiOoUu]}
while [[ $rhyme == [^AaEeIiOoUuYy]* ]]; do
rhyme=${rhyme#?}
done
if [[ "$rhyme" == [AEIOU]* ]]; then
rhyme=$(tr A-Z a-z <<<"$rhyme")
fi
if [[ $name == [Bb]* ]]; then
b=
fi
if [[ $name == [Ff]* ]]; then
f=
fi
if [[ $name == [Mm]* ]]; then
m=
fi
printf '%s, %s, bo-%s%s\n' "$name" "$name" "$b" "$rhyme"
printf 'Banana-fana fo-%s%s\n' "$f" "$rhyme"
printf 'Fee-fi-mo-%s%s\n' "$m" "$rhyme"
printf '%s!\n' "$name"
}
for name in Gary Earl Billy Felix Mark Frank; do
namegame "$name"
echo
done |
http://rosettacode.org/wiki/The_Name_Game | The Name Game | Write a program that accepts a name as input and outputs the lyrics to the Shirley Ellis song "The Name Game".
The regular verse
Unless your name begins with a vowel (A, E, I, O, U), 'B', 'F' or 'M' you don't have to care about special rules.
The verse for the name 'Gary' would be like this:
Gary, Gary, bo-bary
Banana-fana fo-fary
Fee-fi-mo-mary
Gary!
At the end of every line, the name gets repeated without the first letter: Gary becomes ary
If we take (X) as the full name (Gary) and (Y) as the name without the first letter (ary) the verse would look like this:
(X), (X), bo-b(Y)
Banana-fana fo-f(Y)
Fee-fi-mo-m(Y)
(X)!
Vowel as first letter of the name
If you have a vowel as the first letter of your name (e.g. Earl) you do not truncate the name.
The verse looks like this:
Earl, Earl, bo-bearl
Banana-fana fo-fearl
Fee-fi-mo-mearl
Earl!
'B', 'F' or 'M' as first letter of the name
In case of a 'B', an 'F' or an 'M' (e.g. Billy, Felix, Mary) there is a special rule.
The line which would 'rebuild' the name (e.g. bo-billy) is sang without the first letter of the name.
The verse for the name Billy looks like this:
Billy, Billy, bo-illy
Banana-fana fo-filly
Fee-fi-mo-milly
Billy!
For the name 'Felix', this would be right:
Felix, Felix, bo-belix
Banana-fana fo-elix
Fee-fi-mo-melix
Felix!
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 | Option Explicit
Sub Main()
Dim a, r, i As Integer
Const SCHEM As String = "(X), (X), bo-b(Y)^Banana-fana fo-f(Y)^Fee-fi-mo-m(Y)^(X)!^"
'init
a = Array("GaRY", "Earl", "Billy", "Felix", "Mary", "Mike", "Frank")
'compute
r = TheGameName(a, SCHEM)
'return
For i = LBound(r) To UBound(r)
Debug.Print r(i)
Next i
End Sub
Private Function TheGameName(MyArr, S As String) As String()
Dim i As Integer, s1 As String, s2 As String, tp As String, t() As String
ReDim t(UBound(MyArr))
For i = LBound(MyArr) To UBound(MyArr)
tp = Replace(S, "^", vbCrLf)
s2 = LCase(Mid(MyArr(i), 2)): s1 = UCase(Left(MyArr(i), 1)) & s2
Select Case UCase(Left(MyArr(i), 1))
Case "A", "E", "I", "O", "U": tp = Replace(tp, "(Y)", LCase(MyArr(i)))
Case "B", "F", "M"
tp = Replace(tp, "(Y)", s2)
tp = Replace(tp, LCase(MyArr(i)), s2)
Case Else: tp = Replace(tp, "(Y)", s2)
End Select
t(i) = Replace(tp, "(X)", s1)
Next
TheGameName = t
End Function |
http://rosettacode.org/wiki/Textonyms | Textonyms | When entering text on a phone's digital pad it is possible that a particular combination of digits corresponds to more than one word. Such are called textonyms.
Assuming the digit keys are mapped to letters as follows:
2 -> ABC
3 -> DEF
4 -> GHI
5 -> JKL
6 -> MNO
7 -> PQRS
8 -> TUV
9 -> WXYZ
Task
Write a program that finds textonyms in a list of words such as
Textonyms/wordlist or
unixdict.txt.
The task should produce a report:
There are #{0} words in #{1} which can be represented by the digit key mapping.
They require #{2} digit combinations to represent them.
#{3} digit combinations represent Textonyms.
Where:
#{0} is the number of words in the list which can be represented by the digit key mapping.
#{1} is the URL of the wordlist being used.
#{2} is the number of digit combinations required to represent the words in #{0}.
#{3} is the number of #{2} which represent more than one word.
At your discretion show a couple of examples of your solution displaying Textonyms.
E.G.:
2748424767 -> "Briticisms", "criticisms"
Extra credit
Use a word list and keypad mapping other than English.
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 | URL:="http://www.puzzlers.org/pub/wordlists/unixdict.txt";
var ZC=Import("zklCurl");
var keypad=Dictionary(
"a",2,"b",2,"c",2, "d",3,"e",3,"f",3, "g",4,"h",4,"i",4,
"j",5,"k",5,"l",5, "m",6,"n",6,"o",6, "p",7,"q",7,"r",7,"s",7,
"t",8,"u",8,"v",8, "w",9,"x",9,"y",9,"z",9);
//fcn numerate(word){ word.toLower().apply(keypad.find.fp1("")) }
fcn numerate(word){ word.toLower().apply(keypad.get) } //-->textonym or error
println("criticisms --> ",numerate("criticisms"));
words:=ZC().get(URL); //--> T(Data,bytes of header, bytes of trailer)
words=words[0].del(0,words[1]); // remove HTTP header
println("Read %d words from %s".fmt(words.len(1),URL));
wcnt:=Dictionary();
foreach word in (words.walker(11)){ // iterate over stripped lines
w2n:=try{ numerate(word) }catch(NotFoundError){ continue };
wcnt.appendV(w2n,word); // -->[textonym:list of words]
}
moreThan1Word:=wcnt.reduce(fcn(s,[(k,v)]){ s+=(v.len()>1) },0);
maxWordPerNum:=(0).max(wcnt.values.apply("len"));
("There are %d words which can be represented by the Textonyms mapping.\n"
"There are %d overlaps.").fmt(wcnt.len(),moreThan1Word).println();
println("Max collisions: %d words:".fmt(maxWordPerNum));
foreach k,v in (wcnt.filter('wrap([(k,v)]){ v.len()==maxWordPerNum })){
println(" %s is the textonym of: %s".fmt(k,v.concat(", ")));
} |
http://rosettacode.org/wiki/Text_processing/Max_licenses_in_use | Text processing/Max licenses in use | A company currently pays a fixed sum for the use of a particular licensed software package. In determining if it has a good deal it decides to calculate its maximum use of the software from its license management log file.
Assume the software's licensing daemon faithfully records a checkout event when a copy of the software starts and a checkin event when the software finishes to its log file.
An example of checkout and checkin events are:
License OUT @ 2008/10/03_23:51:05 for job 4974
...
License IN @ 2008/10/04_00:18:22 for job 4974
Task
Save the 10,000 line log file from here into a local file, then write a program to scan the file extracting both the maximum licenses that were out at any time, and the time(s) at which this occurs.
Mirror of log file available as a zip here (offsite mirror).
| #Haskell | Haskell |
import Data.List
main = do
f <- readFile "./../Puzzels/Rosetta/inout.txt"
let (ioo,dt) = unzip. map ((\(_:io:_:t:_)-> (io,t)). words) . lines $ f
cio = drop 1 . scanl (\c io -> if io == "IN" then pred c else succ c) 0 $ ioo
mo = maximum cio
putStrLn $ "Maximum simultaneous license use is " ++ show mo ++ " at:"
mapM_ (putStrLn . (dt!!)) . elemIndices mo $ cio
|
http://rosettacode.org/wiki/Test_a_function | Test a function |
Task
Using a well-known testing-specific library/module/suite for your language, write some tests for your language's entry in Palindrome.
If your language does not have a testing specific library well known to the language's community then state this or omit the language.
| #ACL2 | ACL2 | (defun reverse-split-at-r (xs i ys)
(if (zp i)
(mv xs ys)
(reverse-split-at-r (rest xs) (1- i)
(cons (first xs) ys))))
(defun reverse-split-at (xs i)
(reverse-split-at-r xs i nil))
(defun is-palindrome (str)
(let* ((lngth (length str))
(idx (floor lngth 2)))
(mv-let (xs ys)
(reverse-split-at (coerce str 'list) idx)
(if (= (mod lngth 2) 1)
(equal (rest xs) ys)
(equal xs ys)))))
(include-book "testing" :dir :teachpacks)
(check-expect (is-palindrome "abba") t)
(check-expect (is-palindrome "mom") t)
(check-expect (is-palindrome "dennis sinned") t)
(check-expect (is-palindrome "palindrome") nil)
(check-expect (is-palindrome "racecars") nil)
(include-book "doublecheck" :dir :teachpacks)
(defrandom random-palindrome ()
(let ((chars (random-list-of (random-char))))
(coerce (append chars (reverse chars))
'string)))
(defproperty palindrome-test
(p :value (random-palindrome))
(is-palindrome p)) |
http://rosettacode.org/wiki/Text_processing/2 | Text processing/2 | The following task concerns data that came from a pollution monitoring station with twenty-four instruments monitoring twenty-four aspects of pollution in the air. Periodically a record is added to the file, each record being a line of 49 fields separated by white-space, which can be one or more space or tab characters.
The fields (from the left) are:
DATESTAMP [ VALUEn FLAGn ] * 24
i.e. a datestamp followed by twenty-four repetitions of a floating-point instrument value and that instrument's associated integer flag. Flag values are >= 1 if the instrument is working and < 1 if there is some problem with it, in which case that instrument's value should be ignored.
A sample from the full data file readings.txt, which is also used in the Text processing/1 task, follows:
Data is no longer available at that link. Zipped mirror available here
1991-03-30 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1
1991-03-31 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 20.000 1 20.000 1 20.000 1 35.000 1 50.000 1 60.000 1 40.000 1 30.000 1 30.000 1 30.000 1 25.000 1 20.000 1 20.000 1 20.000 1 20.000 1 20.000 1 35.000 1
1991-03-31 40.000 1 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2
1991-04-01 0.000 -2 13.000 1 16.000 1 21.000 1 24.000 1 22.000 1 20.000 1 18.000 1 29.000 1 44.000 1 50.000 1 43.000 1 38.000 1 27.000 1 27.000 1 24.000 1 23.000 1 18.000 1 12.000 1 13.000 1 14.000 1 15.000 1 13.000 1 10.000 1
1991-04-02 8.000 1 9.000 1 11.000 1 12.000 1 12.000 1 12.000 1 27.000 1 26.000 1 27.000 1 33.000 1 32.000 1 31.000 1 29.000 1 31.000 1 25.000 1 25.000 1 24.000 1 21.000 1 17.000 1 14.000 1 15.000 1 12.000 1 12.000 1 10.000 1
1991-04-03 10.000 1 9.000 1 10.000 1 10.000 1 9.000 1 10.000 1 15.000 1 24.000 1 28.000 1 24.000 1 18.000 1 14.000 1 12.000 1 13.000 1 14.000 1 15.000 1 14.000 1 15.000 1 13.000 1 13.000 1 13.000 1 12.000 1 10.000 1 10.000 1
Task
Confirm the general field format of the file.
Identify any DATESTAMPs that are duplicated.
Report the number of records that have good readings for all instruments.
| #Phix | Phix | -- demo\rosetta\TextProcessing2.exw
with javascript_semantics -- (include version/first of next three lines only)
include readings.e -- global constant lines, or:
--assert(write_lines("readings.txt",lines)!=-1) -- first run, then:
--constant lines = read_lines("readings.txt")
include builtins\timedate.e
integer all_good = 0
string fmt = "%d-%d-%d\t"&join(repeat("%f",48),'\t')
sequence extset = sq_mul(tagset(24),2), -- {2,4,6,..48}
curr, last
for i=1 to length(lines) do
string li = lines[i]
sequence r = scanf(li,fmt)
if length(r)!=1 then
printf(1,"bad line [%d]:%s\n",{i,li})
else
curr = r[1][1..3]
if i>1 and curr=last then
printf(1,"duplicate line for %04d/%02d/%02d\n",last)
end if
last = curr
all_good += sum(sq_le(extract(r[1][4..$],extset),0))=0
end if
end for
printf(1,"Valid records %d of %d total\n",{all_good, length(lines)})
?"done"
{} = wait_key()
|
http://rosettacode.org/wiki/Terminal_control/Unicode_output | Terminal control/Unicode output | The task is to check that the terminal supports Unicode output, before outputting a Unicode character. If the terminal supports Unicode, then the terminal should output a Unicode delta (U+25b3). If the terminal does not support Unicode, then an appropriate error should be raised.
Note that it is permissible to use system configuration data to determine terminal capabilities if the system provides such a facility.
| #Nim | Nim | import os, strutils
if "utf" in getEnv("LANG").toLower:
echo "Unicode is supported on this terminal and U+25B3 is: △"
else:
echo "Unicode is not supported on this terminal." |
http://rosettacode.org/wiki/Terminal_control/Unicode_output | Terminal control/Unicode output | The task is to check that the terminal supports Unicode output, before outputting a Unicode character. If the terminal supports Unicode, then the terminal should output a Unicode delta (U+25b3). If the terminal does not support Unicode, then an appropriate error should be raised.
Note that it is permissible to use system configuration data to determine terminal capabilities if the system provides such a facility.
| #Perl | Perl | die "Terminal can't handle UTF-8"
unless $ENV{LC_ALL} =~ /utf-8/i or $ENV{LC_CTYPE} =~ /utf-8/i or $ENV{LANG} =~ /utf-8/i;
print "△ \n"; |
http://rosettacode.org/wiki/Terminal_control/Unicode_output | Terminal control/Unicode output | The task is to check that the terminal supports Unicode output, before outputting a Unicode character. If the terminal supports Unicode, then the terminal should output a Unicode delta (U+25b3). If the terminal does not support Unicode, then an appropriate error should be raised.
Note that it is permissible to use system configuration data to determine terminal capabilities if the system provides such a facility.
| #Phix | Phix | with javascript_semantics
include builtins\cffi.e
constant tGSH = """
HANDLE WINAPI GetStdHandle(
_In_ DWORD nStdHandle
);
""",
tSCOCP = """
BOOL WINAPI SetConsoleOutputCP(
_In_ UINT wCodePageID
);
""",
STD_OUTPUT_HANDLE = -11,
CP_UTF8 = 65001,
envset = {"LANG","LC_ALL","LC_CTYPE"}
atom k32 = NULL, xGetStdHandle, hConsole, xSetConsoleOutputCP
global function unicode_console()
-- initialises the windows console for unicode, and
-- returns true if unicode is supported, else false.
bool res = false
if platform()=WINDOWS then
if k32=NULL then
puts(1,"") -- force console to exist
k32 = open_dll("kernel32.dll")
xGetStdHandle = define_cffi_func(k32,tGSH)
hConsole = c_func(xGetStdHandle,{STD_OUTPUT_HANDLE})
xSetConsoleOutputCP = define_cffi_func(k32,tSCOCP)
end if
-- following is equivalent to running "chcp 65001":
res = c_func(xSetConsoleOutputCP,{CP_UTF8})
else -- LINUX
for i=1 to length(envset) do
if match("UTF",upper(getenv(envset[i])))!=0 then
res = true
exit
end if
end for
end if
return res
end function
|
http://rosettacode.org/wiki/Terminal_control/Ringing_the_terminal_bell | Terminal control/Ringing the terminal bell |
Task
Make the terminal running the program ring its "bell".
On modern terminal emulators, this may be done by playing some other sound which might or might not be configurable, or by flashing the title bar or inverting the colors of the screen, but was classically a physical bell within the terminal. It is usually used to indicate a problem where a wrong character has been typed.
In most terminals, if the Bell character (ASCII code 7, \a in C) is printed by the program, it will cause the terminal to ring its bell. This is a function of the terminal, and is independent of the programming language of the program, other than the ability to print a particular character to standard out.
| #AWK | AWK | BEGIN {
print "\a" # Ring the bell
} |
http://rosettacode.org/wiki/Terminal_control/Ringing_the_terminal_bell | Terminal control/Ringing the terminal bell |
Task
Make the terminal running the program ring its "bell".
On modern terminal emulators, this may be done by playing some other sound which might or might not be configurable, or by flashing the title bar or inverting the colors of the screen, but was classically a physical bell within the terminal. It is usually used to indicate a problem where a wrong character has been typed.
In most terminals, if the Bell character (ASCII code 7, \a in C) is printed by the program, it will cause the terminal to ring its bell. This is a function of the terminal, and is independent of the programming language of the program, other than the ability to print a particular character to standard out.
| #BASIC | BASIC | 10 PRINT CHR$ (7); |
http://rosettacode.org/wiki/Terminal_control/Ringing_the_terminal_bell | Terminal control/Ringing the terminal bell |
Task
Make the terminal running the program ring its "bell".
On modern terminal emulators, this may be done by playing some other sound which might or might not be configurable, or by flashing the title bar or inverting the colors of the screen, but was classically a physical bell within the terminal. It is usually used to indicate a problem where a wrong character has been typed.
In most terminals, if the Bell character (ASCII code 7, \a in C) is printed by the program, it will cause the terminal to ring its bell. This is a function of the terminal, and is independent of the programming language of the program, other than the ability to print a particular character to standard out.
| #Batch_File | Batch File | @echo off
for /f %%. in ('forfiles /m "%~nx0" /c "cmd /c echo 0x07"') do set bell=%%.
echo %bell% |
http://rosettacode.org/wiki/The_Name_Game | The Name Game | Write a program that accepts a name as input and outputs the lyrics to the Shirley Ellis song "The Name Game".
The regular verse
Unless your name begins with a vowel (A, E, I, O, U), 'B', 'F' or 'M' you don't have to care about special rules.
The verse for the name 'Gary' would be like this:
Gary, Gary, bo-bary
Banana-fana fo-fary
Fee-fi-mo-mary
Gary!
At the end of every line, the name gets repeated without the first letter: Gary becomes ary
If we take (X) as the full name (Gary) and (Y) as the name without the first letter (ary) the verse would look like this:
(X), (X), bo-b(Y)
Banana-fana fo-f(Y)
Fee-fi-mo-m(Y)
(X)!
Vowel as first letter of the name
If you have a vowel as the first letter of your name (e.g. Earl) you do not truncate the name.
The verse looks like this:
Earl, Earl, bo-bearl
Banana-fana fo-fearl
Fee-fi-mo-mearl
Earl!
'B', 'F' or 'M' as first letter of the name
In case of a 'B', an 'F' or an 'M' (e.g. Billy, Felix, Mary) there is a special rule.
The line which would 'rebuild' the name (e.g. bo-billy) is sang without the first letter of the name.
The verse for the name Billy looks like this:
Billy, Billy, bo-illy
Banana-fana fo-filly
Fee-fi-mo-milly
Billy!
For the name 'Felix', this would be right:
Felix, Felix, bo-belix
Banana-fana fo-elix
Fee-fi-mo-melix
Felix!
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Visual_Basic_.NET | Visual Basic .NET | Option Strict On
Imports System.Text
Module Module1
Sub PrintVerse(name As String)
Dim sb As New StringBuilder(name.ToLower())
sb(0) = Char.ToUpper(sb(0))
Dim x = sb.ToString()
Dim y = If("AEIOU".IndexOf(x(0)) > -1, x.ToLower(), x.Substring(1))
Dim b = "b" + y
Dim f = "f" + y
Dim m = "m" + y
Select Case x(0)
Case "B"c
b = y
Exit Select
Case "F"c
f = y
Exit Select
Case "M"c
m = y
Exit Select
End Select
Console.WriteLine("{0}, {0}, bo-{1}", x, b)
Console.WriteLine("Banana-fana fo-{0}", f)
Console.WriteLine("Fee-fi-mo-{0}", m)
Console.WriteLine("{0}!", x)
Console.WriteLine()
End Sub
Sub Main()
Dim nameList As New List(Of String) From {"Gary", "Earl", "Billy", "Felix", "Mary", "Steve"}
nameList.ForEach(AddressOf PrintVerse)
End Sub
End Module |
http://rosettacode.org/wiki/Test_integerness | Test integerness | Mathematically,
the integers Z are included in the rational numbers Q,
which are included in the real numbers R,
which can be generalized to the complex numbers C.
This means that each of those larger sets, and the data types used to represent them, include some integers.
Task[edit]
Given a rational, real, or complex number of any type, test whether it is mathematically an integer.
Your code should handle all numeric data types commonly used in your programming language.
Discuss any limitations of your code.
Definition
For the purposes of this task, integerness means that a number could theoretically be represented as an integer at no loss of precision (given an infinitely wide integer type).
In other words:
Set
Common representation
C++ type
Considered an integer...
rational numbers Q
fraction
std::ratio
...if its denominator is 1 (in reduced form)
real numbers Z
(approximated)
fixed-point
...if it has no non-zero digits after the decimal point
floating-point
float, double
...if the number of significant decimal places of its mantissa isn't greater than its exponent
complex numbers C
pair of real numbers
std::complex
...if its real part is considered an integer and its imaginary part is zero
Extra credit
Optionally, make your code accept a tolerance parameter for fuzzy testing. The tolerance is the maximum amount by which the number may differ from the nearest integer, to still be considered an integer.
This is useful in practice, because when dealing with approximate numeric types (such as floating point), there may already be round-off errors from previous calculations. For example, a float value of 0.9999999998 might actually be intended to represent the integer 1.
Test cases
Input
Output
Comment
Type
Value
exact
tolerance = 0.00001
decimal
25.000000
true
24.999999
false
true
25.000100
false
floating-point
-2.1e120
true
This one is tricky, because in most languages it is too large to fit into a native integer type.
It is, nonetheless, mathematically an integer, and your code should identify it as such.
-5e-2
false
NaN
false
Inf
false
This one is debatable. If your code considers it an integer, that's okay too.
complex
5.0+0.0i
true
5-5i
false
(The types and notations shown in these tables are merely examples – you should use the native data types and number literals of your programming language and standard library. Use a different set of test-cases, if this one doesn't demonstrate all relevant behavior.)
| #11l | 11l | F isint(f)
R Complex(f).imag == 0 & fract(Complex(f).real) == 0
print([Complex(1.0), 2, (3.0 + 0.0i), 4.1, (3 + 4i), (5.6 + 0i)].map(f -> isint(f)))
print(isint(25.000000))
print(isint(24.999999))
print(isint(25.000100))
print(isint(-5e-2))
print(isint(Float.infinity))
print(isint(5.0 + 0.0i))
print(isint(5 - 5i)) |
http://rosettacode.org/wiki/Text_processing/Max_licenses_in_use | Text processing/Max licenses in use | A company currently pays a fixed sum for the use of a particular licensed software package. In determining if it has a good deal it decides to calculate its maximum use of the software from its license management log file.
Assume the software's licensing daemon faithfully records a checkout event when a copy of the software starts and a checkin event when the software finishes to its log file.
An example of checkout and checkin events are:
License OUT @ 2008/10/03_23:51:05 for job 4974
...
License IN @ 2008/10/04_00:18:22 for job 4974
Task
Save the 10,000 line log file from here into a local file, then write a program to scan the file extracting both the maximum licenses that were out at any time, and the time(s) at which this occurs.
Mirror of log file available as a zip here (offsite mirror).
| #HicEst | HicEst | CHARACTER Licenses="Licenses.txt"
REAL :: counts(1), Top10(10)
OPEN(FIle=Licenses, fmt='8x,A3,3x,A19,Nb ,', LENgth=lines)
ALLOCATE(counts, lines)
counts(1) = 1
DO line = 2, lines
counts(line) = counts(line-1) + 1 - 2*(Licenses(line,1)=='IN')
ENDDO
SORT(Vector=counts, Descending=1, Index=Top10)
DO i = 1, LEN(Top10)
WRITE() counts(Top10(i)), Licenses(Top10(i), 2)
ENDDO
END |
http://rosettacode.org/wiki/Test_a_function | Test a function |
Task
Using a well-known testing-specific library/module/suite for your language, write some tests for your language's entry in Palindrome.
If your language does not have a testing specific library well known to the language's community then state this or omit the language.
| #Ada | Ada | with Ada.Text_IO;
procedure Test_Function is
function Palindrome (Text : String) return Boolean is
begin
for Offset in 0 .. Text'Length / 2 - 1 loop
if Text (Text'First + Offset) /= Text (Text'Last - Offset) then
return False;
end if;
end loop;
return True;
end Palindrome;
str1 : String := "racecar";
str2 : String := "wombat";
begin
begin
pragma Assert(False); -- raises an exception if assertions are switched on
Ada.Text_IO.Put_Line("Skipping the test! Please compile with assertions switched on!");
exception
when others => -- assertions are switched on -- perform the tests
pragma Assert (Palindrome (str1) = True, "Assertion on str1 failed");
pragma Assert (Palindrome (str2) = False, "Assertion on str2 failed");
Ada.Text_IO.Put_Line("Test Passed!");
end;
end Test_Function; |
http://rosettacode.org/wiki/Test_a_function | Test a function |
Task
Using a well-known testing-specific library/module/suite for your language, write some tests for your language's entry in Palindrome.
If your language does not have a testing specific library well known to the language's community then state this or omit the language.
| #Arturo | Arturo | palindrome?: function [s][
s = reverse s
]
tests: [
[true? palindrome? "aba"]
[false? palindrome? "ab" ]
]
loop tests => ensure |
http://rosettacode.org/wiki/Text_processing/2 | Text processing/2 | The following task concerns data that came from a pollution monitoring station with twenty-four instruments monitoring twenty-four aspects of pollution in the air. Periodically a record is added to the file, each record being a line of 49 fields separated by white-space, which can be one or more space or tab characters.
The fields (from the left) are:
DATESTAMP [ VALUEn FLAGn ] * 24
i.e. a datestamp followed by twenty-four repetitions of a floating-point instrument value and that instrument's associated integer flag. Flag values are >= 1 if the instrument is working and < 1 if there is some problem with it, in which case that instrument's value should be ignored.
A sample from the full data file readings.txt, which is also used in the Text processing/1 task, follows:
Data is no longer available at that link. Zipped mirror available here
1991-03-30 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1
1991-03-31 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 20.000 1 20.000 1 20.000 1 35.000 1 50.000 1 60.000 1 40.000 1 30.000 1 30.000 1 30.000 1 25.000 1 20.000 1 20.000 1 20.000 1 20.000 1 20.000 1 35.000 1
1991-03-31 40.000 1 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2
1991-04-01 0.000 -2 13.000 1 16.000 1 21.000 1 24.000 1 22.000 1 20.000 1 18.000 1 29.000 1 44.000 1 50.000 1 43.000 1 38.000 1 27.000 1 27.000 1 24.000 1 23.000 1 18.000 1 12.000 1 13.000 1 14.000 1 15.000 1 13.000 1 10.000 1
1991-04-02 8.000 1 9.000 1 11.000 1 12.000 1 12.000 1 12.000 1 27.000 1 26.000 1 27.000 1 33.000 1 32.000 1 31.000 1 29.000 1 31.000 1 25.000 1 25.000 1 24.000 1 21.000 1 17.000 1 14.000 1 15.000 1 12.000 1 12.000 1 10.000 1
1991-04-03 10.000 1 9.000 1 10.000 1 10.000 1 9.000 1 10.000 1 15.000 1 24.000 1 28.000 1 24.000 1 18.000 1 14.000 1 12.000 1 13.000 1 14.000 1 15.000 1 14.000 1 15.000 1 13.000 1 13.000 1 13.000 1 12.000 1 10.000 1 10.000 1
Task
Confirm the general field format of the file.
Identify any DATESTAMPs that are duplicated.
Report the number of records that have good readings for all instruments.
| #PHP | PHP | $handle = fopen("readings.txt", "rb");
$missformcount = 0;
$totalcount = 0;
$dates = array();
while (!feof($handle)) {
$buffer = fgets($handle);
$line = preg_replace('/\s+/',' ',$buffer);
$line = explode(' ',trim($line));
$datepattern = '/^\d{4}-\d{2}-\d{2}$/';
$valpattern = '/^\d+\.{1}\d{3}$/';
$flagpattern = '/^[1-9]{1}$/';
if(count($line) != 49) $missformcount++;
if(!preg_match($datepattern,$line[0],$check)) $missformcount++;
else $dates[$totalcount+1] = $check[0];
$errcount = 0;
for($i=1;$i<count($line);$i++){
if($i%2!=0){
if(!preg_match($valpattern,$line[$i],$check)) $errcount++;
}else{
if(!preg_match($flagpattern,$line[$i],$check)) $errcount++;
}
}
if($errcount != 0) $missformcount++;
$totalcount++;
}
fclose ($handle);
$good = $totalcount - $missformcount;
$duplicates = array_diff_key( $dates , array_unique( $dates ));
echo 'Valid records ' . $good . ' of ' . $totalcount . ' total<br>';
echo 'Duplicates : <br>';
foreach ($duplicates as $key => $val){
echo $val . ' at Line : ' . $key . '<br>';
} |
http://rosettacode.org/wiki/Terminal_control/Unicode_output | Terminal control/Unicode output | The task is to check that the terminal supports Unicode output, before outputting a Unicode character. If the terminal supports Unicode, then the terminal should output a Unicode delta (U+25b3). If the terminal does not support Unicode, then an appropriate error should be raised.
Note that it is permissible to use system configuration data to determine terminal capabilities if the system provides such a facility.
| #PicoLisp | PicoLisp | (if (sub? "UTF-8" (or (sys "LC_ALL") (sys "LC_CTYPE") (sys "LANG")))
(prinl (char (hex "25b3")))
(quit "UTF-8 capable terminal required") ) |
http://rosettacode.org/wiki/Terminal_control/Unicode_output | Terminal control/Unicode output | The task is to check that the terminal supports Unicode output, before outputting a Unicode character. If the terminal supports Unicode, then the terminal should output a Unicode delta (U+25b3). If the terminal does not support Unicode, then an appropriate error should be raised.
Note that it is permissible to use system configuration data to determine terminal capabilities if the system provides such a facility.
| #Python | Python | import sys
if "UTF-8" in sys.stdout.encoding:
print("△")
else:
raise Exception("Terminal can't handle UTF-8") |
http://rosettacode.org/wiki/Terminal_control/Unicode_output | Terminal control/Unicode output | The task is to check that the terminal supports Unicode output, before outputting a Unicode character. If the terminal supports Unicode, then the terminal should output a Unicode delta (U+25b3). If the terminal does not support Unicode, then an appropriate error should be raised.
Note that it is permissible to use system configuration data to determine terminal capabilities if the system provides such a facility.
| #R | R | if (any(grepl("UTF", toupper(Sys.getenv(c("LANG", "LC_ALL", "LC_CTYPE")))))) {
cat("Unicode is supported on this terminal and U+25B3 is : \u25b3\n")
} else {
cat("Unicode is not supported on this terminal.")
} |
http://rosettacode.org/wiki/Terminal_control/Unicode_output | Terminal control/Unicode output | The task is to check that the terminal supports Unicode output, before outputting a Unicode character. If the terminal supports Unicode, then the terminal should output a Unicode delta (U+25b3). If the terminal does not support Unicode, then an appropriate error should be raised.
Note that it is permissible to use system configuration data to determine terminal capabilities if the system provides such a facility.
| #Racket | Racket |
#lang racket
(displayln
(if (regexp-match? #px"(?i:utf-?8)"
(or (getenv "LC_ALL") (getenv "LC_CTYPE") (getenv "LANG")))
"\u25b3" "No Unicode detected."))
|
http://rosettacode.org/wiki/Terminal_control/Ringing_the_terminal_bell | Terminal control/Ringing the terminal bell |
Task
Make the terminal running the program ring its "bell".
On modern terminal emulators, this may be done by playing some other sound which might or might not be configurable, or by flashing the title bar or inverting the colors of the screen, but was classically a physical bell within the terminal. It is usually used to indicate a problem where a wrong character has been typed.
In most terminals, if the Bell character (ASCII code 7, \a in C) is printed by the program, it will cause the terminal to ring its bell. This is a function of the terminal, and is independent of the programming language of the program, other than the ability to print a particular character to standard out.
| #BBC_BASIC | BBC BASIC | VDU 7 |
http://rosettacode.org/wiki/Terminal_control/Ringing_the_terminal_bell | Terminal control/Ringing the terminal bell |
Task
Make the terminal running the program ring its "bell".
On modern terminal emulators, this may be done by playing some other sound which might or might not be configurable, or by flashing the title bar or inverting the colors of the screen, but was classically a physical bell within the terminal. It is usually used to indicate a problem where a wrong character has been typed.
In most terminals, if the Bell character (ASCII code 7, \a in C) is printed by the program, it will cause the terminal to ring its bell. This is a function of the terminal, and is independent of the programming language of the program, other than the ability to print a particular character to standard out.
| #Bc | Bc | print "\a" |
http://rosettacode.org/wiki/Terminal_control/Ringing_the_terminal_bell | Terminal control/Ringing the terminal bell |
Task
Make the terminal running the program ring its "bell".
On modern terminal emulators, this may be done by playing some other sound which might or might not be configurable, or by flashing the title bar or inverting the colors of the screen, but was classically a physical bell within the terminal. It is usually used to indicate a problem where a wrong character has been typed.
In most terminals, if the Bell character (ASCII code 7, \a in C) is printed by the program, it will cause the terminal to ring its bell. This is a function of the terminal, and is independent of the programming language of the program, other than the ability to print a particular character to standard out.
| #beeswax | beeswax | _7} |
http://rosettacode.org/wiki/Terminal_control/Ringing_the_terminal_bell | Terminal control/Ringing the terminal bell |
Task
Make the terminal running the program ring its "bell".
On modern terminal emulators, this may be done by playing some other sound which might or might not be configurable, or by flashing the title bar or inverting the colors of the screen, but was classically a physical bell within the terminal. It is usually used to indicate a problem where a wrong character has been typed.
In most terminals, if the Bell character (ASCII code 7, \a in C) is printed by the program, it will cause the terminal to ring its bell. This is a function of the terminal, and is independent of the programming language of the program, other than the ability to print a particular character to standard out.
| #Befunge | Befunge | 7,@ |
http://rosettacode.org/wiki/The_Name_Game | The Name Game | Write a program that accepts a name as input and outputs the lyrics to the Shirley Ellis song "The Name Game".
The regular verse
Unless your name begins with a vowel (A, E, I, O, U), 'B', 'F' or 'M' you don't have to care about special rules.
The verse for the name 'Gary' would be like this:
Gary, Gary, bo-bary
Banana-fana fo-fary
Fee-fi-mo-mary
Gary!
At the end of every line, the name gets repeated without the first letter: Gary becomes ary
If we take (X) as the full name (Gary) and (Y) as the name without the first letter (ary) the verse would look like this:
(X), (X), bo-b(Y)
Banana-fana fo-f(Y)
Fee-fi-mo-m(Y)
(X)!
Vowel as first letter of the name
If you have a vowel as the first letter of your name (e.g. Earl) you do not truncate the name.
The verse looks like this:
Earl, Earl, bo-bearl
Banana-fana fo-fearl
Fee-fi-mo-mearl
Earl!
'B', 'F' or 'M' as first letter of the name
In case of a 'B', an 'F' or an 'M' (e.g. Billy, Felix, Mary) there is a special rule.
The line which would 'rebuild' the name (e.g. bo-billy) is sang without the first letter of the name.
The verse for the name Billy looks like this:
Billy, Billy, bo-illy
Banana-fana fo-filly
Fee-fi-mo-milly
Billy!
For the name 'Felix', this would be right:
Felix, Felix, bo-belix
Banana-fana fo-elix
Fee-fi-mo-melix
Felix!
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Wren | Wren | import "/str" for Str
var printVerse = Fn.new { |name|
var x = Str.capitalize(Str.lower(name))
var z = x[0]
var y = "AEIOU".contains(z) ? Str.lower(x) : x[1..-1]
var b = "b%(y)"
var f = "f%(y)"
var m = "m%(y)"
if (z == "B") {
b = y
} else if (z == "F") {
f = y
} else if (z == "M") {
m = y
}
System.print("%(x), %(x), bo-%(b)")
System.print("Banana-fana fo-%(f)")
System.print("Fee-fi-mo-%(m)")
System.print("%(x)!\n")
}
["Gary", "Earl", "Billy", "Felix", "Mary", "Steve"].each { |name| printVerse.call(name) } |
http://rosettacode.org/wiki/Test_integerness | Test integerness | Mathematically,
the integers Z are included in the rational numbers Q,
which are included in the real numbers R,
which can be generalized to the complex numbers C.
This means that each of those larger sets, and the data types used to represent them, include some integers.
Task[edit]
Given a rational, real, or complex number of any type, test whether it is mathematically an integer.
Your code should handle all numeric data types commonly used in your programming language.
Discuss any limitations of your code.
Definition
For the purposes of this task, integerness means that a number could theoretically be represented as an integer at no loss of precision (given an infinitely wide integer type).
In other words:
Set
Common representation
C++ type
Considered an integer...
rational numbers Q
fraction
std::ratio
...if its denominator is 1 (in reduced form)
real numbers Z
(approximated)
fixed-point
...if it has no non-zero digits after the decimal point
floating-point
float, double
...if the number of significant decimal places of its mantissa isn't greater than its exponent
complex numbers C
pair of real numbers
std::complex
...if its real part is considered an integer and its imaginary part is zero
Extra credit
Optionally, make your code accept a tolerance parameter for fuzzy testing. The tolerance is the maximum amount by which the number may differ from the nearest integer, to still be considered an integer.
This is useful in practice, because when dealing with approximate numeric types (such as floating point), there may already be round-off errors from previous calculations. For example, a float value of 0.9999999998 might actually be intended to represent the integer 1.
Test cases
Input
Output
Comment
Type
Value
exact
tolerance = 0.00001
decimal
25.000000
true
24.999999
false
true
25.000100
false
floating-point
-2.1e120
true
This one is tricky, because in most languages it is too large to fit into a native integer type.
It is, nonetheless, mathematically an integer, and your code should identify it as such.
-5e-2
false
NaN
false
Inf
false
This one is debatable. If your code considers it an integer, that's okay too.
complex
5.0+0.0i
true
5-5i
false
(The types and notations shown in these tables are merely examples – you should use the native data types and number literals of your programming language and standard library. Use a different set of test-cases, if this one doesn't demonstrate all relevant behavior.)
| #ALGOL_68 | ALGOL 68 | # set the required precision of LONG LONG values using #
# "PR precision n PR" if required #
PR precision 24 PR
# returns TRUE if v has an integer value, FALSE otherwise #
OP ISINT = ( LONG LONG COMPL v )BOOL:
IF im OF v /= 0 THEN
# v has an imaginary part #
FALSE
ELSE
# v has a real part only #
ENTIER re OF v = v
FI; # ISINT #
# test ISINT #
PROC test is int = ( LONG LONG COMPLEX v )VOID:
print( ( re OF v, "_", im OF v, IF ISINT v THEN " is " ELSE " is not " FI, "integral", newline ) );
test is int( 1 );
test is int( 1.00000001 );
test is int( 4 I 3 );
test is int( 4.0 I 0 );
test is int( 123456789012345678901234 )
|
http://rosettacode.org/wiki/Text_processing/Max_licenses_in_use | Text processing/Max licenses in use | A company currently pays a fixed sum for the use of a particular licensed software package. In determining if it has a good deal it decides to calculate its maximum use of the software from its license management log file.
Assume the software's licensing daemon faithfully records a checkout event when a copy of the software starts and a checkin event when the software finishes to its log file.
An example of checkout and checkin events are:
License OUT @ 2008/10/03_23:51:05 for job 4974
...
License IN @ 2008/10/04_00:18:22 for job 4974
Task
Save the 10,000 line log file from here into a local file, then write a program to scan the file extracting both the maximum licenses that were out at any time, and the time(s) at which this occurs.
Mirror of log file available as a zip here (offsite mirror).
| #Icon_and_Unicon | Icon and Unicon | procedure main(A)
maxCount := count := 0
every !&input ? case tab(upto('@')) of {
"License OUT ": {
maxTime := (maxCount <:= (count +:= 1), [])
put(maxTime, (maxCount = count, ="@ ", tab(find(" for "))))
}
"License IN ": count -:= (count > 0, 1) # Error check
}
write("There were ",maxCount," licenses out at:")
every write("\t",!maxTime)
end |
http://rosettacode.org/wiki/Test_a_function | Test a function |
Task
Using a well-known testing-specific library/module/suite for your language, write some tests for your language's entry in Palindrome.
If your language does not have a testing specific library well known to the language's community then state this or omit the language.
| #AutoHotkey | AutoHotkey | ; assert.ahk
;; assert(a, b, test=2)
assert(a, b="blank", test=0)
{
if (b = "blank")
{
if !a
msgbox % "blank value"
return 0
}
if equal_list(a, b, "`n")
return 0
else
msgbox % test . ":`n" . a . "`nexpected:`n" . b
}
!r::reload
;; equal_list(a, b, delimiter)
equal_list(a, b, delimiter)
{
loop, parse, b, %delimiter%
{
if instr(a, A_LoopField)
continue
else
return 0
}
loop, parse, a, %delimiter%
{
if instr(b, A_LoopField)
continue
else
return 0
}
return 1
} |
http://rosettacode.org/wiki/Test_a_function | Test a function |
Task
Using a well-known testing-specific library/module/suite for your language, write some tests for your language's entry in Palindrome.
If your language does not have a testing specific library well known to the language's community then state this or omit the language.
| #Brat | Brat | include :assert
palindrome? = { str |
str = str.downcase.sub /\s+/ ""
str == str.reverse
}
setup name: "palindrome test" {
test "is a palindrome" {
assert { palindrome? "abba" }
}
test "is not a palindrome" {
assert_false { palindrome? "abb" }
}
test "is not a string" {
assert_fail { palindrome? 1001 }
}
test "this test fails" {
assert { palindrome? "blah blah" }
}
} |
http://rosettacode.org/wiki/Text_processing/2 | Text processing/2 | The following task concerns data that came from a pollution monitoring station with twenty-four instruments monitoring twenty-four aspects of pollution in the air. Periodically a record is added to the file, each record being a line of 49 fields separated by white-space, which can be one or more space or tab characters.
The fields (from the left) are:
DATESTAMP [ VALUEn FLAGn ] * 24
i.e. a datestamp followed by twenty-four repetitions of a floating-point instrument value and that instrument's associated integer flag. Flag values are >= 1 if the instrument is working and < 1 if there is some problem with it, in which case that instrument's value should be ignored.
A sample from the full data file readings.txt, which is also used in the Text processing/1 task, follows:
Data is no longer available at that link. Zipped mirror available here
1991-03-30 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1
1991-03-31 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 20.000 1 20.000 1 20.000 1 35.000 1 50.000 1 60.000 1 40.000 1 30.000 1 30.000 1 30.000 1 25.000 1 20.000 1 20.000 1 20.000 1 20.000 1 20.000 1 35.000 1
1991-03-31 40.000 1 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2
1991-04-01 0.000 -2 13.000 1 16.000 1 21.000 1 24.000 1 22.000 1 20.000 1 18.000 1 29.000 1 44.000 1 50.000 1 43.000 1 38.000 1 27.000 1 27.000 1 24.000 1 23.000 1 18.000 1 12.000 1 13.000 1 14.000 1 15.000 1 13.000 1 10.000 1
1991-04-02 8.000 1 9.000 1 11.000 1 12.000 1 12.000 1 12.000 1 27.000 1 26.000 1 27.000 1 33.000 1 32.000 1 31.000 1 29.000 1 31.000 1 25.000 1 25.000 1 24.000 1 21.000 1 17.000 1 14.000 1 15.000 1 12.000 1 12.000 1 10.000 1
1991-04-03 10.000 1 9.000 1 10.000 1 10.000 1 9.000 1 10.000 1 15.000 1 24.000 1 28.000 1 24.000 1 18.000 1 14.000 1 12.000 1 13.000 1 14.000 1 15.000 1 14.000 1 15.000 1 13.000 1 13.000 1 13.000 1 12.000 1 10.000 1 10.000 1
Task
Confirm the general field format of the file.
Identify any DATESTAMPs that are duplicated.
Report the number of records that have good readings for all instruments.
| #Picat | Picat | import util.
go =>
Readings = [split(Record) : Record in read_file_lines("readings.txt")],
DateStamps = new_map(),
GoodReadings = 0,
foreach({Rec,Id} in zip(Readings,1..Readings.length))
if Rec.length != 49 then printf("Entry %d has bad_length %d\n", Id, Rec.length) end,
Date = Rec[1],
if DateStamps.has_key(Date) then
printf("Entry %d (date %w) is a duplicate of entry %w\n", Id, Date, DateStamps.get(Date))
else
if sum([1: I in 3..2..49, check_field(Rec[I])]) == 0 then
GoodReadings := GoodReadings + 1
end
end,
DateStamps.put(Date, Id)
end,
nl,
printf("Total readings: %d\n",Readings.len),
printf("Good readings: %d\n",GoodReadings),
nl.
check_field(Field) =>
Field == "-2" ; Field == "-1" ; Field == "0". |
http://rosettacode.org/wiki/Text_processing/2 | Text processing/2 | The following task concerns data that came from a pollution monitoring station with twenty-four instruments monitoring twenty-four aspects of pollution in the air. Periodically a record is added to the file, each record being a line of 49 fields separated by white-space, which can be one or more space or tab characters.
The fields (from the left) are:
DATESTAMP [ VALUEn FLAGn ] * 24
i.e. a datestamp followed by twenty-four repetitions of a floating-point instrument value and that instrument's associated integer flag. Flag values are >= 1 if the instrument is working and < 1 if there is some problem with it, in which case that instrument's value should be ignored.
A sample from the full data file readings.txt, which is also used in the Text processing/1 task, follows:
Data is no longer available at that link. Zipped mirror available here
1991-03-30 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1
1991-03-31 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 20.000 1 20.000 1 20.000 1 35.000 1 50.000 1 60.000 1 40.000 1 30.000 1 30.000 1 30.000 1 25.000 1 20.000 1 20.000 1 20.000 1 20.000 1 20.000 1 35.000 1
1991-03-31 40.000 1 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2
1991-04-01 0.000 -2 13.000 1 16.000 1 21.000 1 24.000 1 22.000 1 20.000 1 18.000 1 29.000 1 44.000 1 50.000 1 43.000 1 38.000 1 27.000 1 27.000 1 24.000 1 23.000 1 18.000 1 12.000 1 13.000 1 14.000 1 15.000 1 13.000 1 10.000 1
1991-04-02 8.000 1 9.000 1 11.000 1 12.000 1 12.000 1 12.000 1 27.000 1 26.000 1 27.000 1 33.000 1 32.000 1 31.000 1 29.000 1 31.000 1 25.000 1 25.000 1 24.000 1 21.000 1 17.000 1 14.000 1 15.000 1 12.000 1 12.000 1 10.000 1
1991-04-03 10.000 1 9.000 1 10.000 1 10.000 1 9.000 1 10.000 1 15.000 1 24.000 1 28.000 1 24.000 1 18.000 1 14.000 1 12.000 1 13.000 1 14.000 1 15.000 1 14.000 1 15.000 1 13.000 1 13.000 1 13.000 1 12.000 1 10.000 1 10.000 1
Task
Confirm the general field format of the file.
Identify any DATESTAMPs that are duplicated.
Report the number of records that have good readings for all instruments.
| #PicoLisp | PicoLisp | #!/usr/bin/picolisp /usr/lib/picolisp/lib.l
(load "@lib/misc.l")
(in (opt)
(until (eof)
(let Lst (split (line) "^I")
(unless
(and
(= 49 (length Lst)) # Check total length
($dat (car Lst) "-") # Check for valid date
(fully # Check data format
'((L F)
(if F # Alternating:
(format L 3) # Number
(>= 9 (format L) -9) ) ) # or flag
(cdr Lst)
'(T NIL .) ) )
(prinl "Bad line format: " (glue " " Lst))
(bye 1) ) ) ) )
(bye) |
http://rosettacode.org/wiki/Terminal_control/Unicode_output | Terminal control/Unicode output | The task is to check that the terminal supports Unicode output, before outputting a Unicode character. If the terminal supports Unicode, then the terminal should output a Unicode delta (U+25b3). If the terminal does not support Unicode, then an appropriate error should be raised.
Note that it is permissible to use system configuration data to determine terminal capabilities if the system provides such a facility.
| #Raku | Raku | die "Terminal can't handle UTF-8"
unless first(*.defined, %*ENV<LC_ALL LC_CTYPE LANG>) ~~ /:i 'utf-8'/;
say "△"; |
http://rosettacode.org/wiki/Terminal_control/Unicode_output | Terminal control/Unicode output | The task is to check that the terminal supports Unicode output, before outputting a Unicode character. If the terminal supports Unicode, then the terminal should output a Unicode delta (U+25b3). If the terminal does not support Unicode, then an appropriate error should be raised.
Note that it is permissible to use system configuration data to determine terminal capabilities if the system provides such a facility.
| #Ruby | Ruby | #encoding: UTF-8 # superfluous in Ruby >1.9.3
if ENV.values_at("LC_ALL","LC_CTYPE","LANG").compact.first.include?("UTF-8")
puts "△"
else
raise "Terminal can't handle UTF-8"
end
|
http://rosettacode.org/wiki/Terminal_control/Unicode_output | Terminal control/Unicode output | The task is to check that the terminal supports Unicode output, before outputting a Unicode character. If the terminal supports Unicode, then the terminal should output a Unicode delta (U+25b3). If the terminal does not support Unicode, then an appropriate error should be raised.
Note that it is permissible to use system configuration data to determine terminal capabilities if the system provides such a facility.
| #Scala | Scala | scala> println(s"Unicode is supported on this terminal and U+25B3 is : \u25b3")
Unicode is supported on this terminal and U+25B3 is : △ |
http://rosettacode.org/wiki/Terminal_control/Ringing_the_terminal_bell | Terminal control/Ringing the terminal bell |
Task
Make the terminal running the program ring its "bell".
On modern terminal emulators, this may be done by playing some other sound which might or might not be configurable, or by flashing the title bar or inverting the colors of the screen, but was classically a physical bell within the terminal. It is usually used to indicate a problem where a wrong character has been typed.
In most terminals, if the Bell character (ASCII code 7, \a in C) is printed by the program, it will cause the terminal to ring its bell. This is a function of the terminal, and is independent of the programming language of the program, other than the ability to print a particular character to standard out.
| #Bracmat | Bracmat | \a |
http://rosettacode.org/wiki/Terminal_control/Ringing_the_terminal_bell | Terminal control/Ringing the terminal bell |
Task
Make the terminal running the program ring its "bell".
On modern terminal emulators, this may be done by playing some other sound which might or might not be configurable, or by flashing the title bar or inverting the colors of the screen, but was classically a physical bell within the terminal. It is usually used to indicate a problem where a wrong character has been typed.
In most terminals, if the Bell character (ASCII code 7, \a in C) is printed by the program, it will cause the terminal to ring its bell. This is a function of the terminal, and is independent of the programming language of the program, other than the ability to print a particular character to standard out.
| #Brainf.2A.2A.2A | Brainf*** | I
+
+ +
+++
+-+-+
. |
http://rosettacode.org/wiki/Terminal_control/Ringing_the_terminal_bell | Terminal control/Ringing the terminal bell |
Task
Make the terminal running the program ring its "bell".
On modern terminal emulators, this may be done by playing some other sound which might or might not be configurable, or by flashing the title bar or inverting the colors of the screen, but was classically a physical bell within the terminal. It is usually used to indicate a problem where a wrong character has been typed.
In most terminals, if the Bell character (ASCII code 7, \a in C) is printed by the program, it will cause the terminal to ring its bell. This is a function of the terminal, and is independent of the programming language of the program, other than the ability to print a particular character to standard out.
| #C | C | #include <stdio.h>
int main() {
printf("\a");
return 0;
} |
http://rosettacode.org/wiki/Terminal_control/Ringing_the_terminal_bell | Terminal control/Ringing the terminal bell |
Task
Make the terminal running the program ring its "bell".
On modern terminal emulators, this may be done by playing some other sound which might or might not be configurable, or by flashing the title bar or inverting the colors of the screen, but was classically a physical bell within the terminal. It is usually used to indicate a problem where a wrong character has been typed.
In most terminals, if the Bell character (ASCII code 7, \a in C) is printed by the program, it will cause the terminal to ring its bell. This is a function of the terminal, and is independent of the programming language of the program, other than the ability to print a particular character to standard out.
| #C.23 | C# | // the simple version:
System.Console.Write("\a"); // will beep
System.Threading.Thread.Sleep(1000); // will wait for 1 second
System.Console.Beep(); // will beep a second time
System.Threading.Thread.Sleep(1000);
// System.Console.Beep() also accepts (int)hertz and (int)duration in milliseconds:
System.Console.Beep(440, 2000); // default "concert pitch" for 2 seconds
|
http://rosettacode.org/wiki/The_ISAAC_Cipher | The ISAAC Cipher | ISAAC is a cryptographically secure pseudo-random number generator (CSPRNG) and stream cipher. It was developed by Bob Jenkins from 1993 (http://burtleburtle.net/bob/rand/isaac.html) and placed in the Public Domain. ISAAC is fast - especially when optimised - and portable to most architectures in nearly all programming and scripting languages.
It is also simple and succinct, using as it does just two 256-word arrays for its state.
ISAAC stands for "Indirection, Shift, Accumulate, Add, and Count" which are the principal bitwise operations employed.
To date - and that's after more than 20 years of existence - ISAAC has not been broken (unless GCHQ or NSA did it, but they wouldn't be telling).
ISAAC thus deserves a lot more attention than it has hitherto received and it would be salutary to see it more universally implemented.
Task
Translate ISAAC's reference C or Pascal code into your language of choice.
The RNG should then be seeded with the string "this is my secret key" and
finally the message "a Top Secret secret" should be encrypted on that key.
Your program's output cipher-text will be a string of hexadecimal digits.
Optional: Include a decryption check by re-initializing ISAAC and performing
the same encryption pass on the cipher-text.
Please use the C or Pascal as a reference guide to these operations.
Two encryption schemes are possible:
(1) XOR (Vernam) or
(2) Caesar-shift mod 95 (Vigenère).
XOR is the simplest; C-shifting offers greater security.
You may choose either scheme, or both, but please specify which you used.
Here are the alternative sample outputs for checking purposes:
Message: a Top Secret secret
Key : this is my secret key
XOR : 1C0636190B1260233B35125F1E1D0E2F4C5422
MOD : 734270227D36772A783B4F2A5F206266236978
XOR dcr: a Top Secret secret
MOD dcr: a Top Secret secret
No official seeding method for ISAAC has been published, but for this task
we may as well just inject the bytes of our key into the randrsl array,
padding with zeroes before mixing, like so:
// zeroise mm array
FOR i:= 0 TO 255 DO mm[i]:=0;
// check seed's highest array element
m := High(seed);
// inject the seed
FOR i:= 0 TO 255 DO BEGIN
// in case seed[] has less than 256 elements.
IF i>m THEN randrsl[i]:=0
ELSE randrsl[i]:=seed[i];
END;
// initialize ISAAC with seed
RandInit(true);
ISAAC can of course also be initialized with a single 32-bit unsigned integer in the manner of traditional RNGs, and indeed used as such for research and gaming purposes.
But building a strong and simple ISAAC-based stream cipher - replacing the irreparably broken RC4 - is our goal here: ISAAC's intended purpose.
| #C | C |
/* Known to compile and work with tcc in win32 & gcc on Linux (with warnings)
------------------------------------------------------------------------------
readable.c: My random number generator, ISAAC.
(c) Bob Jenkins, March 1996, Public Domain
You may use this code in any way you wish, and it is free. No warrantee.
------------------------------------------------------------------------------
*/
#include <stdio.h>
#include <stddef.h>
#include <string.h>
#ifdef _MSC_VER
typedef unsigned __int32 uint32_t;
#else
#include <stdint.h>
#endif
/* a ub4 is an unsigned 4-byte quantity */
typedef uint32_t ub4;
/* external results */
ub4 randrsl[256], randcnt;
/* internal state */
static ub4 mm[256];
static ub4 aa=0, bb=0, cc=0;
void isaac()
{
register ub4 i,x,y;
cc = cc + 1; /* cc just gets incremented once per 256 results */
bb = bb + cc; /* then combined with bb */
for (i=0; i<256; ++i)
{
x = mm[i];
switch (i%4)
{
case 0: aa = aa^(aa<<13); break;
case 1: aa = aa^(aa>>6); break;
case 2: aa = aa^(aa<<2); break;
case 3: aa = aa^(aa>>16); break;
}
aa = mm[(i+128)%256] + aa;
mm[i] = y = mm[(x>>2)%256] + aa + bb;
randrsl[i] = bb = mm[(y>>10)%256] + x;
}
// not in original readable.c
randcnt = 0;
}
/* if (flag!=0), then use the contents of randrsl[] to initialize mm[]. */
#define mix(a,b,c,d,e,f,g,h) \
{ \
a^=b<<11; d+=a; b+=c; \
b^=c>>2; e+=b; c+=d; \
c^=d<<8; f+=c; d+=e; \
d^=e>>16; g+=d; e+=f; \
e^=f<<10; h+=e; f+=g; \
f^=g>>4; a+=f; g+=h; \
g^=h<<8; b+=g; h+=a; \
h^=a>>9; c+=h; a+=b; \
}
void randinit(int flag)
{
register int i;
ub4 a,b,c,d,e,f,g,h;
aa=bb=cc=0;
a=b=c=d=e=f=g=h=0x9e3779b9; /* the golden ratio */
for (i=0; i<4; ++i) /* scramble it */
{
mix(a,b,c,d,e,f,g,h);
}
for (i=0; i<256; i+=8) /* fill in mm[] with messy stuff */
{
if (flag) /* use all the information in the seed */
{
a+=randrsl[i ]; b+=randrsl[i+1]; c+=randrsl[i+2]; d+=randrsl[i+3];
e+=randrsl[i+4]; f+=randrsl[i+5]; g+=randrsl[i+6]; h+=randrsl[i+7];
}
mix(a,b,c,d,e,f,g,h);
mm[i ]=a; mm[i+1]=b; mm[i+2]=c; mm[i+3]=d;
mm[i+4]=e; mm[i+5]=f; mm[i+6]=g; mm[i+7]=h;
}
if (flag)
{ /* do a second pass to make all of the seed affect all of mm */
for (i=0; i<256; i+=8)
{
a+=mm[i ]; b+=mm[i+1]; c+=mm[i+2]; d+=mm[i+3];
e+=mm[i+4]; f+=mm[i+5]; g+=mm[i+6]; h+=mm[i+7];
mix(a,b,c,d,e,f,g,h);
mm[i ]=a; mm[i+1]=b; mm[i+2]=c; mm[i+3]=d;
mm[i+4]=e; mm[i+5]=f; mm[i+6]=g; mm[i+7]=h;
}
}
isaac(); /* fill in the first set of results */
randcnt=0; /* prepare to use the first set of results */
}
// Get a random 32-bit value 0..MAXINT
ub4 iRandom()
{
ub4 r = randrsl[randcnt];
++randcnt;
if (randcnt >255) {
isaac();
randcnt = 0;
}
return r;
}
// Get a random character in printable ASCII range
char iRandA()
{
return iRandom() % 95 + 32;
}
// Seed ISAAC with a string
void iSeed(char *seed, int flag)
{
register ub4 i,m;
for (i=0; i<256; i++) mm[i]=0;
m = strlen(seed);
for (i=0; i<256; i++)
{
// in case seed has less than 256 elements
if (i>m) randrsl[i]=0; else randrsl[i] = seed[i];
}
// initialize ISAAC with seed
randinit(flag);
}
// maximum length of message
#define MAXMSG 4096
#define MOD 95
#define START 32
// cipher modes for Caesar
enum ciphermode {
mEncipher, mDecipher, mNone
};
// XOR cipher on random stream. Output: ASCII string
char v[MAXMSG];
char* Vernam(char *msg)
{
register ub4 i,l;
l = strlen(msg);
// zeroise v
memset(v,'\0',l+1);
// XOR message
for (i=0; i<l; i++)
v[i] = iRandA() ^ msg[i];
return v;
}
// Caesar-shift a printable character
char Caesar(enum ciphermode m, char ch, char shift, char modulo, char start)
{
register int n;
if (m == mDecipher) shift = -shift;
n = (ch-start) + shift;
n = n % modulo;
if (n<0) n += modulo;
return start+n;
}
// Caesar-shift a string on a pseudo-random stream
char c[MAXMSG];
char* CaesarStr(enum ciphermode m, char *msg, char modulo, char start)
{
register ub4 i,l;
l = strlen(msg);
// zeroise c
memset(c,'\0',l+1);
// Caesar-shift message
for (i=0; i<l; i++)
c[i] = Caesar(m, msg[i], iRandA(), modulo, start);
return c;
}
int main()
{
register ub4 n,l;
// input: message and key
char *msg = "a Top Secret secret";
char *key = "this is my secret key";
// Vernam ciphertext & plaintext
char vctx[MAXMSG], vptx[MAXMSG];
// Caesar ciphertext & plaintext
char cctx[MAXMSG], cptx[MAXMSG];
l = strlen(msg);
// Encrypt: Vernam XOR
iSeed(key,1);
strcpy(vctx, Vernam(msg));
// Encrypt: Caesar
strcpy(cctx, CaesarStr(mEncipher, msg, MOD, START));
// Decrypt: Vernam XOR
iSeed(key,1);
strcpy(vptx, Vernam(vctx));
// Decrypt: Caesar
strcpy(cptx, CaesarStr(mDecipher,cctx, MOD, START));
// Program output
printf("Message: %s\n",msg);
printf("Key : %s\n",key);
printf("XOR : ");
// Output Vernam ciphertext as a string of hex digits
for (n=0; n<l; n++) printf("%02X",vctx[n]);
printf("\n");
// Output Vernam decrypted plaintext
printf("XOR dcr: %s\n",vptx);
// Caesar
printf("MOD : ");
// Output Caesar ciphertext as a string of hex digits
for (n=0; n<l; n++) printf("%02X",cctx[n]);
printf("\n");
// Output Caesar decrypted plaintext
printf("MOD dcr: %s\n",cptx);
return 0;
}
|
http://rosettacode.org/wiki/The_Name_Game | The Name Game | Write a program that accepts a name as input and outputs the lyrics to the Shirley Ellis song "The Name Game".
The regular verse
Unless your name begins with a vowel (A, E, I, O, U), 'B', 'F' or 'M' you don't have to care about special rules.
The verse for the name 'Gary' would be like this:
Gary, Gary, bo-bary
Banana-fana fo-fary
Fee-fi-mo-mary
Gary!
At the end of every line, the name gets repeated without the first letter: Gary becomes ary
If we take (X) as the full name (Gary) and (Y) as the name without the first letter (ary) the verse would look like this:
(X), (X), bo-b(Y)
Banana-fana fo-f(Y)
Fee-fi-mo-m(Y)
(X)!
Vowel as first letter of the name
If you have a vowel as the first letter of your name (e.g. Earl) you do not truncate the name.
The verse looks like this:
Earl, Earl, bo-bearl
Banana-fana fo-fearl
Fee-fi-mo-mearl
Earl!
'B', 'F' or 'M' as first letter of the name
In case of a 'B', an 'F' or an 'M' (e.g. Billy, Felix, Mary) there is a special rule.
The line which would 'rebuild' the name (e.g. bo-billy) is sang without the first letter of the name.
The verse for the name Billy looks like this:
Billy, Billy, bo-illy
Banana-fana fo-filly
Fee-fi-mo-milly
Billy!
For the name 'Felix', this would be right:
Felix, Felix, bo-belix
Banana-fana fo-elix
Fee-fi-mo-melix
Felix!
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 | fcn printVerse(name){
z,x := name[0].toLower(), z.toUpper() + name[1,*].toLower();
y:=( if("aeiou".holds(z)) name.toLower() else x[1,*] );
b,f,m := T("b","f","m").apply('wrap(c){ z==c and y or c+y });
println("%s, %s, bo-%s".fmt(x,x,b));
println("Banana-fana fo-",f);
println("Fee-fi-mo-",m);
println(x,"!\n");
} |
http://rosettacode.org/wiki/Test_integerness | Test integerness | Mathematically,
the integers Z are included in the rational numbers Q,
which are included in the real numbers R,
which can be generalized to the complex numbers C.
This means that each of those larger sets, and the data types used to represent them, include some integers.
Task[edit]
Given a rational, real, or complex number of any type, test whether it is mathematically an integer.
Your code should handle all numeric data types commonly used in your programming language.
Discuss any limitations of your code.
Definition
For the purposes of this task, integerness means that a number could theoretically be represented as an integer at no loss of precision (given an infinitely wide integer type).
In other words:
Set
Common representation
C++ type
Considered an integer...
rational numbers Q
fraction
std::ratio
...if its denominator is 1 (in reduced form)
real numbers Z
(approximated)
fixed-point
...if it has no non-zero digits after the decimal point
floating-point
float, double
...if the number of significant decimal places of its mantissa isn't greater than its exponent
complex numbers C
pair of real numbers
std::complex
...if its real part is considered an integer and its imaginary part is zero
Extra credit
Optionally, make your code accept a tolerance parameter for fuzzy testing. The tolerance is the maximum amount by which the number may differ from the nearest integer, to still be considered an integer.
This is useful in practice, because when dealing with approximate numeric types (such as floating point), there may already be round-off errors from previous calculations. For example, a float value of 0.9999999998 might actually be intended to represent the integer 1.
Test cases
Input
Output
Comment
Type
Value
exact
tolerance = 0.00001
decimal
25.000000
true
24.999999
false
true
25.000100
false
floating-point
-2.1e120
true
This one is tricky, because in most languages it is too large to fit into a native integer type.
It is, nonetheless, mathematically an integer, and your code should identify it as such.
-5e-2
false
NaN
false
Inf
false
This one is debatable. If your code considers it an integer, that's okay too.
complex
5.0+0.0i
true
5-5i
false
(The types and notations shown in these tables are merely examples – you should use the native data types and number literals of your programming language and standard library. Use a different set of test-cases, if this one doesn't demonstrate all relevant behavior.)
| #AWK | AWK |
# syntax: GAWK -f TEST_INTEGERNESS.AWK
BEGIN {
n = split("25.000000,24.999999,25.000100,-2.1e120,-5e-2,NaN,Inf,-0.05",arr,",")
for (i=1; i<=n; i++) {
s = arr[i]
x = (s == int(s)) ? 1 : 0
printf("%d %s\n",x,s)
}
exit(0)
}
|
http://rosettacode.org/wiki/Test_integerness | Test integerness | Mathematically,
the integers Z are included in the rational numbers Q,
which are included in the real numbers R,
which can be generalized to the complex numbers C.
This means that each of those larger sets, and the data types used to represent them, include some integers.
Task[edit]
Given a rational, real, or complex number of any type, test whether it is mathematically an integer.
Your code should handle all numeric data types commonly used in your programming language.
Discuss any limitations of your code.
Definition
For the purposes of this task, integerness means that a number could theoretically be represented as an integer at no loss of precision (given an infinitely wide integer type).
In other words:
Set
Common representation
C++ type
Considered an integer...
rational numbers Q
fraction
std::ratio
...if its denominator is 1 (in reduced form)
real numbers Z
(approximated)
fixed-point
...if it has no non-zero digits after the decimal point
floating-point
float, double
...if the number of significant decimal places of its mantissa isn't greater than its exponent
complex numbers C
pair of real numbers
std::complex
...if its real part is considered an integer and its imaginary part is zero
Extra credit
Optionally, make your code accept a tolerance parameter for fuzzy testing. The tolerance is the maximum amount by which the number may differ from the nearest integer, to still be considered an integer.
This is useful in practice, because when dealing with approximate numeric types (such as floating point), there may already be round-off errors from previous calculations. For example, a float value of 0.9999999998 might actually be intended to represent the integer 1.
Test cases
Input
Output
Comment
Type
Value
exact
tolerance = 0.00001
decimal
25.000000
true
24.999999
false
true
25.000100
false
floating-point
-2.1e120
true
This one is tricky, because in most languages it is too large to fit into a native integer type.
It is, nonetheless, mathematically an integer, and your code should identify it as such.
-5e-2
false
NaN
false
Inf
false
This one is debatable. If your code considers it an integer, that's okay too.
complex
5.0+0.0i
true
5-5i
false
(The types and notations shown in these tables are merely examples – you should use the native data types and number literals of your programming language and standard library. Use a different set of test-cases, if this one doesn't demonstrate all relevant behavior.)
| #C | C |
#include <stdio.h>
#include <complex.h>
#include <math.h>
/* Testing macros */
#define FMTSPEC(arg) _Generic((arg), \
float: "%f", double: "%f", \
long double: "%Lf", unsigned int: "%u", \
unsigned long: "%lu", unsigned long long: "%llu", \
int: "%d", long: "%ld", long long: "%lld", \
default: "(invalid type (%p)")
#define CMPPARTS(x, y) ((long double complex)((long double)(x) + \
I * (long double)(y)))
#define TEST_CMPL(i, j)\
printf(FMTSPEC(i), i), printf(" + "), printf(FMTSPEC(j), j), \
printf("i = %s\n", (isint(CMPPARTS(i, j)) ? "true" : "false"))
#define TEST_REAL(i)\
printf(FMTSPEC(i), i), printf(" = %s\n", (isint(i) ? "true" : "false"))
/* Main code */
static inline int isint(long double complex n)
{
return cimagl(n) == 0 && nearbyintl(creall(n)) == creall(n);
}
int main(void)
{
TEST_REAL(0);
TEST_REAL(-0);
TEST_REAL(-2);
TEST_REAL(-2.00000000000001);
TEST_REAL(5);
TEST_REAL(7.3333333333333);
TEST_REAL(3.141592653589);
TEST_REAL(-9.223372036854776e18);
TEST_REAL(5e-324);
TEST_REAL(NAN);
TEST_CMPL(6, 0);
TEST_CMPL(0, 1);
TEST_CMPL(0, 0);
TEST_CMPL(3.4, 0);
/* Demonstrating that we can use the same function for complex values
* constructed in the standard way */
double complex test1 = 5 + 0*I,
test2 = 3.4f,
test3 = 3,
test4 = 0 + 1.2*I;
printf("Test 1 (5+i) = %s\n", isint(test1) ? "true" : "false");
printf("Test 2 (3.4+0i) = %s\n", isint(test2) ? "true" : "false");
printf("Test 3 (3+0i) = %s\n", isint(test3) ? "true" : "false");
printf("Test 4 (0+1.2i) = %s\n", isint(test4) ? "true" : "false");
}
|
http://rosettacode.org/wiki/Text_processing/Max_licenses_in_use | Text processing/Max licenses in use | A company currently pays a fixed sum for the use of a particular licensed software package. In determining if it has a good deal it decides to calculate its maximum use of the software from its license management log file.
Assume the software's licensing daemon faithfully records a checkout event when a copy of the software starts and a checkin event when the software finishes to its log file.
An example of checkout and checkin events are:
License OUT @ 2008/10/03_23:51:05 for job 4974
...
License IN @ 2008/10/04_00:18:22 for job 4974
Task
Save the 10,000 line log file from here into a local file, then write a program to scan the file extracting both the maximum licenses that were out at any time, and the time(s) at which this occurs.
Mirror of log file available as a zip here (offsite mirror).
| #J | J | require 'files'
'I D' =: (8 ; 14+i.19) {"1 &.> <'m' fread 'licenses.txt' NB. read file as matrix, select columns
lu =: +/\ _1 ^ 'OI' i. I NB. Number of licenses in use at any given time
mx =: (I.@:= >./) lu NB. Indicies of maxima
NB. Output results
(mx { D) ,~ 'Maximum simultaneous license use is ' , ' at the following times:' ,~ ": {. ,mx { lu |
http://rosettacode.org/wiki/Test_a_function | Test a function |
Task
Using a well-known testing-specific library/module/suite for your language, write some tests for your language's entry in Palindrome.
If your language does not have a testing specific library well known to the language's community then state this or omit the language.
| #C | C | #include <assert.h>
int IsPalindrome(char *Str);
int main()
{
assert(IsPalindrome("racecar"));
assert(IsPalindrome("alice"));
}
|
http://rosettacode.org/wiki/Test_a_function | Test a function |
Task
Using a well-known testing-specific library/module/suite for your language, write some tests for your language's entry in Palindrome.
If your language does not have a testing specific library well known to the language's community then state this or omit the language.
| #C.23 | C# |
using Microsoft.VisualStudio.TestTools.UnitTesting;
using PalindromeDetector.ConsoleApp;
namespace PalindromeDetector.VisualStudioTests
{
[TestClass]
public class VSTests
{
[TestMethod]
public void PalindromeDetectorCanUnderstandPalindrome()
{
//Microsoft.VisualStudio.QualityTools.UnitTestFramework v4.0.30319
bool expected = true;
bool actual;
actual = Program.IsPalindrome("1");
Assert.AreEqual(expected, actual);
actual = Program.IsPalindromeNonRecursive("1");
Assert.AreEqual(expected, actual);
actual = Program.IsPalindrome("ingirumimusnocteetconsumimurigni");
Assert.AreEqual(expected, actual);
actual = Program.IsPalindromeNonRecursive("ingirumimusnocteetconsumimurigni");
Assert.AreEqual(expected, actual);
}
[TestMethod]
public void PalindromeDetecotryCanUnderstandNonPalindrome()
{
bool notExpected = true;
bool actual = Program.IsPalindrome("ThisIsNotAPalindrome");
Assert.AreNotEqual(notExpected, actual);
actual = Program.IsPalindromeNonRecursive("ThisIsNotAPalindrome");
Assert.AreNotEqual(notExpected, actual);
}
}
} |
http://rosettacode.org/wiki/Text_processing/2 | Text processing/2 | The following task concerns data that came from a pollution monitoring station with twenty-four instruments monitoring twenty-four aspects of pollution in the air. Periodically a record is added to the file, each record being a line of 49 fields separated by white-space, which can be one or more space or tab characters.
The fields (from the left) are:
DATESTAMP [ VALUEn FLAGn ] * 24
i.e. a datestamp followed by twenty-four repetitions of a floating-point instrument value and that instrument's associated integer flag. Flag values are >= 1 if the instrument is working and < 1 if there is some problem with it, in which case that instrument's value should be ignored.
A sample from the full data file readings.txt, which is also used in the Text processing/1 task, follows:
Data is no longer available at that link. Zipped mirror available here
1991-03-30 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1
1991-03-31 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 20.000 1 20.000 1 20.000 1 35.000 1 50.000 1 60.000 1 40.000 1 30.000 1 30.000 1 30.000 1 25.000 1 20.000 1 20.000 1 20.000 1 20.000 1 20.000 1 35.000 1
1991-03-31 40.000 1 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2
1991-04-01 0.000 -2 13.000 1 16.000 1 21.000 1 24.000 1 22.000 1 20.000 1 18.000 1 29.000 1 44.000 1 50.000 1 43.000 1 38.000 1 27.000 1 27.000 1 24.000 1 23.000 1 18.000 1 12.000 1 13.000 1 14.000 1 15.000 1 13.000 1 10.000 1
1991-04-02 8.000 1 9.000 1 11.000 1 12.000 1 12.000 1 12.000 1 27.000 1 26.000 1 27.000 1 33.000 1 32.000 1 31.000 1 29.000 1 31.000 1 25.000 1 25.000 1 24.000 1 21.000 1 17.000 1 14.000 1 15.000 1 12.000 1 12.000 1 10.000 1
1991-04-03 10.000 1 9.000 1 10.000 1 10.000 1 9.000 1 10.000 1 15.000 1 24.000 1 28.000 1 24.000 1 18.000 1 14.000 1 12.000 1 13.000 1 14.000 1 15.000 1 14.000 1 15.000 1 13.000 1 13.000 1 13.000 1 12.000 1 10.000 1 10.000 1
Task
Confirm the general field format of the file.
Identify any DATESTAMPs that are duplicated.
Report the number of records that have good readings for all instruments.
| #PL.2FI | PL/I |
/* To process readings produced by automatic reading stations. */
check: procedure options (main);
declare 1 date, 2 (yy, mm, dd) character (2),
(j1, j2) character (1);
declare old_date character (6);
declare line character (330) varying;
declare R(24) fixed decimal, Machine(24) fixed binary;
declare (i, k, n, faulty static initial (0)) fixed binary;
declare input file;
open file (input) title ('/READINGS.TXT,TYPE(CRLF),RECSIZE(300)');
on endfile (input) go to done;
old_date = '';
k = 0;
do forever;
k = k + 1;
get file (input) edit (line) (L);
get string(line) edit (yy, j1, mm, j2, dd) (a(4), a(1), a(2), a(1), a(2));
line = substr(line, 11);
do i = 1 to length(line);
if substr(line, i, 1) = '09'x then substr(line, i, 1) = ' ';
end;
line = trim(line);
n = tally(line, ' ') - tally (line, ' ') + 1;
if n ^= 48 then
do;
put skip list ('There are ' || n || ' readings in line ' || k);
end;
n = n/2;
line = line || ' ';
get string(line) list ((R(i), Machine(i) do i = 1 to n));
if any(Machine < 1) ^= '0'B then
faulty = faulty + 1;
if old_date ^= ' ' then if old_date = string(date) then
put skip list ('Dates are the same at line' || k);
old_date = string(date);
end;
done:
put skip list ('There were ' || k || ' sets of readings');
put skip list ('There were ' || faulty || ' faulty readings' );
put skip list ('There were ' || k-faulty || ' good readings' );
end check;
|
http://rosettacode.org/wiki/Terminal_control/Unicode_output | Terminal control/Unicode output | The task is to check that the terminal supports Unicode output, before outputting a Unicode character. If the terminal supports Unicode, then the terminal should output a Unicode delta (U+25b3). If the terminal does not support Unicode, then an appropriate error should be raised.
Note that it is permissible to use system configuration data to determine terminal capabilities if the system provides such a facility.
| #Seed7 | Seed7 | $ include "seed7_05.s7i";
include "environment.s7i";
include "console.s7i";
const proc: main is func
begin
if pos(lower(getenv("LANG")), "utf") <> 0 or
pos(lower(getenv("LC_ALL")), "utf") <> 0 or
pos(lower(getenv("LC_CTYPE")), "utf") <> 0 then
writeln(STD_CONSOLE, "Unicode is supported on this terminal and U+25B3 is: △");
else
writeln("Unicode is not supported on this terminal.");
end if;
end func; |
http://rosettacode.org/wiki/Terminal_control/Unicode_output | Terminal control/Unicode output | The task is to check that the terminal supports Unicode output, before outputting a Unicode character. If the terminal supports Unicode, then the terminal should output a Unicode delta (U+25b3). If the terminal does not support Unicode, then an appropriate error should be raised.
Note that it is permissible to use system configuration data to determine terminal capabilities if the system provides such a facility.
| #Sidef | Sidef | if (/\bUTF-?8/i ~~ [ENV{"LC_ALL","LC_CTYPE","LANG"}]) {
say "△"
} else {
die "Terminal can't handle UTF-8.\n";
} |
http://rosettacode.org/wiki/Terminal_control/Unicode_output | Terminal control/Unicode output | The task is to check that the terminal supports Unicode output, before outputting a Unicode character. If the terminal supports Unicode, then the terminal should output a Unicode delta (U+25b3). If the terminal does not support Unicode, then an appropriate error should be raised.
Note that it is permissible to use system configuration data to determine terminal capabilities if the system provides such a facility.
| #Tcl | Tcl | # Check if we're using one of the UTF or "unicode" encodings
if {[string match utf-* [encoding system]] || [string match *unicode* [encoding system]]} {
puts "\u25b3"
} else {
error "terminal does not support unicode (probably)"
} |
http://rosettacode.org/wiki/Terminal_control/Ringing_the_terminal_bell | Terminal control/Ringing the terminal bell |
Task
Make the terminal running the program ring its "bell".
On modern terminal emulators, this may be done by playing some other sound which might or might not be configurable, or by flashing the title bar or inverting the colors of the screen, but was classically a physical bell within the terminal. It is usually used to indicate a problem where a wrong character has been typed.
In most terminals, if the Bell character (ASCII code 7, \a in C) is printed by the program, it will cause the terminal to ring its bell. This is a function of the terminal, and is independent of the programming language of the program, other than the ability to print a particular character to standard out.
| #C.2B.2B | C++ | #include <iostream>
int main() {
std::cout << "\a";
return 0;
} |
http://rosettacode.org/wiki/Terminal_control/Ringing_the_terminal_bell | Terminal control/Ringing the terminal bell |
Task
Make the terminal running the program ring its "bell".
On modern terminal emulators, this may be done by playing some other sound which might or might not be configurable, or by flashing the title bar or inverting the colors of the screen, but was classically a physical bell within the terminal. It is usually used to indicate a problem where a wrong character has been typed.
In most terminals, if the Bell character (ASCII code 7, \a in C) is printed by the program, it will cause the terminal to ring its bell. This is a function of the terminal, and is independent of the programming language of the program, other than the ability to print a particular character to standard out.
| #Clojure | Clojure | (println (char 7)) |
http://rosettacode.org/wiki/Terminal_control/Ringing_the_terminal_bell | Terminal control/Ringing the terminal bell |
Task
Make the terminal running the program ring its "bell".
On modern terminal emulators, this may be done by playing some other sound which might or might not be configurable, or by flashing the title bar or inverting the colors of the screen, but was classically a physical bell within the terminal. It is usually used to indicate a problem where a wrong character has been typed.
In most terminals, if the Bell character (ASCII code 7, \a in C) is printed by the program, it will cause the terminal to ring its bell. This is a function of the terminal, and is independent of the programming language of the program, other than the ability to print a particular character to standard out.
| #COBOL | COBOL | DISPLAY SPACE WITH BELL |
http://rosettacode.org/wiki/The_ISAAC_Cipher | The ISAAC Cipher | ISAAC is a cryptographically secure pseudo-random number generator (CSPRNG) and stream cipher. It was developed by Bob Jenkins from 1993 (http://burtleburtle.net/bob/rand/isaac.html) and placed in the Public Domain. ISAAC is fast - especially when optimised - and portable to most architectures in nearly all programming and scripting languages.
It is also simple and succinct, using as it does just two 256-word arrays for its state.
ISAAC stands for "Indirection, Shift, Accumulate, Add, and Count" which are the principal bitwise operations employed.
To date - and that's after more than 20 years of existence - ISAAC has not been broken (unless GCHQ or NSA did it, but they wouldn't be telling).
ISAAC thus deserves a lot more attention than it has hitherto received and it would be salutary to see it more universally implemented.
Task
Translate ISAAC's reference C or Pascal code into your language of choice.
The RNG should then be seeded with the string "this is my secret key" and
finally the message "a Top Secret secret" should be encrypted on that key.
Your program's output cipher-text will be a string of hexadecimal digits.
Optional: Include a decryption check by re-initializing ISAAC and performing
the same encryption pass on the cipher-text.
Please use the C or Pascal as a reference guide to these operations.
Two encryption schemes are possible:
(1) XOR (Vernam) or
(2) Caesar-shift mod 95 (Vigenère).
XOR is the simplest; C-shifting offers greater security.
You may choose either scheme, or both, but please specify which you used.
Here are the alternative sample outputs for checking purposes:
Message: a Top Secret secret
Key : this is my secret key
XOR : 1C0636190B1260233B35125F1E1D0E2F4C5422
MOD : 734270227D36772A783B4F2A5F206266236978
XOR dcr: a Top Secret secret
MOD dcr: a Top Secret secret
No official seeding method for ISAAC has been published, but for this task
we may as well just inject the bytes of our key into the randrsl array,
padding with zeroes before mixing, like so:
// zeroise mm array
FOR i:= 0 TO 255 DO mm[i]:=0;
// check seed's highest array element
m := High(seed);
// inject the seed
FOR i:= 0 TO 255 DO BEGIN
// in case seed[] has less than 256 elements.
IF i>m THEN randrsl[i]:=0
ELSE randrsl[i]:=seed[i];
END;
// initialize ISAAC with seed
RandInit(true);
ISAAC can of course also be initialized with a single 32-bit unsigned integer in the manner of traditional RNGs, and indeed used as such for research and gaming purposes.
But building a strong and simple ISAAC-based stream cipher - replacing the irreparably broken RC4 - is our goal here: ISAAC's intended purpose.
| #C.23 | C# |
using System;
namespace cipher {
static class Cipher {
// external results
static uint[] randrsl = new uint[256];
static uint randcnt;
// internal state
static uint[] mm = new uint[256];
static uint aa=0, bb=0, cc=0;
static void isaac() {
uint i,x,y;
cc++; // cc just gets incremented once per 256 results
bb+=cc; // then combined with bb
for (i=0; i<=255; i++) {
x = mm[i];
switch (i & 3) {
case 0: aa = aa ^ (aa << 13); break;
case 1: aa = aa ^ (aa >> 6); break;
case 2: aa = aa ^ (aa << 2); break;
case 3: aa = aa ^ (aa >> 16); break;
}
aa = mm[(i+128) & 255] + aa;
y = mm[(x >> 2) & 255] + aa + bb;
mm[i] = y;
bb = mm[(y >> 10) & 255] + x;
randrsl[i]= bb;
}
}
// if (flag==TRUE), then use the contents of randrsl[] to initialize mm[].
static void mix(ref uint a, ref uint b, ref uint c, ref uint d, ref uint e, ref uint f, ref uint g, ref uint h) {
a = a ^ b << 11; d+=a; b+=c;
b = b ^ c >> 2; e+=b; c+=d;
c = c ^ d << 8; f+=c; d+=e;
d = d ^ e >> 16; g+=d; e+=f;
e = e ^ f << 10; h+=e; f+=g;
f = f ^ g >> 4; a+=f; g+=h;
g = g ^ h << 8; b+=g; h+=a;
h = h ^ a >> 9; c+=h; a+=b;
}
static void Init(bool flag) {
short i; uint a,b,c,d,e,f,g,h;
aa=0; bb=0; cc=0;
a=0x9e3779b9; b=a; c=a; d=a;
e=a; f=a; g=a; h=a;
for (i=0; i<=3; i++) // scramble it
mix(ref a,ref b,ref c,ref d,ref e,ref f,ref g,ref h);
i=0;
do { // fill in mm[] with messy stuff
if (flag) { // use all the information in the seed
a+=randrsl[i ]; b+=randrsl[i+1]; c+=randrsl[i+2]; d+=randrsl[i+3];
e+=randrsl[i+4]; f+=randrsl[i+5]; g+=randrsl[i+6]; h+=randrsl[i+7];
} // if flag
mix(ref a,ref b,ref c,ref d,ref e,ref f,ref g,ref h);
mm[i ]=a; mm[i+1]=b; mm[i+2]=c; mm[i+3]=d;
mm[i+4]=e; mm[i+5]=f; mm[i+6]=g; mm[i+7]=h;
i+=8;
}
while (i<255);
if (flag) {
// do a second pass to make all of the seed affect all of mm
i=0;
do {
a+=mm[i ]; b+=mm[i+1]; c+=mm[i+2]; d+=mm[i+3];
e+=mm[i+4]; f+=mm[i+5]; g+=mm[i+6]; h+=mm[i+7];
mix(ref a,ref b,ref c,ref d,ref e,ref f,ref g,ref h);
mm[i ]=a; mm[i+1]=b; mm[i+2]=c; mm[i+3]=d;
mm[i+4]=e; mm[i+5]=f; mm[i+6]=g; mm[i+7]=h;
i+=8;
}
while (i<255);
}
isaac(); // fill in the first set of results
randcnt=0; // prepare to use the first set of results
}
// Seed ISAAC with a string
static void Seed(string seed, bool flag) {
for (int i=0; i<256; i++) mm[i]=0;
for (int i=0; i<256; i++) randrsl[i]=0;
int m = seed.Length;
for (int i=0; i<m; i++) {
randrsl[i] = seed[i];
}
// initialize ISAAC with seed
Init(flag);
}
// Get a random 32-bit value
static uint Random() {
uint result = randrsl[randcnt];
randcnt++;
if (randcnt>255) {
isaac(); randcnt=0;
}
return result;
}
// Get a random character in printable ASCII range
static byte RandA() {
return (byte)(Random() % 95 + 32);
}
// XOR encrypt on random stream. Output: ASCII byte array
static byte[] Vernam(string msg)
{
int n,l;
byte[] v = new byte[msg.Length];
l = msg.Length;
// XOR message
for (n=0; n<l; n++) {
v[n] = (byte) (RandA() ^ (byte)msg[n]);
}
return v;
}
public static void Main() {
string msg = "a Top Secret secret";
string key = "this is my secret key";
byte[] xctx= new byte[msg.Length];
byte[] xptx= new byte[msg.Length];
string xtcx= "*******************";
string xtpx= "*******************";
Seed(key,true);
// XOR encrypt
xctx = Vernam(msg);
xtcx = System.Text.Encoding.ASCII.GetString(xctx);
// XOR decrypt
Seed(key,true);
xptx = Vernam(xtcx);
xtpx = System.Text.Encoding.ASCII.GetString(xptx);
Console.WriteLine("Message: "+msg);
Console.WriteLine("Key : "+key);
Console.Write ("XOR : ");
// output ciphertext as a string of hexadecimal digits
for (int n=0; n<xctx.Length; n++) Console.Write("{0:X2}", xctx[n]);
Console.WriteLine("\nXOR dcr: "+xtpx);
}
}
}
|
http://rosettacode.org/wiki/Test_integerness | Test integerness | Mathematically,
the integers Z are included in the rational numbers Q,
which are included in the real numbers R,
which can be generalized to the complex numbers C.
This means that each of those larger sets, and the data types used to represent them, include some integers.
Task[edit]
Given a rational, real, or complex number of any type, test whether it is mathematically an integer.
Your code should handle all numeric data types commonly used in your programming language.
Discuss any limitations of your code.
Definition
For the purposes of this task, integerness means that a number could theoretically be represented as an integer at no loss of precision (given an infinitely wide integer type).
In other words:
Set
Common representation
C++ type
Considered an integer...
rational numbers Q
fraction
std::ratio
...if its denominator is 1 (in reduced form)
real numbers Z
(approximated)
fixed-point
...if it has no non-zero digits after the decimal point
floating-point
float, double
...if the number of significant decimal places of its mantissa isn't greater than its exponent
complex numbers C
pair of real numbers
std::complex
...if its real part is considered an integer and its imaginary part is zero
Extra credit
Optionally, make your code accept a tolerance parameter for fuzzy testing. The tolerance is the maximum amount by which the number may differ from the nearest integer, to still be considered an integer.
This is useful in practice, because when dealing with approximate numeric types (such as floating point), there may already be round-off errors from previous calculations. For example, a float value of 0.9999999998 might actually be intended to represent the integer 1.
Test cases
Input
Output
Comment
Type
Value
exact
tolerance = 0.00001
decimal
25.000000
true
24.999999
false
true
25.000100
false
floating-point
-2.1e120
true
This one is tricky, because in most languages it is too large to fit into a native integer type.
It is, nonetheless, mathematically an integer, and your code should identify it as such.
-5e-2
false
NaN
false
Inf
false
This one is debatable. If your code considers it an integer, that's okay too.
complex
5.0+0.0i
true
5-5i
false
(The types and notations shown in these tables are merely examples – you should use the native data types and number literals of your programming language and standard library. Use a different set of test-cases, if this one doesn't demonstrate all relevant behavior.)
| #C.23 | C# |
namespace Test_integerness
{
class Program
{
public static void Main(string[] args)
{
Console.Clear();
Console.WriteLine();
Console.WriteLine(" ***************************************************");
Console.WriteLine(" * *");
Console.WriteLine(" * Integerness test *");
Console.WriteLine(" * *");
Console.WriteLine(" ***************************************************");
Console.WriteLine();
ConsoleKeyInfo key = new ConsoleKeyInfo('Y',ConsoleKey.Y,true,true,true);
while(key.Key == ConsoleKey.Y)
{
// Get number value from keyboard
Console.Write(" Enter number value : ");
string LINE = Console.ReadLine();
// Get tolerance value from keyboard
Console.Write(" Enter tolerance value : ");
double TOLERANCE = double.Parse(Console.ReadLine());
// Resolve entered number format and set NUMBER value
double NUMBER = 0;
string [] N;
// Real number value
if(!double.TryParse(LINE, out NUMBER))
{
// Rational number value
if(LINE.Contains("/"))
{
N = LINE.Split('/');
NUMBER = double.Parse(N[0]) / double.Parse(N[1]);
}
// Inf value
else if(LINE.ToUpper().Contains("INF"))
{
NUMBER = double.PositiveInfinity;
}
// Complex value
else if(LINE.ToUpper().Contains("I"))
{
// Delete letter i
LINE = LINE.ToUpper().Replace("I","");
string r = string.Empty; // real part
string i = string.Empty; // imaginary part
int s = 1; // sign offset
// Get sign
if(LINE[0]=='+' || LINE[0]=='-')
{
r+=LINE[0].ToString();
LINE = LINE.Remove(0,1);
s--;
}
// Get real part
foreach (char element in LINE)
{
if(element!='+' && element!='-')
r+=element.ToString();
else
break;
}
// get imaginary part
i = LINE.Substring(LINE.Length-(r.Length+s));
NUMBER = double.Parse(i);
if(NUMBER==0)
NUMBER = double.Parse(r);
else
NUMBER = double.NaN;
}
// NaN value
else
NUMBER = double.NaN;
}
// Test
bool IS_INTEGER = false;
bool IS_INTEGER_T = false;
if(double.IsNaN(NUMBER))
IS_INTEGER=false;
else if(Math.Round(NUMBER,0).ToString() == NUMBER.ToString())
IS_INTEGER = true;
else if((decimal)TOLERANCE >= (decimal)Math.Abs( (decimal)Math.Round(NUMBER,0) - (decimal)NUMBER ))
IS_INTEGER_T = true;
if(IS_INTEGER)
Console.WriteLine(" Is exact integer " + IS_INTEGER);
else
{
Console.WriteLine( " Is exact integer " + IS_INTEGER );
Console.WriteLine( " Is integer with tolerance " + IS_INTEGER_T );
}
Console.WriteLine();
Console.Write(" Another test < Y /N > . . . ");
key = Console.ReadKey(true);
Console.WriteLine();
Console.WriteLine();
}
}
}
}
|
http://rosettacode.org/wiki/Text_processing/Max_licenses_in_use | Text processing/Max licenses in use | A company currently pays a fixed sum for the use of a particular licensed software package. In determining if it has a good deal it decides to calculate its maximum use of the software from its license management log file.
Assume the software's licensing daemon faithfully records a checkout event when a copy of the software starts and a checkin event when the software finishes to its log file.
An example of checkout and checkin events are:
License OUT @ 2008/10/03_23:51:05 for job 4974
...
License IN @ 2008/10/04_00:18:22 for job 4974
Task
Save the 10,000 line log file from here into a local file, then write a program to scan the file extracting both the maximum licenses that were out at any time, and the time(s) at which this occurs.
Mirror of log file available as a zip here (offsite mirror).
| #Java | Java | import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.LinkedList;
public class License {
public static void main(String[] args) throws FileNotFoundException, IOException{
BufferedReader in = new BufferedReader(new FileReader(args[0]));
int max = Integer.MIN_VALUE;
LinkedList<String> dates = new LinkedList<String>();
String line;
int count = 0;
while((line = in.readLine()) != null){
if(line.startsWith("License OUT ")) count++;
if(line.startsWith("License IN ")) count--;
if(count > max){
max = count;
String date = line.split(" ")[3];
dates.clear();
dates.add(date);
}else if(count == max){
String date = line.split(" ")[3];
dates.add(date);
}
}
System.out.println("Max licenses out: "+max);
System.out.println("At time(s): "+dates);
}
} |
http://rosettacode.org/wiki/Test_a_function | Test a function |
Task
Using a well-known testing-specific library/module/suite for your language, write some tests for your language's entry in Palindrome.
If your language does not have a testing specific library well known to the language's community then state this or omit the language.
| #C.2B.2B | C++ | #include <algorithm>
#include <string>
constexpr bool is_palindrome(std::string_view s)
{
return std::equal(s.begin(), s.begin()+s.length()/2, s.rbegin());
}
|
http://rosettacode.org/wiki/Test_a_function | Test a function |
Task
Using a well-known testing-specific library/module/suite for your language, write some tests for your language's entry in Palindrome.
If your language does not have a testing specific library well known to the language's community then state this or omit the language.
| #Clojure | Clojure |
(use 'clojure.test)
(deftest test-palindrome?
(is (palindrome? "amanaplanacanalpanama"))
(is (not (palindrome? "Test 1, 2, 3")))
(run-tests)
|
http://rosettacode.org/wiki/Text_processing/2 | Text processing/2 | The following task concerns data that came from a pollution monitoring station with twenty-four instruments monitoring twenty-four aspects of pollution in the air. Periodically a record is added to the file, each record being a line of 49 fields separated by white-space, which can be one or more space or tab characters.
The fields (from the left) are:
DATESTAMP [ VALUEn FLAGn ] * 24
i.e. a datestamp followed by twenty-four repetitions of a floating-point instrument value and that instrument's associated integer flag. Flag values are >= 1 if the instrument is working and < 1 if there is some problem with it, in which case that instrument's value should be ignored.
A sample from the full data file readings.txt, which is also used in the Text processing/1 task, follows:
Data is no longer available at that link. Zipped mirror available here
1991-03-30 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1
1991-03-31 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 20.000 1 20.000 1 20.000 1 35.000 1 50.000 1 60.000 1 40.000 1 30.000 1 30.000 1 30.000 1 25.000 1 20.000 1 20.000 1 20.000 1 20.000 1 20.000 1 35.000 1
1991-03-31 40.000 1 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2
1991-04-01 0.000 -2 13.000 1 16.000 1 21.000 1 24.000 1 22.000 1 20.000 1 18.000 1 29.000 1 44.000 1 50.000 1 43.000 1 38.000 1 27.000 1 27.000 1 24.000 1 23.000 1 18.000 1 12.000 1 13.000 1 14.000 1 15.000 1 13.000 1 10.000 1
1991-04-02 8.000 1 9.000 1 11.000 1 12.000 1 12.000 1 12.000 1 27.000 1 26.000 1 27.000 1 33.000 1 32.000 1 31.000 1 29.000 1 31.000 1 25.000 1 25.000 1 24.000 1 21.000 1 17.000 1 14.000 1 15.000 1 12.000 1 12.000 1 10.000 1
1991-04-03 10.000 1 9.000 1 10.000 1 10.000 1 9.000 1 10.000 1 15.000 1 24.000 1 28.000 1 24.000 1 18.000 1 14.000 1 12.000 1 13.000 1 14.000 1 15.000 1 14.000 1 15.000 1 13.000 1 13.000 1 13.000 1 12.000 1 10.000 1 10.000 1
Task
Confirm the general field format of the file.
Identify any DATESTAMPs that are duplicated.
Report the number of records that have good readings for all instruments.
| #PowerShell | PowerShell | $dateHash = @{}
$goodLineCount = 0
get-content c:\temp\readings.txt |
ForEach-Object {
$line = $_.split(" |`t",2)
if ($dateHash.containskey($line[0])) {
$line[0] + " is duplicated"
} else {
$dateHash.add($line[0], $line[1])
}
$readings = $line[1].split()
$goodLine = $true
if ($readings.count -ne 48) { $goodLine = $false; "incorrect line length : $line[0]" }
for ($i=0; $i -lt $readings.count; $i++) {
if ($i % 2 -ne 0) {
if ([int]$readings[$i] -lt 1) {
$goodLine = $false
}
}
}
if ($goodLine) { $goodLineCount++ }
}
[string]$goodLineCount + " good lines"
|
http://rosettacode.org/wiki/Terminal_control/Unicode_output | Terminal control/Unicode output | The task is to check that the terminal supports Unicode output, before outputting a Unicode character. If the terminal supports Unicode, then the terminal should output a Unicode delta (U+25b3). If the terminal does not support Unicode, then an appropriate error should be raised.
Note that it is permissible to use system configuration data to determine terminal capabilities if the system provides such a facility.
| #UNIX_Shell | UNIX Shell | unicode_tty() {
# LC_ALL supersedes LC_CTYPE, which supersedes LANG.
# Set $1 to environment value.
case y in
${LC_ALL:+y}) set -- "$LC_ALL";;
${LC_CTYPE:+y}) set -- "$LC_CTYPE";;
${LANG:+y}) set -- "$LANG";;
y) return 1;; # Assume "C" locale not UTF-8.
esac
# We use 'case' to perform pattern matching against a string.
case "$1" in
*UTF-8*) return 0;;
*) return 1;;
esac
}
if unicode_tty; then
# printf might not know \u or \x, so use octal.
# U+25B3 => UTF-8 342 226 263
printf "\342\226\263\n"
else
echo "HW65001 This program requires a Unicode compatible terminal" >&2
exit 252 # Incompatible hardware
fi |
http://rosettacode.org/wiki/Terminal_control/Unicode_output | Terminal control/Unicode output | The task is to check that the terminal supports Unicode output, before outputting a Unicode character. If the terminal supports Unicode, then the terminal should output a Unicode delta (U+25b3). If the terminal does not support Unicode, then an appropriate error should be raised.
Note that it is permissible to use system configuration data to determine terminal capabilities if the system provides such a facility.
| #Wren | Wren | /* terminal_control_unicode_output.wren */
class C {
foreign static isUnicodeSupported
}
if (C.isUnicodeSupported) {
System.print("Unicode is supported on this terminal and U+25B3 is : \u25b3")
} else {
System.print("Unicode is not supported on this terminal.")
} |
http://rosettacode.org/wiki/Terminal_control/Unicode_output | Terminal control/Unicode output | The task is to check that the terminal supports Unicode output, before outputting a Unicode character. If the terminal supports Unicode, then the terminal should output a Unicode delta (U+25b3). If the terminal does not support Unicode, then an appropriate error should be raised.
Note that it is permissible to use system configuration data to determine terminal capabilities if the system provides such a facility.
| #zkl | zkl | if(System.isUnix and T("LC_CTYPE","LC_LANG","LANG").apply(System.getenv)
.filter().filter("holds","UTF"))
println("This terminal supports UTF-8 (\U25B3;)");
else println("I have doubts about UTF-8 on this terminal."); |
http://rosettacode.org/wiki/Terminal_control/Ringing_the_terminal_bell | Terminal control/Ringing the terminal bell |
Task
Make the terminal running the program ring its "bell".
On modern terminal emulators, this may be done by playing some other sound which might or might not be configurable, or by flashing the title bar or inverting the colors of the screen, but was classically a physical bell within the terminal. It is usually used to indicate a problem where a wrong character has been typed.
In most terminals, if the Bell character (ASCII code 7, \a in C) is printed by the program, it will cause the terminal to ring its bell. This is a function of the terminal, and is independent of the programming language of the program, other than the ability to print a particular character to standard out.
| #Common_Lisp | Common Lisp |
(format t "~C" (code-char 7))
|
http://rosettacode.org/wiki/Terminal_control/Ringing_the_terminal_bell | Terminal control/Ringing the terminal bell |
Task
Make the terminal running the program ring its "bell".
On modern terminal emulators, this may be done by playing some other sound which might or might not be configurable, or by flashing the title bar or inverting the colors of the screen, but was classically a physical bell within the terminal. It is usually used to indicate a problem where a wrong character has been typed.
In most terminals, if the Bell character (ASCII code 7, \a in C) is printed by the program, it will cause the terminal to ring its bell. This is a function of the terminal, and is independent of the programming language of the program, other than the ability to print a particular character to standard out.
| #D | D | void main() {
import std.stdio;
writeln('\a');
} |
http://rosettacode.org/wiki/Terminal_control/Ringing_the_terminal_bell | Terminal control/Ringing the terminal bell |
Task
Make the terminal running the program ring its "bell".
On modern terminal emulators, this may be done by playing some other sound which might or might not be configurable, or by flashing the title bar or inverting the colors of the screen, but was classically a physical bell within the terminal. It is usually used to indicate a problem where a wrong character has been typed.
In most terminals, if the Bell character (ASCII code 7, \a in C) is printed by the program, it will cause the terminal to ring its bell. This is a function of the terminal, and is independent of the programming language of the program, other than the ability to print a particular character to standard out.
| #Delphi | Delphi | program TerminalBell;
{$APPTYPE CONSOLE}
begin
Writeln(#7);
end. |
http://rosettacode.org/wiki/The_Twelve_Days_of_Christmas | The Twelve Days of Christmas | Task
Write a program that outputs the lyrics of the Christmas carol The Twelve Days of Christmas.
The lyrics can be found here.
(You must reproduce the words in the correct order, but case, format, and punctuation are left to your discretion.)
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #11l | 11l | V gifts = |‘A partridge in a pear tree.
Two turtle doves
Three french hens
Four calling birds
Five golden rings
Six geese a-laying
Seven swans a-swimming
Eight maids a-milking
Nine ladies dancing
Ten lords a-leaping
Eleven pipers piping
Twelve drummers drumming’.split("\n")
V days = ‘first second third fourth fifth sixth seventh eighth ninth tenth eleventh twelfth’.split(‘ ’)
L(day) days
V n = L.index + 1
V g = reversed(gifts[0 .< n])
print("\nOn the #. day of Christmas\nMy true love gave to me:\n".format(day)‘’g[0 .< (len)-1].join("\n")‘’(I n > 1 {" and\n"g.last} E g.last)) |
http://rosettacode.org/wiki/The_ISAAC_Cipher | The ISAAC Cipher | ISAAC is a cryptographically secure pseudo-random number generator (CSPRNG) and stream cipher. It was developed by Bob Jenkins from 1993 (http://burtleburtle.net/bob/rand/isaac.html) and placed in the Public Domain. ISAAC is fast - especially when optimised - and portable to most architectures in nearly all programming and scripting languages.
It is also simple and succinct, using as it does just two 256-word arrays for its state.
ISAAC stands for "Indirection, Shift, Accumulate, Add, and Count" which are the principal bitwise operations employed.
To date - and that's after more than 20 years of existence - ISAAC has not been broken (unless GCHQ or NSA did it, but they wouldn't be telling).
ISAAC thus deserves a lot more attention than it has hitherto received and it would be salutary to see it more universally implemented.
Task
Translate ISAAC's reference C or Pascal code into your language of choice.
The RNG should then be seeded with the string "this is my secret key" and
finally the message "a Top Secret secret" should be encrypted on that key.
Your program's output cipher-text will be a string of hexadecimal digits.
Optional: Include a decryption check by re-initializing ISAAC and performing
the same encryption pass on the cipher-text.
Please use the C or Pascal as a reference guide to these operations.
Two encryption schemes are possible:
(1) XOR (Vernam) or
(2) Caesar-shift mod 95 (Vigenère).
XOR is the simplest; C-shifting offers greater security.
You may choose either scheme, or both, but please specify which you used.
Here are the alternative sample outputs for checking purposes:
Message: a Top Secret secret
Key : this is my secret key
XOR : 1C0636190B1260233B35125F1E1D0E2F4C5422
MOD : 734270227D36772A783B4F2A5F206266236978
XOR dcr: a Top Secret secret
MOD dcr: a Top Secret secret
No official seeding method for ISAAC has been published, but for this task
we may as well just inject the bytes of our key into the randrsl array,
padding with zeroes before mixing, like so:
// zeroise mm array
FOR i:= 0 TO 255 DO mm[i]:=0;
// check seed's highest array element
m := High(seed);
// inject the seed
FOR i:= 0 TO 255 DO BEGIN
// in case seed[] has less than 256 elements.
IF i>m THEN randrsl[i]:=0
ELSE randrsl[i]:=seed[i];
END;
// initialize ISAAC with seed
RandInit(true);
ISAAC can of course also be initialized with a single 32-bit unsigned integer in the manner of traditional RNGs, and indeed used as such for research and gaming purposes.
But building a strong and simple ISAAC-based stream cipher - replacing the irreparably broken RC4 - is our goal here: ISAAC's intended purpose.
| #C.2B.2B | C++ |
#include <iomanip>
#include <iostream>
#include <sstream>
using namespace std;
enum CipherMode {ENCRYPT, DECRYPT};
// External results
uint32_t randRsl[256];
uint32_t randCnt;
// Internal state
uint32_t mm[256];
uint32_t aa = 0, bb = 0, cc = 0;
void isaac()
{
++cc; // cc just gets incremented once per 256 results
bb += cc; // then combined with bb
for (uint32_t i = 0; i < 256; ++i)
{
uint32_t x, y;
x = mm[i];
switch (i % 4)
{
case 0:
aa = aa ^ (aa << 13);
break;
case 1:
aa = aa ^ (aa >> 6);
break;
case 2:
aa = aa ^ (aa << 2);
break;
case 3:
aa = aa ^ (aa >> 16);
break;
}
aa = mm[(i + 128) % 256] + aa;
y = mm[(x >> 2) % 256] + aa + bb;
mm[i] = y;
bb = mm[(y >> 10) % 256] + x;
randRsl[i] = bb;
}
randCnt = 0; // Prepare to use the first set of results.
}
void mix(uint32_t a[])
{
a[0] = a[0] ^ a[1] << 11; a[3] += a[0]; a[1] += a[2];
a[1] = a[1] ^ a[2] >> 2; a[4] += a[1]; a[2] += a[3];
a[2] = a[2] ^ a[3] << 8; a[5] += a[2]; a[3] += a[4];
a[3] = a[3] ^ a[4] >> 16; a[6] += a[3]; a[4] += a[5];
a[4] = a[4] ^ a[5] << 10; a[7] += a[4]; a[5] += a[6];
a[5] = a[5] ^ a[6] >> 4; a[0] += a[5]; a[6] += a[7];
a[6] = a[6] ^ a[7] << 8; a[1] += a[6]; a[7] += a[0];
a[7] = a[7] ^ a[0] >> 9; a[2] += a[7]; a[0] += a[1];
}
void randInit(bool flag)
{
uint32_t a[8];
aa = bb = cc = 0;
a[0] = 2654435769UL; // 0x9e3779b9: the golden ratio
for (uint32_t j = 1; j < 8; ++j)
a[j] = a[0];
for (uint32_t i = 0; i < 4; ++i) // Scramble it.
mix(a);
for (uint32_t i = 0; i < 256; i += 8) // Fill in mm[] with messy stuff.
{
if (flag) // Use all the information in the seed.
for (uint32_t j = 0; j < 8; ++j)
a[j] += randRsl[i + j];
mix(a);
for (uint32_t j = 0; j < 8; ++j)
mm[i + j] = a[j];
}
if (flag)
{ // Do a second pass to make all of the seed affect all of mm.
for (uint32_t i = 0; i < 256; i += 8)
{
for (uint32_t j = 0; j < 8; ++j)
a[j] += mm[i + j];
mix(a);
for (uint32_t j = 0; j < 8; ++j)
mm[i + j] = a[j];
}
}
isaac(); // Fill in the first set of results.
randCnt = 0; // Prepare to use the first set of results.
}
// Seed ISAAC with a given string.
// The string can be any size. The first 256 values will be used.
void seedIsaac(string seed, bool flag)
{
uint32_t seedLength = seed.length();
for (uint32_t i = 0; i < 256; i++)
mm[i] = 0;
for (uint32_t i = 0; i < 256; i++)
// In case seed has less than 256 elements
randRsl[i] = i > seedLength ? 0 : seed[i];
// Initialize ISAAC with seed
randInit(flag);
}
// Get a random 32-bit value 0..MAXINT
uint32_t getRandom32Bit()
{
uint32_t result = randRsl[randCnt];
++randCnt;
if (randCnt > 255)
{
isaac();
randCnt = 0;
}
return result;
}
// Get a random character in printable ASCII range
char getRandomChar()
{
return getRandom32Bit() % 95 + 32;
}
// Convert an ASCII string to a hexadecimal string.
string ascii2hex(string source)
{
uint32_t sourceLength = source.length();
stringstream ss;
for (uint32_t i = 0; i < sourceLength; i++)
ss << setfill ('0') << setw(2) << hex << (int) source[i];
return ss.str();
}
// XOR encrypt on random stream.
string vernam(string msg)
{
uint32_t msgLength = msg.length();
string destination = msg;
for (uint32_t i = 0; i < msgLength; i++)
destination[i] = getRandomChar() ^ msg[i];
return destination;
}
// Caesar-shift a character <shift> places: Generalized Vigenere
char caesar(CipherMode m, char ch, char shift, char modulo, char start)
{
int n;
if (m == DECRYPT)
shift = -shift;
n = (ch - start) + shift;
n %= modulo;
if (n < 0)
n += modulo;
return start + n;
}
// Vigenere mod 95 encryption & decryption.
string vigenere(string msg, CipherMode m)
{
uint32_t msgLength = msg.length();
string destination = msg;
// Caesar-shift message
for (uint32_t i = 0; i < msgLength; ++i)
destination[i] = caesar(m, msg[i], getRandomChar(), 95, ' ');
return destination;
}
int main()
{
// TASK globals
string msg = "a Top Secret secret";
string key = "this is my secret key";
string xorCipherText, modCipherText, xorPlainText, modPlainText;
// (1) Seed ISAAC with the key
seedIsaac(key, true);
// (2) Encryption
// (a) XOR (Vernam)
xorCipherText = vernam(msg);
// (b) MOD (Vigenere)
modCipherText = vigenere(msg, ENCRYPT);
// (3) Decryption
seedIsaac(key, true);
// (a) XOR (Vernam)
xorPlainText = vernam(xorCipherText);
// (b) MOD (Vigenere)
modPlainText = vigenere(modCipherText, DECRYPT);
// Program output
cout << "Message: " << msg << endl;
cout << "Key : " << key << endl;
cout << "XOR : " << ascii2hex(xorCipherText) << endl;
cout << "MOD : " << ascii2hex(modCipherText) << endl;
cout << "XOR dcr: " << xorPlainText << endl;
cout << "MOD dcr: " << modPlainText << endl;
}
|
http://rosettacode.org/wiki/Test_integerness | Test integerness | Mathematically,
the integers Z are included in the rational numbers Q,
which are included in the real numbers R,
which can be generalized to the complex numbers C.
This means that each of those larger sets, and the data types used to represent them, include some integers.
Task[edit]
Given a rational, real, or complex number of any type, test whether it is mathematically an integer.
Your code should handle all numeric data types commonly used in your programming language.
Discuss any limitations of your code.
Definition
For the purposes of this task, integerness means that a number could theoretically be represented as an integer at no loss of precision (given an infinitely wide integer type).
In other words:
Set
Common representation
C++ type
Considered an integer...
rational numbers Q
fraction
std::ratio
...if its denominator is 1 (in reduced form)
real numbers Z
(approximated)
fixed-point
...if it has no non-zero digits after the decimal point
floating-point
float, double
...if the number of significant decimal places of its mantissa isn't greater than its exponent
complex numbers C
pair of real numbers
std::complex
...if its real part is considered an integer and its imaginary part is zero
Extra credit
Optionally, make your code accept a tolerance parameter for fuzzy testing. The tolerance is the maximum amount by which the number may differ from the nearest integer, to still be considered an integer.
This is useful in practice, because when dealing with approximate numeric types (such as floating point), there may already be round-off errors from previous calculations. For example, a float value of 0.9999999998 might actually be intended to represent the integer 1.
Test cases
Input
Output
Comment
Type
Value
exact
tolerance = 0.00001
decimal
25.000000
true
24.999999
false
true
25.000100
false
floating-point
-2.1e120
true
This one is tricky, because in most languages it is too large to fit into a native integer type.
It is, nonetheless, mathematically an integer, and your code should identify it as such.
-5e-2
false
NaN
false
Inf
false
This one is debatable. If your code considers it an integer, that's okay too.
complex
5.0+0.0i
true
5-5i
false
(The types and notations shown in these tables are merely examples – you should use the native data types and number literals of your programming language and standard library. Use a different set of test-cases, if this one doesn't demonstrate all relevant behavior.)
| #C.2B.2B | C++ |
#include <complex>
#include <math.h>
#include <iostream>
template<class Type>
struct Precision
{
public:
static Type GetEps()
{
return eps;
}
static void SetEps(Type e)
{
eps = e;
}
private:
static Type eps;
};
template<class Type> Type Precision<Type>::eps = static_cast<Type>(1E-7);
template<class DigType>
bool IsDoubleEqual(DigType d1, DigType d2)
{
return (fabs(d1 - d2) < Precision<DigType>::GetEps());
}
template<class DigType>
DigType IntegerPart(DigType value)
{
return (value > 0) ? floor(value) : ceil(value);
}
template<class DigType>
DigType FractionPart(DigType value)
{
return fabs(IntegerPart<DigType>(value) - value);
}
template<class Type>
bool IsInteger(const Type& value)
{
return false;
}
#define GEN_CHECK_INTEGER(type) \
template<> \
bool IsInteger<type>(const type& value) \
{ \
return true; \
}
#define GEN_CHECK_CMPL_INTEGER(type) \
template<> \
bool IsInteger<std::complex<type> >(const std::complex<type>& value) \
{ \
type zero = type(); \
return value.imag() == zero; \
}
#define GEN_CHECK_REAL(type) \
template<> \
bool IsInteger<type>(const type& value) \
{ \
type zero = type(); \
return IsDoubleEqual<type>(FractionPart<type>(value), zero); \
}
#define GEN_CHECK_CMPL_REAL(type) \
template<> \
bool IsInteger<std::complex<type> >(const std::complex<type>& value) \
{ \
type zero = type(); \
return IsDoubleEqual<type>(value.imag(), zero); \
}
#define GEN_INTEGER(type) \
GEN_CHECK_INTEGER(type) \
GEN_CHECK_CMPL_INTEGER(type)
#define GEN_REAL(type) \
GEN_CHECK_REAL(type) \
GEN_CHECK_CMPL_REAL(type)
GEN_INTEGER(char)
GEN_INTEGER(unsigned char)
GEN_INTEGER(short)
GEN_INTEGER(unsigned short)
GEN_INTEGER(int)
GEN_INTEGER(unsigned int)
GEN_INTEGER(long)
GEN_INTEGER(unsigned long)
GEN_INTEGER(long long)
GEN_INTEGER(unsigned long long)
GEN_REAL(float)
GEN_REAL(double)
GEN_REAL(long double)
template<class Type>
inline void TestValue(const Type& value)
{
std::cout << "Value: " << value << " of type: " << typeid(Type).name() << " is integer - " << std::boolalpha << IsInteger(value) << std::endl;
}
int main()
{
char c = -100;
unsigned char uc = 200;
short s = c;
unsigned short us = uc;
int i = s;
unsigned int ui = us;
long long ll = i;
unsigned long long ull = ui;
std::complex<unsigned int> ci1(2, 0);
std::complex<int> ci2(2, 4);
std::complex<int> ci3(-2, 4);
std::complex<unsigned short> cs1(2, 0);
std::complex<short> cs2(2, 4);
std::complex<short> cs3(-2, 4);
std::complex<double> cd1(2, 0);
std::complex<float> cf1(2, 4);
std::complex<double> cd2(-2, 4);
float f1 = 1.0;
float f2 = -2.0;
float f3 = -2.4f;
float f4 = 1.23e-5f;
float f5 = 1.23e-10f;
double d1 = f5;
TestValue(c);
TestValue(uc);
TestValue(s);
TestValue(us);
TestValue(i);
TestValue(ui);
TestValue(ll);
TestValue(ull);
TestValue(ci1);
TestValue(ci2);
TestValue(ci3);
TestValue(cs1);
TestValue(cs2);
TestValue(cs3);
TestValue(cd1);
TestValue(cd2);
TestValue(cf1);
TestValue(f1);
TestValue(f2);
TestValue(f3);
TestValue(f4);
TestValue(f5);
std::cout << "Set float precision: 1e-15f\n";
Precision<float>::SetEps(1e-15f);
TestValue(f5);
TestValue(d1);
return 0;
}
|
http://rosettacode.org/wiki/Text_processing/Max_licenses_in_use | Text processing/Max licenses in use | A company currently pays a fixed sum for the use of a particular licensed software package. In determining if it has a good deal it decides to calculate its maximum use of the software from its license management log file.
Assume the software's licensing daemon faithfully records a checkout event when a copy of the software starts and a checkin event when the software finishes to its log file.
An example of checkout and checkin events are:
License OUT @ 2008/10/03_23:51:05 for job 4974
...
License IN @ 2008/10/04_00:18:22 for job 4974
Task
Save the 10,000 line log file from here into a local file, then write a program to scan the file extracting both the maximum licenses that were out at any time, and the time(s) at which this occurs.
Mirror of log file available as a zip here (offsite mirror).
| #JavaScript | JavaScript | var file_system = new ActiveXObject("Scripting.FileSystemObject");
var fh = file_system.openTextFile('mlijobs.txt', 1); // 1 == open for reading
var in_use = 0, max_in_use = -1, max_in_use_at = [];
while ( ! fh.atEndOfStream) {
var line = fh.readline();
if (line.substr(8,3) == "OUT") {
in_use++;
if (in_use > max_in_use) {
max_in_use = in_use;
max_in_use_at = [ line.split(' ')[3] ];
}
else if (in_use == max_in_use)
max_in_use_at.push( line.split(' ')[3] );
}
else if (line.substr(8,2) == "IN")
in_use--;
}
fh.close();
WScript.echo("Max licenses out: " + max_in_use + "\n " + max_in_use_at.join('\n ')); |
http://rosettacode.org/wiki/Test_a_function | Test a function |
Task
Using a well-known testing-specific library/module/suite for your language, write some tests for your language's entry in Palindrome.
If your language does not have a testing specific library well known to the language's community then state this or omit the language.
| #Common_Lisp | Common Lisp |
(defpackage :rosetta
(:use :cl
:fiveam))
(in-package :rosetta)
(defun palindromep (string)
(string= string (reverse string)))
;; A suite of tests are declared with DEF-SUITE
(def-suite palindrome-suite :description "Tests for PALINDROMEP")
;; Tests following IN-SUITE are in the defined suite of tests
(in-suite palindrome-suite)
;; Tests are declared with TEST and take an optional documentation
;; string
(test palindromep
"Basic unit tests for PALINDROMEP."
(is-true (palindromep "a"))
(is-true (palindromep ""))
(is-true (palindromep "aba"))
(is-true (palindromep "ahha"))
(is-true (palindromep "amanaplanacanalpanama"))
(is-false (palindromep "ab"))
(is-false (palindromep "abcab")))
(test palindromep-bad-tests
"In order to demonstrate a failing test"
(is-true (palindromep "ab")))
;; Property based tests are also possible using built-in generators
(test matches-even-length-palindromes
(for-all ((s (gen-string)))
(is-true (palindromep (concatenate 'string s (reverse s))))))
;; And counter examples can be found for failing tests. This also
;; demonstrates combining generators to create cleaner input, in this
;; case restricting characters to the range of ASCII characters and
;; only permitting alphanumeric values.
(test matches-even-length-palindromes-bad
(for-all ((s (gen-string :elements (gen-character :code (gen-integer :min 0 :max 127) :alphanumericp t))))
(is-true (palindromep (concatenate 'string s s)))))
#|
Tests can be executed using RUN, RUN!, and (EXPLAIN! result-list)
RUN! = (EXPLAIN! (RUN test))
Individual tests can be run or the entire suite:
ROSETTA> (run! 'palindrome-suite)
Running test suite PALINDROME-SUITE
Running test PALINDROMEP .......
Running test PALINDROMEP-BAD-TESTS f
Running test MATCHES-EVEN-LENGTH-PALINDROMES .....................................................................................................
Running test MATCHES-EVEN-LENGTH-PALINDROMES-BAD ff
Did 10 checks.
Pass: 8 (80%)
Skip: 0 ( 0%)
Fail: 2 (20%)
Failure Details:
--------------------------------
MATCHES-EVEN-LENGTH-PALINDROMES-BAD []:
Falsifiable with ("oMYhcqnVbjYgxT6d3").
Results collected with failure data:
Did 1 check.
Pass: 0 ( 0%)
Skip: 0 ( 0%)
Fail: 1 (100%)
Failure Details:
--------------------------------
MATCHES-EVEN-LENGTH-PALINDROMES-BAD []:
(PALINDROMEP (CONCATENATE 'STRING S S)) did not return a true value.
--------------------------------
--------------------------------
--------------------------------
PALINDROMEP-BAD-TESTS [In order to demonstrate a failing test]:
(PALINDROMEP "ab") did not return a true value.
--------------------------------
NIL
(#<IT.BESE.FIVEAM::TEST-FAILURE {10083B52A3}>
#<IT.BESE.FIVEAM::FOR-ALL-TEST-FAILED {1008B34963}>)
NIL
ROSETTA> (run! 'palindromep)
Running test PALINDROMEP .......
Did 7 checks.
Pass: 7 (100%)
Skip: 0 ( 0%)
Fail: 0 ( 0%)
T
NIL
NIL
|#
|
http://rosettacode.org/wiki/Text_processing/2 | Text processing/2 | The following task concerns data that came from a pollution monitoring station with twenty-four instruments monitoring twenty-four aspects of pollution in the air. Periodically a record is added to the file, each record being a line of 49 fields separated by white-space, which can be one or more space or tab characters.
The fields (from the left) are:
DATESTAMP [ VALUEn FLAGn ] * 24
i.e. a datestamp followed by twenty-four repetitions of a floating-point instrument value and that instrument's associated integer flag. Flag values are >= 1 if the instrument is working and < 1 if there is some problem with it, in which case that instrument's value should be ignored.
A sample from the full data file readings.txt, which is also used in the Text processing/1 task, follows:
Data is no longer available at that link. Zipped mirror available here
1991-03-30 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1
1991-03-31 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 20.000 1 20.000 1 20.000 1 35.000 1 50.000 1 60.000 1 40.000 1 30.000 1 30.000 1 30.000 1 25.000 1 20.000 1 20.000 1 20.000 1 20.000 1 20.000 1 35.000 1
1991-03-31 40.000 1 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2
1991-04-01 0.000 -2 13.000 1 16.000 1 21.000 1 24.000 1 22.000 1 20.000 1 18.000 1 29.000 1 44.000 1 50.000 1 43.000 1 38.000 1 27.000 1 27.000 1 24.000 1 23.000 1 18.000 1 12.000 1 13.000 1 14.000 1 15.000 1 13.000 1 10.000 1
1991-04-02 8.000 1 9.000 1 11.000 1 12.000 1 12.000 1 12.000 1 27.000 1 26.000 1 27.000 1 33.000 1 32.000 1 31.000 1 29.000 1 31.000 1 25.000 1 25.000 1 24.000 1 21.000 1 17.000 1 14.000 1 15.000 1 12.000 1 12.000 1 10.000 1
1991-04-03 10.000 1 9.000 1 10.000 1 10.000 1 9.000 1 10.000 1 15.000 1 24.000 1 28.000 1 24.000 1 18.000 1 14.000 1 12.000 1 13.000 1 14.000 1 15.000 1 14.000 1 15.000 1 13.000 1 13.000 1 13.000 1 12.000 1 10.000 1 10.000 1
Task
Confirm the general field format of the file.
Identify any DATESTAMPs that are duplicated.
Report the number of records that have good readings for all instruments.
| #PureBasic | PureBasic | Define filename.s = "readings.txt"
#instrumentCount = 24
Enumeration
#exp_date
#exp_instruments
#exp_instrumentStatus
EndEnumeration
Structure duplicate
date.s
firstLine.i
line.i
EndStructure
NewMap dates() ;records line date occurs first
NewList duplicated.duplicate()
NewList syntaxError()
Define goodRecordCount, totalLines, line.s, i
Dim inputDate.s(0)
Dim instruments.s(0)
If ReadFile(0, filename)
CreateRegularExpression(#exp_date, "\d+-\d+-\d+")
CreateRegularExpression(#exp_instruments, "(\t|\x20)+(\d+\.\d+)(\t|\x20)+\-?\d")
CreateRegularExpression(#exp_instrumentStatus, "(\t|\x20)+(\d+\.\d+)(\t|\x20)+")
Repeat
line = ReadString(0, #PB_Ascii)
If line = "": Break: EndIf
totalLines + 1
ExtractRegularExpression(#exp_date, line, inputDate())
If FindMapElement(dates(), inputDate(0))
AddElement(duplicated())
duplicated()\date = inputDate(0)
duplicated()\firstLine = dates()
duplicated()\line = totalLines
Else
dates(inputDate(0)) = totalLines
EndIf
ExtractRegularExpression(#exp_instruments, Mid(line, Len(inputDate(0)) + 1), instruments())
Define pairsCount = ArraySize(instruments()), containsBadValues = #False
For i = 0 To pairsCount
If Val(ReplaceRegularExpression(#exp_instrumentStatus, instruments(i), "")) < 1
containsBadValues = #True
Break
EndIf
Next
If pairsCount <> #instrumentCount - 1
AddElement(syntaxError()): syntaxError() = totalLines
EndIf
If Not containsBadValues
goodRecordCount + 1
EndIf
ForEver
CloseFile(0)
If OpenConsole()
ForEach duplicated()
PrintN("Duplicate date: " + duplicated()\date + " occurs on lines " + Str(duplicated()\line) + " and " + Str(duplicated()\firstLine) + ".")
Next
ForEach syntaxError()
PrintN( "Syntax error in line " + Str(syntaxError()))
Next
PrintN(#CRLF$ + Str(goodRecordCount) + " of " + Str(totalLines) + " lines read were valid records.")
Print(#CRLF$ + #CRLF$ + "Press ENTER to exit"): Input()
CloseConsole()
EndIf
EndIf |
http://rosettacode.org/wiki/Terminal_control/Unicode_output | Terminal control/Unicode output | The task is to check that the terminal supports Unicode output, before outputting a Unicode character. If the terminal supports Unicode, then the terminal should output a Unicode delta (U+25b3). If the terminal does not support Unicode, then an appropriate error should be raised.
Note that it is permissible to use system configuration data to determine terminal capabilities if the system provides such a facility.
| #ZX_Spectrum_Basic | ZX Spectrum Basic | 10 REM There is no Unicode delta in ROM
20 REM So we first define a custom character
30 FOR l=0 TO 7
40 READ n
50 POKE USR "d"+l,n
60 NEXT l
70 REM our custom character is a user defined d
80 PRINT CHR$(147): REM this outputs our delta
9500 REM data for our custom delta
9510 DATA 0,0,8,20,34,65,127,0
|
http://rosettacode.org/wiki/Terminal_control/Ringing_the_terminal_bell | Terminal control/Ringing the terminal bell |
Task
Make the terminal running the program ring its "bell".
On modern terminal emulators, this may be done by playing some other sound which might or might not be configurable, or by flashing the title bar or inverting the colors of the screen, but was classically a physical bell within the terminal. It is usually used to indicate a problem where a wrong character has been typed.
In most terminals, if the Bell character (ASCII code 7, \a in C) is printed by the program, it will cause the terminal to ring its bell. This is a function of the terminal, and is independent of the programming language of the program, other than the ability to print a particular character to standard out.
| #E | E | print("\u0007") |
http://rosettacode.org/wiki/Terminal_control/Ringing_the_terminal_bell | Terminal control/Ringing the terminal bell |
Task
Make the terminal running the program ring its "bell".
On modern terminal emulators, this may be done by playing some other sound which might or might not be configurable, or by flashing the title bar or inverting the colors of the screen, but was classically a physical bell within the terminal. It is usually used to indicate a problem where a wrong character has been typed.
In most terminals, if the Bell character (ASCII code 7, \a in C) is printed by the program, it will cause the terminal to ring its bell. This is a function of the terminal, and is independent of the programming language of the program, other than the ability to print a particular character to standard out.
| #Emacs_Lisp | Emacs Lisp | (ding) ;; ring the bell
(beep) ;; the same thing |
http://rosettacode.org/wiki/The_Twelve_Days_of_Christmas | The Twelve Days of Christmas | Task
Write a program that outputs the lyrics of the Christmas carol The Twelve Days of Christmas.
The lyrics can be found here.
(You must reproduce the words in the correct order, but case, format, and punctuation are left to your discretion.)
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #8080_Assembly | 8080 Assembly | CR: equ 13
LF: equ 10
puts: equ 9 ; CP/M function to write a string to the console
bdos: equ 5 ; CP/M entry point
org 100h
mvi e,0 ; Start with first verse
;;; Print verse
verse: lxi h,onthe ; On the
call pstr
lxi h,ordtab
call ptabs ; Nth
lxi h,doc
call pstr ; day of Christmas, my true love gave to me
lxi h,vrstab
call ptabs ; ...whatever stuff
inr e ; next verse
mov a,e
cpi 12 ; if at 12, stop
jnz verse ; otherwise, print another verse
ret
;;; Print the E'th string from the table under HL,
;;; preserving DE registers.
ptabs: push d ; Save DE registers
mvi d,0 ; Add E*2 to HL, looking up the pointer
dad d
dad d
mov a,m ; Load low byte of pointer
inx h
mov h,m ; Load high byte of pointer
mov l,a
xchg ; Store pointer in DE
mvi c,puts ; Print string in DE using CP/M
call bdos
pop d ; Restore registers
ret
;;; Print the string under HL, preserving DE registers.
pstr: push d
xchg
mvi c,puts
call bdos
pop d
ret
ordtab: dw first,second,third,forth,fifth,sixth
dw _7th,eighth,ninth,tenth,_11th,_12th
vrstab: dw one,two,three,four,five,six,seven,eight
dw nine,ten,eleven,twelve
onthe: db 'On the $'
first: db 'first$'
second: db 'second$'
third: db 'third$'
forth: db 'forth$'
fifth: db 'fifth$'
sixth: db 'sixth$'
_7th: db 'seventh$'
eighth: db 'eighth$'
ninth: db 'ninth$'
tenth: db 'tenth$'
_11th: db 'eleventh$'
_12th: db 'twelfth$'
doc: db ' day of Christmas',CR,LF
db 'My true love gave to me:',CR,LF,'$'
twelve: db 'Twelve drummers drumming',CR,LF
eleven: db 'Eleven pipers piping',CR,LF
ten: db 'Ten lords a-leaping',CR,LF
nine: db 'Nine ladies dancing',CR,LF
eight: db 'Eight maids a-milking',CR,LF
seven: db 'Seven swans a-swimming',CR,LF
six: db 'Six geese a-laying',CR,LF
five: db 'Five golden rings',CR,LF
four: db 'Four calling birds',CR,LF
three: db 'Three french hens',CR,LF
two: db 'Two turtle doves and',CR,LF
one: db 'A partridge in a pear tree.',CR,LF
db CR,LF,'$' |
http://rosettacode.org/wiki/Terminal_control/Preserve_screen | Terminal control/Preserve screen |
Task
Clear the screen, output something on the display, and then restore the screen to the preserved state that it was in before the task was carried out.
There is no requirement to change the font or kerning in this task, however character decorations and attributes are expected to be preserved. If the implementer decides to change the font or kerning during the display of the temporary screen, then these settings need to be restored prior to exit.
| #11l | 11l | print("\033[?1049h\033[H")
print(‘Alternate buffer!’)
L(i) (5.<0).step(-1)
print(‘Going back in: ’i)
sleep(1)
print("\033[?1049l") |
http://rosettacode.org/wiki/The_ISAAC_Cipher | The ISAAC Cipher | ISAAC is a cryptographically secure pseudo-random number generator (CSPRNG) and stream cipher. It was developed by Bob Jenkins from 1993 (http://burtleburtle.net/bob/rand/isaac.html) and placed in the Public Domain. ISAAC is fast - especially when optimised - and portable to most architectures in nearly all programming and scripting languages.
It is also simple and succinct, using as it does just two 256-word arrays for its state.
ISAAC stands for "Indirection, Shift, Accumulate, Add, and Count" which are the principal bitwise operations employed.
To date - and that's after more than 20 years of existence - ISAAC has not been broken (unless GCHQ or NSA did it, but they wouldn't be telling).
ISAAC thus deserves a lot more attention than it has hitherto received and it would be salutary to see it more universally implemented.
Task
Translate ISAAC's reference C or Pascal code into your language of choice.
The RNG should then be seeded with the string "this is my secret key" and
finally the message "a Top Secret secret" should be encrypted on that key.
Your program's output cipher-text will be a string of hexadecimal digits.
Optional: Include a decryption check by re-initializing ISAAC and performing
the same encryption pass on the cipher-text.
Please use the C or Pascal as a reference guide to these operations.
Two encryption schemes are possible:
(1) XOR (Vernam) or
(2) Caesar-shift mod 95 (Vigenère).
XOR is the simplest; C-shifting offers greater security.
You may choose either scheme, or both, but please specify which you used.
Here are the alternative sample outputs for checking purposes:
Message: a Top Secret secret
Key : this is my secret key
XOR : 1C0636190B1260233B35125F1E1D0E2F4C5422
MOD : 734270227D36772A783B4F2A5F206266236978
XOR dcr: a Top Secret secret
MOD dcr: a Top Secret secret
No official seeding method for ISAAC has been published, but for this task
we may as well just inject the bytes of our key into the randrsl array,
padding with zeroes before mixing, like so:
// zeroise mm array
FOR i:= 0 TO 255 DO mm[i]:=0;
// check seed's highest array element
m := High(seed);
// inject the seed
FOR i:= 0 TO 255 DO BEGIN
// in case seed[] has less than 256 elements.
IF i>m THEN randrsl[i]:=0
ELSE randrsl[i]:=seed[i];
END;
// initialize ISAAC with seed
RandInit(true);
ISAAC can of course also be initialized with a single 32-bit unsigned integer in the manner of traditional RNGs, and indeed used as such for research and gaming purposes.
But building a strong and simple ISAAC-based stream cipher - replacing the irreparably broken RC4 - is our goal here: ISAAC's intended purpose.
| #Common_Lisp | Common Lisp | (defpackage isaac
(:use cl))
(in-package isaac)
(deftype uint32 () '(unsigned-byte 32))
(deftype arru32 () '(simple-array uint32))
(defstruct state
(randrsl (make-array 256 :element-type 'uint32) :type arru32)
(randcnt 0 :type uint32)
(mm (make-array 256 :element-type 'uint32) :type arru32)
(aa 0 :type uint32)
(bb 0 :type uint32)
(cc 0 :type uint32))
(defparameter *global-state* (make-state))
;; Some helper functions to force 32-bit arithmetic.
;; COERCE32 will be used to ensure the 32-bit results from
;; the given operations.
(declaim (inline lsh32 rsh32 add32 mod32 xor32))
(defmacro coerce32 (thing)
`(ldb (byte 32 0) ,thing))
;; ASH is split into lsh32 and rsh32 to satisfy the compiler and
;; allow inlining.
(declaim (ftype (function (uint32 (unsigned-byte 6)) uint32) lsh32))
(defun lsh32 (integer count)
(declare (optimize (speed 3) (safety 0) (space 0) (debug 0)))
(coerce32 (ash integer count)))
(declaim (ftype (function (uint32 uint32) uint32) rsh32 add32 mod32 xor32))
(defun rsh32 (integer count)
(declare (optimize (speed 3) (safety 0) (space 0) (debug 0)))
(coerce32 (ash integer (- count))))
(defun add32 (x y)
(declare (optimize (speed 3) (safety 0) (space 0) (debug 0)))
(coerce32 (+ x y)))
(defun mod32 (number divisor)
(declare (optimize (speed 3) (safety 0) (space 0) (debug 0)))
(coerce32 (mod number divisor)))
(defun xor32 (x y)
(declare (optimize (speed 3) (safety 0) (space 0) (debug 0)))
(coerce32 (logxor x y)))
(defmacro incf32 (place &optional (delta 1))
`(setf ,place (add32 ,place ,delta)))
(defun isaac (&optional (state *global-state*))
"The ISAAC function."
(declare (optimize (speed 3) (safety 0) (space 0) (debug 0))
(type state state))
(with-slots (randrsl randcnt mm aa bb cc) state
(incf32 cc)
(incf32 bb cc)
(dotimes (i 256)
(let ((x (aref mm i)))
(setf aa (add32 (aref mm (mod32 (add32 i 128) 256))
(xor32 aa
(ecase (mod32 i 4)
(0 (lsh32 aa 13))
(1 (rsh32 aa 6))
(2 (lsh32 aa 2))
(3 (rsh32 aa 16))))))
(let ((y (add32 (aref mm (mod32 (rsh32 x 2) 256))
(add32 aa
bb))))
(setf (aref mm i) y)
(setf bb (add32 (aref mm (mod32 (rsh32 y 10) 256))
x))
(setf (aref randrsl i) bb))))
(setf randcnt 0)
(values)))
(defmacro mix (&rest places)
"The magic mixer that spits out code to mix the given places."
(let ((len (length places))
(kernel '#0=(11 -2 8 -16 10 -4 8 -9 . #0#)))
(rplacd (last places) places)
`(progn
,@(loop
for i from 0
for n in kernel
until (= i len)
append
(destructuring-bind (a b c d . rest) places
(declare (ignore rest))
(pop places)
`((setf ,a (xor32 ,a ,(if (> n 0) `(lsh32 ,b ,n) `(rsh32 ,b ,(- n)))))
(incf32 ,d ,a)
(incf32 ,b ,c)))))))
(defun replace-tree (value replacement tree)
"Replace all of the values in the given expression with the replacement."
(if (atom tree)
(if (equal tree value)
replacement
tree)
(cons (replace-tree value replacement (car tree))
(if (null (cdr tree))
nil
(replace-tree value replacement (cdr tree))))))
(defmacro unroller (index-name place-name places &body body)
"A helper for unrolling a section of a loop's index with the given places."
`(progn ,@(loop
for place in places
for i from 0 below (length places) append
`(,@(if (= i 0)
(replace-tree place-name place body)
(replace-tree index-name `(add32 ,index-name ,i)
(replace-tree place-name place body)))))))
(defun randinit (flag &optional (state *global-state*))
"Initialize the given state."
(declare (optimize (speed 3) (safety 0) (space 0) (debug 0))
(type state state))
(with-slots (randrsl randcnt mm aa bb cc) state
(let* ((a #x9e3779b9) (b a) (c a) (d a) (e a) (f a) (g a) (h a))
(setf aa 0)
(setf bb 0)
(setf cc 0)
(loop repeat 4 do
(mix a b c d e f g h))
(loop for idx from 0 below 256 by 8 do
(when flag
(unroller idx place (a b c d e f g h)
(incf32 place (aref randrsl idx))))
(mix a b c d e f g h)
(unroller idx place (a b c d e f g h)
(setf (aref mm idx) place)))
(when flag
(loop for idx from 0 below 256 by 8 do
(unroller idx place (a b c d e f g h)
(incf32 place (aref mm idx)))
(mix a b c d e f g h)
(unroller idx place (a b c d e f g h)
(setf (aref mm idx) place)))))
(isaac state)
(setf randcnt 0)
(values)))
(defun i-random (&optional (state *global-state*))
"Get a random integer from the given state."
(declare (optimize (speed 3) (safety 0) (space 0) (debug 0))
(type state state))
(with-slots (randrsl randcnt) state
(prog1 (aref randrsl randcnt)
(incf32 randcnt)
(when (> randcnt 255)
(isaac state)
(setf randcnt 0)))))
(defun i-rand-a (&optional (state *global-state*))
"Get a random printable character from the given state."
(declare (optimize (speed 3) (safety 0) (space 0) (debug 0))
(type state state))
(add32 (mod32 (i-random state) 95) 32))
(defun i-seed (seed flag &optional (state *global-state*))
"Seed the given state with a string of up to 256 characters."
(declare (optimize (speed 3) (safety 0) (space 0) (debug 0))
(type state state)
(type string seed))
(with-slots (randrsl mm) state
(dotimes (i 256)
(setf (aref mm i) 0))
(let ((m (length seed)))
(dotimes (i 256)
(setf (aref randrsl i)
(if (>= i m)
0
(char-code (char seed i))))))
(randinit flag state)
(values)))
(defun vernam (msg &optional (state *global-state*))
"Vernam encode MSG with STATE."
(declare (optimize (speed 3) (safety 0) (space 0) (debug 0))
(type state state)
(type string msg))
(let* ((l (length msg))
(v (make-string l)))
(dotimes (i l)
(setf (aref v i) (code-char (logxor (i-rand-a state) (char-code (char msg i))))))
v))
;; Cipher modes: encipher, decipher, none
(defconstant +mod+ 95)
(defconstant +start+ 32)
(defun caesar (mode char shift modulo start)
"Caesar encode the given character."
(declare (optimize (speed 3) (safety 0) (space 0) (debug 0))
(type uint32 char shift modulo start))
(when (eq mode 'decipher)
(setf shift (- shift)))
(let ((n (mod (+ (- char start) shift) modulo)))
(when (< n 0)
(incf n modulo))
(+ start n)))
(defun caesar-str (mode msg modulo start &optional (state *global-state*))
"Caesar encode or decode MSG with STATE."
(declare (optimize (speed 3) (safety 0) (space 0) (debug 0))
(type string msg)
(type fixnum modulo start)
(type state state))
(let* ((l (length msg))
(c (make-string l)))
(dotimes (i l)
(setf (aref c i) (code-char (caesar mode (char-code (char msg i)) (i-rand-a state) modulo start))))
c))
(defun print-hex (string)
(loop for c across string do (format t "~2,'0x" (char-code c))))
(defun main-test ()
(let ((state (make-state))
(msg "a Top Secret secret")
(key "this is my secret key"))
(i-seed key t state)
(let ((vctx (vernam msg state))
(cctx (caesar-str 'encipher msg +mod+ +start+ state)))
(i-seed key t state)
(let ((vptx (vernam vctx state))
(cptx (caesar-str 'decipher cctx +mod+ +start+ state)))
(format t "Message: ~a~%" msg)
(format t "Key : ~a~%" key)
(format t "XOR : ")
(print-hex vctx)
(terpri)
(format t "XOR dcr: ~a~%" vptx)
(format t "MOD : ")
(print-hex cctx)
(terpri)
(format t "MOD dcr: ~a~%" cptx))))
(values)) |
http://rosettacode.org/wiki/Test_integerness | Test integerness | Mathematically,
the integers Z are included in the rational numbers Q,
which are included in the real numbers R,
which can be generalized to the complex numbers C.
This means that each of those larger sets, and the data types used to represent them, include some integers.
Task[edit]
Given a rational, real, or complex number of any type, test whether it is mathematically an integer.
Your code should handle all numeric data types commonly used in your programming language.
Discuss any limitations of your code.
Definition
For the purposes of this task, integerness means that a number could theoretically be represented as an integer at no loss of precision (given an infinitely wide integer type).
In other words:
Set
Common representation
C++ type
Considered an integer...
rational numbers Q
fraction
std::ratio
...if its denominator is 1 (in reduced form)
real numbers Z
(approximated)
fixed-point
...if it has no non-zero digits after the decimal point
floating-point
float, double
...if the number of significant decimal places of its mantissa isn't greater than its exponent
complex numbers C
pair of real numbers
std::complex
...if its real part is considered an integer and its imaginary part is zero
Extra credit
Optionally, make your code accept a tolerance parameter for fuzzy testing. The tolerance is the maximum amount by which the number may differ from the nearest integer, to still be considered an integer.
This is useful in practice, because when dealing with approximate numeric types (such as floating point), there may already be round-off errors from previous calculations. For example, a float value of 0.9999999998 might actually be intended to represent the integer 1.
Test cases
Input
Output
Comment
Type
Value
exact
tolerance = 0.00001
decimal
25.000000
true
24.999999
false
true
25.000100
false
floating-point
-2.1e120
true
This one is tricky, because in most languages it is too large to fit into a native integer type.
It is, nonetheless, mathematically an integer, and your code should identify it as such.
-5e-2
false
NaN
false
Inf
false
This one is debatable. If your code considers it an integer, that's okay too.
complex
5.0+0.0i
true
5-5i
false
(The types and notations shown in these tables are merely examples – you should use the native data types and number literals of your programming language and standard library. Use a different set of test-cases, if this one doesn't demonstrate all relevant behavior.)
| #COBOL | COBOL | IDENTIFICATION DIVISION.
PROGRAM-ID. INTEGERNESS-PROGRAM.
DATA DIVISION.
WORKING-STORAGE SECTION.
01 INTEGERS-OR-ARE-THEY.
05 POSSIBLE-INTEGER PIC S9(9)V9(9).
05 DEFINITE-INTEGER PIC S9(9).
01 COMPLEX-NUMBER.
05 REAL-PART PIC S9(9)V9(9).
05 IMAGINARY-PART PIC S9(9)V9(9).
PROCEDURE DIVISION.
TEST-PARAGRAPH.
MOVE ZERO TO IMAGINARY-PART.
DIVIDE -28 BY 7 GIVING POSSIBLE-INTEGER.
PERFORM INTEGER-PARAGRAPH.
DIVIDE 28 BY 18 GIVING POSSIBLE-INTEGER.
PERFORM INTEGER-PARAGRAPH.
DIVIDE 3 BY 10000000000 GIVING POSSIBLE-INTEGER.
PERFORM INTEGER-PARAGRAPH.
TEST-COMPLEX-PARAGRAPH.
MOVE ZERO TO REAL-PART.
MOVE 1 TO IMAGINARY-PART.
MOVE REAL-PART TO POSSIBLE-INTEGER.
PERFORM INTEGER-PARAGRAPH.
STOP RUN.
INTEGER-PARAGRAPH.
IF IMAGINARY-PART IS EQUAL TO ZERO THEN PERFORM REAL-PARAGRAPH,
ELSE PERFORM COMPLEX-PARAGRAPH.
REAL-PARAGRAPH.
MOVE POSSIBLE-INTEGER TO DEFINITE-INTEGER.
IF DEFINITE-INTEGER IS EQUAL TO POSSIBLE-INTEGER
THEN DISPLAY POSSIBLE-INTEGER ' IS AN INTEGER.',
ELSE DISPLAY POSSIBLE-INTEGER ' IS NOT AN INTEGER.'.
COMPLEX-PARAGRAPH.
DISPLAY REAL-PART '+' IMAGINARY-PART 'i IS NOT AN INTEGER.'. |
http://rosettacode.org/wiki/Text_processing/Max_licenses_in_use | Text processing/Max licenses in use | A company currently pays a fixed sum for the use of a particular licensed software package. In determining if it has a good deal it decides to calculate its maximum use of the software from its license management log file.
Assume the software's licensing daemon faithfully records a checkout event when a copy of the software starts and a checkin event when the software finishes to its log file.
An example of checkout and checkin events are:
License OUT @ 2008/10/03_23:51:05 for job 4974
...
License IN @ 2008/10/04_00:18:22 for job 4974
Task
Save the 10,000 line log file from here into a local file, then write a program to scan the file extracting both the maximum licenses that were out at any time, and the time(s) at which this occurs.
Mirror of log file available as a zip here (offsite mirror).
| #jq | jq | # Input: an array of strings
def max_licenses_in_use:
# state: [in_use = 0, max_in_use = -1, max_in_use_at = [] ]
reduce .[] as $line
([0, -1, [] ];
($line|split(" ")) as $line
| if $line[1] == "OUT" then
.[0] += 1 # in_use++;
| if .[0] > .[1] # (in_use > max_in_use)
then .[1] = .[0] # max_in_use = in_use
| .[2] = [$line[3]] # max_in_use_at = [$line[3]]
elif .[0] == .[1] # (in_use == max_in_use)
then .[2] += [$line[3]] # max_in_use_at << $line[3]
else .
end
elif $line[1] == "IN" then .[0] -= 1 # in_use--
else .
end )
| "Max licenses out: \(.[1]) at:\n \(.[2]|join("\n "))" ;
# The file is read in as a single string and so must be split at newlines:
split("\n") | max_licenses_in_use |
http://rosettacode.org/wiki/Text_processing/Max_licenses_in_use | Text processing/Max licenses in use | A company currently pays a fixed sum for the use of a particular licensed software package. In determining if it has a good deal it decides to calculate its maximum use of the software from its license management log file.
Assume the software's licensing daemon faithfully records a checkout event when a copy of the software starts and a checkin event when the software finishes to its log file.
An example of checkout and checkin events are:
License OUT @ 2008/10/03_23:51:05 for job 4974
...
License IN @ 2008/10/04_00:18:22 for job 4974
Task
Save the 10,000 line log file from here into a local file, then write a program to scan the file extracting both the maximum licenses that were out at any time, and the time(s) at which this occurs.
Mirror of log file available as a zip here (offsite mirror).
| #Julia | Julia | function maximumsimultlicenses(io::IO)
out, maxout, maxtimes = 0, -1, String[]
for job in readlines(io)
out += ifelse(occursin("OUT", job), 1, -1)
if out > maxout
maxout = out
empty!(maxtimes)
end
if out == maxout
push!(maxtimes, split(job)[4])
end
end
return maxout, maxtimes
end
let (maxout, maxtimes) = open(maximumsimultlicenses, "data/mlijobs.txt")
println("Maximum simultaneous license use is $maxout at the following times: \n - ", join(maxtimes, "\n - "))
end |
http://rosettacode.org/wiki/Test_a_function | Test a function |
Task
Using a well-known testing-specific library/module/suite for your language, write some tests for your language's entry in Palindrome.
If your language does not have a testing specific library well known to the language's community then state this or omit the language.
| #Crystal | Crystal | require "spec"
describe "palindrome" do
it "returns true for a word that's palindromic" do
palindrome("racecar").should be_true
end
it "returns false for a word that's not palindromic" do
palindrome("goodbye").should be_false
end
end
def palindrome(s)
s == s.reverse
end |
http://rosettacode.org/wiki/Test_a_function | Test a function |
Task
Using a well-known testing-specific library/module/suite for your language, write some tests for your language's entry in Palindrome.
If your language does not have a testing specific library well known to the language's community then state this or omit the language.
| #D | D | unittest {
assert(isPalindrome("racecar"));
assert(isPalindrome("bob"));
assert(!isPalindrome("alice"));
} |
http://rosettacode.org/wiki/Text_processing/2 | Text processing/2 | The following task concerns data that came from a pollution monitoring station with twenty-four instruments monitoring twenty-four aspects of pollution in the air. Periodically a record is added to the file, each record being a line of 49 fields separated by white-space, which can be one or more space or tab characters.
The fields (from the left) are:
DATESTAMP [ VALUEn FLAGn ] * 24
i.e. a datestamp followed by twenty-four repetitions of a floating-point instrument value and that instrument's associated integer flag. Flag values are >= 1 if the instrument is working and < 1 if there is some problem with it, in which case that instrument's value should be ignored.
A sample from the full data file readings.txt, which is also used in the Text processing/1 task, follows:
Data is no longer available at that link. Zipped mirror available here
1991-03-30 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1
1991-03-31 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 20.000 1 20.000 1 20.000 1 35.000 1 50.000 1 60.000 1 40.000 1 30.000 1 30.000 1 30.000 1 25.000 1 20.000 1 20.000 1 20.000 1 20.000 1 20.000 1 35.000 1
1991-03-31 40.000 1 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2
1991-04-01 0.000 -2 13.000 1 16.000 1 21.000 1 24.000 1 22.000 1 20.000 1 18.000 1 29.000 1 44.000 1 50.000 1 43.000 1 38.000 1 27.000 1 27.000 1 24.000 1 23.000 1 18.000 1 12.000 1 13.000 1 14.000 1 15.000 1 13.000 1 10.000 1
1991-04-02 8.000 1 9.000 1 11.000 1 12.000 1 12.000 1 12.000 1 27.000 1 26.000 1 27.000 1 33.000 1 32.000 1 31.000 1 29.000 1 31.000 1 25.000 1 25.000 1 24.000 1 21.000 1 17.000 1 14.000 1 15.000 1 12.000 1 12.000 1 10.000 1
1991-04-03 10.000 1 9.000 1 10.000 1 10.000 1 9.000 1 10.000 1 15.000 1 24.000 1 28.000 1 24.000 1 18.000 1 14.000 1 12.000 1 13.000 1 14.000 1 15.000 1 14.000 1 15.000 1 13.000 1 13.000 1 13.000 1 12.000 1 10.000 1 10.000 1
Task
Confirm the general field format of the file.
Identify any DATESTAMPs that are duplicated.
Report the number of records that have good readings for all instruments.
| #Python | Python | import re
import zipfile
import StringIO
def munge2(readings):
datePat = re.compile(r'\d{4}-\d{2}-\d{2}')
valuPat = re.compile(r'[-+]?\d+\.\d+')
statPat = re.compile(r'-?\d+')
allOk, totalLines = 0, 0
datestamps = set([])
for line in readings:
totalLines += 1
fields = line.split('\t')
date = fields[0]
pairs = [(fields[i],fields[i+1]) for i in range(1,len(fields),2)]
lineFormatOk = datePat.match(date) and \
all( valuPat.match(p[0]) for p in pairs ) and \
all( statPat.match(p[1]) for p in pairs )
if not lineFormatOk:
print 'Bad formatting', line
continue
if len(pairs)!=24 or any( int(p[1]) < 1 for p in pairs ):
print 'Missing values', line
continue
if date in datestamps:
print 'Duplicate datestamp', line
continue
datestamps.add(date)
allOk += 1
print 'Lines with all readings: ', allOk
print 'Total records: ', totalLines
#zfs = zipfile.ZipFile('readings.zip','r')
#readings = StringIO.StringIO(zfs.read('readings.txt'))
readings = open('readings.txt','r')
munge2(readings) |
http://rosettacode.org/wiki/Terminal_control/Ringing_the_terminal_bell | Terminal control/Ringing the terminal bell |
Task
Make the terminal running the program ring its "bell".
On modern terminal emulators, this may be done by playing some other sound which might or might not be configurable, or by flashing the title bar or inverting the colors of the screen, but was classically a physical bell within the terminal. It is usually used to indicate a problem where a wrong character has been typed.
In most terminals, if the Bell character (ASCII code 7, \a in C) is printed by the program, it will cause the terminal to ring its bell. This is a function of the terminal, and is independent of the programming language of the program, other than the ability to print a particular character to standard out.
| #F.23 | F# | open System
Console.Beep() |
http://rosettacode.org/wiki/Terminal_control/Ringing_the_terminal_bell | Terminal control/Ringing the terminal bell |
Task
Make the terminal running the program ring its "bell".
On modern terminal emulators, this may be done by playing some other sound which might or might not be configurable, or by flashing the title bar or inverting the colors of the screen, but was classically a physical bell within the terminal. It is usually used to indicate a problem where a wrong character has been typed.
In most terminals, if the Bell character (ASCII code 7, \a in C) is printed by the program, it will cause the terminal to ring its bell. This is a function of the terminal, and is independent of the programming language of the program, other than the ability to print a particular character to standard out.
| #Factor | Factor | USE: io
"\u{7}" print |
http://rosettacode.org/wiki/Terminal_control/Ringing_the_terminal_bell | Terminal control/Ringing the terminal bell |
Task
Make the terminal running the program ring its "bell".
On modern terminal emulators, this may be done by playing some other sound which might or might not be configurable, or by flashing the title bar or inverting the colors of the screen, but was classically a physical bell within the terminal. It is usually used to indicate a problem where a wrong character has been typed.
In most terminals, if the Bell character (ASCII code 7, \a in C) is printed by the program, it will cause the terminal to ring its bell. This is a function of the terminal, and is independent of the programming language of the program, other than the ability to print a particular character to standard out.
| #Forth | Forth | 7 emit |
http://rosettacode.org/wiki/Terminal_control/Ringing_the_terminal_bell | Terminal control/Ringing the terminal bell |
Task
Make the terminal running the program ring its "bell".
On modern terminal emulators, this may be done by playing some other sound which might or might not be configurable, or by flashing the title bar or inverting the colors of the screen, but was classically a physical bell within the terminal. It is usually used to indicate a problem where a wrong character has been typed.
In most terminals, if the Bell character (ASCII code 7, \a in C) is printed by the program, it will cause the terminal to ring its bell. This is a function of the terminal, and is independent of the programming language of the program, other than the ability to print a particular character to standard out.
| #FreeBASIC | FreeBASIC | ' FB 1.05.0 Win64
Print !"\a"
Sleep |
http://rosettacode.org/wiki/The_Twelve_Days_of_Christmas | The Twelve Days of Christmas | Task
Write a program that outputs the lyrics of the Christmas carol The Twelve Days of Christmas.
The lyrics can be found here.
(You must reproduce the words in the correct order, but case, format, and punctuation are left to your discretion.)
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #8086_Assembly | 8086 Assembly | CR: equ 10
LF: equ 13
puts: equ 9 ; MS-DOS syscall to print string
cpu 8086
bits 16
org 100h
section .text
xor cx,cx ; Start with first verse
verse: mov dx,onthe ; On the...
call pstr
mov si,ord.tab ; Nth
call ptabs
mov dx,doc ; day of Christmas, my true love
call pstr ; gave to me...
mov si,vrs.tab ; the gifts
call ptabs
inc cx ; Next verse
cmp cx,12 ; If not last verse,
jb verse ; then print next verse.
ret
;;; Print the CX'th string from the table in [SI].
ptabs: mov bx,cx ; BX = CX*2
shl bx,1 ; (Each entry is 2 bytes wide)
mov dx,[bx+si] ; Retrieve table entry
;;; Print the string in DX.
pstr: mov ah,puts ; Tell DOS to print the string
int 21h
ret
section .data
onthe: db 'On the $'
ord:
.n1: db 'first$'
.n2: db 'second$'
.n3: db 'third$'
.n4: db 'forth$'
.n5: db 'fifth$'
.n6: db 'sixth$'
.n7: db 'seventh$'
.n8: db 'eighth$'
.n9: db 'ninth$'
.n10: db 'tenth$'
.n11: db 'eleventh$'
.n12: db 'twelfth$'
.tab: dw .n1,.n2,.n3,.n4,.n5,.n6
dw .n7,.n8,.n9,.n10,.n11,.n12
doc: db ' day of Christmas',CR,LF
db 'My true love gave to me:',CR,LF,'$'
vrs:
.n12: db 'Twelve drummers drumming',CR,LF
.n11: db 'Eleven pipers piping',CR,LF
.n10: db 'Ten lords a-leaping',CR,LF
.n9: db 'Nine ladies dancing',CR,LF
.n8: db 'Eight maids a-milking',CR,LF
.n7: db 'Seven swans a-swimming',CR,LF
.n6: db 'Six geese a-laying',CR,LF
.n5: db 'Five golden rings',CR,LF
.n4: db 'Four calling birds',CR,LF
.n3: db 'Three french hens',CR,LF
.n2: db 'Two turtle doves and',CR,LF
.n1: db 'A partridge in a pear tree.',CR,LF
db CR,LF,'$'
.tab: dw .n1,.n2,.n3,.n4,.n5,.n6
dw .n7,.n8,.n9,.n10,.n11,.n12 |
http://rosettacode.org/wiki/Terminal_control/Preserve_screen | Terminal control/Preserve screen |
Task
Clear the screen, output something on the display, and then restore the screen to the preserved state that it was in before the task was carried out.
There is no requirement to change the font or kerning in this task, however character decorations and attributes are expected to be preserved. If the implementer decides to change the font or kerning during the display of the temporary screen, then these settings need to be restored prior to exit.
| #Action.21 | Action! | PROC Wait(BYTE frames)
BYTE RTCLOK=$14
frames==+RTCLOK
WHILE frames#RTCLOK DO OD
RETURN
PROC Main()
INT size=[960]
BYTE ARRAY buffer(size)
BYTE POINTER ptr
Graphics(0)
Position(2,10)
Print("This is the original screen content.")
Wait(200)
ptr=PeekC(88)
MoveBlock(buffer,ptr,size) ;copy screen content
Put(125) ;clear screen
Wait(50)
Position(1,10)
Print("This is an alternative screen content.")
Wait(200)
MoveBlock(ptr,buffer,size) ;restore screen content
RETURN |
http://rosettacode.org/wiki/Terminal_control/Preserve_screen | Terminal control/Preserve screen |
Task
Clear the screen, output something on the display, and then restore the screen to the preserved state that it was in before the task was carried out.
There is no requirement to change the font or kerning in this task, however character decorations and attributes are expected to be preserved. If the implementer decides to change the font or kerning during the display of the temporary screen, then these settings need to be restored prior to exit.
| #Applesoft_BASIC | Applesoft BASIC | 10 LET FF = 255:FE = FF - 1
11 LET FD = 253:FC = FD - 1
12 POKE FC, 0 : POKE FE, 0
13 LET R = 768:H = PEEK (116)
14 IF PEEK (R) = 162 GOTO 40
15 LET L = PEEK (115) > 0
16 LET H = H - 4 - L
17 HIMEM:H*256
18 LET A = 10:B = 11:C = 12
19 LET D = 13:E = 14:Z = 256
20 POKE R + 0,162: REMLDX
21 POKE R + 1,004: REM #$04
22 POKE R + 2,160: REMLDY
23 POKE R + 3,000: REM #$00
24 LET L = R + 4: REMLOOP
25 POKE L + 0,177: REMLDA
26 POKE L + 1,FC:: REM($FC),Y
27 POKE L + 2,145: REMSTA
28 POKE L + 3,FE:: REM($FE),Y
29 POKE L + 4,200: REMINY
30 POKE L + 5,208: REMBNE
31 POKE L + 6,Z - 7: REMLOOP
32 POKE L + 7,230: REMINC
33 POKE L + 8,FD:: REM $FD
34 POKE L + 9,230: REMINC
35 POKE L + A,FF:: REM $FF
36 POKE L + B,202: REMDEX
37 POKE L + C,208: REMBNE
38 POKE L + D,Z - E: REMLOOP
39 POKE L + E,096: REMRTS
40 POKE FD, 4 : POKE FF, H
41 CALL R : S = PEEK(241)
42 LET V = PEEK(37)
43 LET C = PEEK(36)
44 LET M = PEEK(50)
45 LET F = PEEK(243)
50 HOME : INVERSE
51 PRINT "ALTERNATE BUFFER"
52 FLASH : SPEED = 125
53 FOR I = 5 TO 1 STEP -1
54 PRINT "GOING BACK IN: "I
55 NEXT I
60 POKE FD, H : POKE FF, 4
61 CALL R : POKE 241, S
62 VTAB V + 1 : HTAB C + 1
63 POKE 50, M : POKE 243, F |
http://rosettacode.org/wiki/Terminal_control/Preserve_screen | Terminal control/Preserve screen |
Task
Clear the screen, output something on the display, and then restore the screen to the preserved state that it was in before the task was carried out.
There is no requirement to change the font or kerning in this task, however character decorations and attributes are expected to be preserved. If the implementer decides to change the font or kerning during the display of the temporary screen, then these settings need to be restored prior to exit.
| #BBC_BASIC | BBC BASIC | PRINT "This is the original screen"
OSCLI "GSAVE """ + @tmp$ + "bbcsave"""
WAIT 200
CLS
PRINT "This is the new screen, following a CLS"
WAIT 200
OSCLI "DISPLAY """ + @tmp$ + "bbcsave""" |
http://rosettacode.org/wiki/Terminal_control/Preserve_screen | Terminal control/Preserve screen |
Task
Clear the screen, output something on the display, and then restore the screen to the preserved state that it was in before the task was carried out.
There is no requirement to change the font or kerning in this task, however character decorations and attributes are expected to be preserved. If the implementer decides to change the font or kerning during the display of the temporary screen, then these settings need to be restored prior to exit.
| #Befunge | Befunge | "h9401?["39*>:#,_"...erotser ot >retnE< sserPH["39*>:#,_~$"l9401?["39*>:#,_@ |
http://rosettacode.org/wiki/Terminal_control/Preserve_screen | Terminal control/Preserve screen |
Task
Clear the screen, output something on the display, and then restore the screen to the preserved state that it was in before the task was carried out.
There is no requirement to change the font or kerning in this task, however character decorations and attributes are expected to be preserved. If the implementer decides to change the font or kerning during the display of the temporary screen, then these settings need to be restored prior to exit.
| #C | C | #include <stdio.h>
#include <unistd.h>
int main()
{
int i;
printf("\033[?1049h\033[H");
printf("Alternate screen buffer\n");
for (i = 5; i; i--) {
printf("\rgoing back in %d...", i);
fflush(stdout);
sleep(1);
}
printf("\033[?1049l");
return 0;
} |
http://rosettacode.org/wiki/The_ISAAC_Cipher | The ISAAC Cipher | ISAAC is a cryptographically secure pseudo-random number generator (CSPRNG) and stream cipher. It was developed by Bob Jenkins from 1993 (http://burtleburtle.net/bob/rand/isaac.html) and placed in the Public Domain. ISAAC is fast - especially when optimised - and portable to most architectures in nearly all programming and scripting languages.
It is also simple and succinct, using as it does just two 256-word arrays for its state.
ISAAC stands for "Indirection, Shift, Accumulate, Add, and Count" which are the principal bitwise operations employed.
To date - and that's after more than 20 years of existence - ISAAC has not been broken (unless GCHQ or NSA did it, but they wouldn't be telling).
ISAAC thus deserves a lot more attention than it has hitherto received and it would be salutary to see it more universally implemented.
Task
Translate ISAAC's reference C or Pascal code into your language of choice.
The RNG should then be seeded with the string "this is my secret key" and
finally the message "a Top Secret secret" should be encrypted on that key.
Your program's output cipher-text will be a string of hexadecimal digits.
Optional: Include a decryption check by re-initializing ISAAC and performing
the same encryption pass on the cipher-text.
Please use the C or Pascal as a reference guide to these operations.
Two encryption schemes are possible:
(1) XOR (Vernam) or
(2) Caesar-shift mod 95 (Vigenère).
XOR is the simplest; C-shifting offers greater security.
You may choose either scheme, or both, but please specify which you used.
Here are the alternative sample outputs for checking purposes:
Message: a Top Secret secret
Key : this is my secret key
XOR : 1C0636190B1260233B35125F1E1D0E2F4C5422
MOD : 734270227D36772A783B4F2A5F206266236978
XOR dcr: a Top Secret secret
MOD dcr: a Top Secret secret
No official seeding method for ISAAC has been published, but for this task
we may as well just inject the bytes of our key into the randrsl array,
padding with zeroes before mixing, like so:
// zeroise mm array
FOR i:= 0 TO 255 DO mm[i]:=0;
// check seed's highest array element
m := High(seed);
// inject the seed
FOR i:= 0 TO 255 DO BEGIN
// in case seed[] has less than 256 elements.
IF i>m THEN randrsl[i]:=0
ELSE randrsl[i]:=seed[i];
END;
// initialize ISAAC with seed
RandInit(true);
ISAAC can of course also be initialized with a single 32-bit unsigned integer in the manner of traditional RNGs, and indeed used as such for research and gaming purposes.
But building a strong and simple ISAAC-based stream cipher - replacing the irreparably broken RC4 - is our goal here: ISAAC's intended purpose.
| #D | D | import std.algorithm: min;
import std.algorithm: copy;
import std.typetuple: TypeTuple;
import std.typecons: staticIota;
struct ISAAC {
// External results.
private uint[mm.length] randResult;
private uint randCount;
// Internal state.
private uint[256] mm;
private uint aa, bb, cc;
private void isaac() pure nothrow @safe @nogc {
cc++; // cc just gets incremented once per mm.length results.
bb = bb + cc; // Then combined with bb.
foreach (immutable i, ref mmi; mm) {
immutable x = mm[i];
final switch (i % 4) { // Not enforced final switch.
case 0: aa ^= (aa << 13); break;
case 1: aa ^= (aa >> 6); break;
case 2: aa ^= (aa << 2); break;
case 3: aa ^= (aa >> 16); break;
}
aa = mm[(i + 128) % $] + aa;
immutable y = mm[(x >> 2) % $] + aa + bb;
bb = mm[(y >> 10) % $] + x;
randResult[i] = bb;
}
randCount = 0;
}
// If flag is true then use the contents of randResult to initialize mm.
private pure nothrow @safe @nogc static void mix(ref uint[8] a) {
alias shifts = TypeTuple!(11, 2, 8, 16, 10, 4, 8, 9);
/*static*/ foreach (immutable i, immutable sh; shifts) {
static if (i % 2 == 0)
a[i] ^= a[(i + 1) % $] << sh;
else
a[i] ^= a[(i + 1) % $] >> sh;
a[(i + 3) % $] += a[i];
a[(i + 1) % $] += a[(i + 2) % $];
}
}
private void randInit(bool flag)() pure nothrow @safe @nogc {
uint[8] a = 0x9E37_79B9; // The Golden Ratio.
aa = bb = cc = 0;
// Scramble it.
/*static*/ foreach (immutable i; staticIota!(0, 4))
mix(a);
// Fill in mm with messy stuff. Use all the information in the seed.
for (size_t i = 0; i < mm.length; i += 8) {
static if (flag)
a[] += randResult[i .. i + 8];
mix(a);
mm[i .. i + 8] = a[];
}
// Do a second pass to make all of the seed affect all of mm.
static if (flag) {
for (size_t i = 0; i < mm.length; i += 8) {
a[] += mm[i .. i + 8];
mix(a);
mm[i .. i + 8] = a[];
}
}
isaac(); // Fill in the first set of results.
randCount = 0; // Prepare to use the first set of results.
}
/// Seed ISAAC with a string.
/// Uses only the first randResult.length ubytes.
public void iSeed(bool flag)(in ubyte[] seed) pure nothrow @safe @nogc {
mm[] = 0;
randResult[] = 0;
immutable n = min(randResult.length, seed.length);
copy(seed[0 .. n], randResult[0 .. n]);
randInit!flag(); // Initialize ISAAC with seed.
}
/// Get a random uint.
private uint iRandom() pure nothrow @safe @nogc {
immutable result = randResult[randCount];
randCount++;
if (randCount > (randResult.length - 1)) {
isaac();
randCount = 0;
}
return result;
}
/// Get a random character in printable ASCII range.
private ubyte iRandA() pure nothrow @safe @nogc {
return iRandom() % 95 + 32;
}
/// XOR encrypt on random stream.
/// buffer must be as large as message or larger.
public ubyte[] vernam(in ubyte[] message, ubyte[] buffer)
pure nothrow @safe @nogc
in {
assert(buffer.length >= message.length);
} out(result) {
assert(result.length == message.length);
} body {
auto v = buffer[0 .. message.length];
// XOR message.
foreach (immutable i, immutable msgi; message)
v[i] = (iRandA() ^ msgi);
return v;
}
/// XOR encrypt on random stream.
public ubyte[] vernam(in ubyte[] message) pure nothrow @safe {
return vernam(message, new ubyte[message.length]);
}
}
void main() {
import std.stdio, std.string;
immutable message = "a Top Secret secret";
immutable key = "this is my secret key";
writeln("Message : ", message);
writeln("Key : ", key);
ISAAC cipher;
// Encrypt.
// iSeed uses only the first ISAAC.randResult.length ubytes.
cipher.iSeed!true(key.representation);
const encrypted = cipher.vernam(message.representation);
// Output ciphertext as a string of hexadecimal digits.
writefln("Encrypted: %(%02X%)", encrypted);
// Decrypt.
cipher.iSeed!true(key.representation);
const decrypted = cipher.vernam(encrypted);
writeln("Decrypted: ", decrypted.assumeUTF);
} |
http://rosettacode.org/wiki/Test_integerness | Test integerness | Mathematically,
the integers Z are included in the rational numbers Q,
which are included in the real numbers R,
which can be generalized to the complex numbers C.
This means that each of those larger sets, and the data types used to represent them, include some integers.
Task[edit]
Given a rational, real, or complex number of any type, test whether it is mathematically an integer.
Your code should handle all numeric data types commonly used in your programming language.
Discuss any limitations of your code.
Definition
For the purposes of this task, integerness means that a number could theoretically be represented as an integer at no loss of precision (given an infinitely wide integer type).
In other words:
Set
Common representation
C++ type
Considered an integer...
rational numbers Q
fraction
std::ratio
...if its denominator is 1 (in reduced form)
real numbers Z
(approximated)
fixed-point
...if it has no non-zero digits after the decimal point
floating-point
float, double
...if the number of significant decimal places of its mantissa isn't greater than its exponent
complex numbers C
pair of real numbers
std::complex
...if its real part is considered an integer and its imaginary part is zero
Extra credit
Optionally, make your code accept a tolerance parameter for fuzzy testing. The tolerance is the maximum amount by which the number may differ from the nearest integer, to still be considered an integer.
This is useful in practice, because when dealing with approximate numeric types (such as floating point), there may already be round-off errors from previous calculations. For example, a float value of 0.9999999998 might actually be intended to represent the integer 1.
Test cases
Input
Output
Comment
Type
Value
exact
tolerance = 0.00001
decimal
25.000000
true
24.999999
false
true
25.000100
false
floating-point
-2.1e120
true
This one is tricky, because in most languages it is too large to fit into a native integer type.
It is, nonetheless, mathematically an integer, and your code should identify it as such.
-5e-2
false
NaN
false
Inf
false
This one is debatable. If your code considers it an integer, that's okay too.
complex
5.0+0.0i
true
5-5i
false
(The types and notations shown in these tables are merely examples – you should use the native data types and number literals of your programming language and standard library. Use a different set of test-cases, if this one doesn't demonstrate all relevant behavior.)
| #D | D | import std.complex;
import std.math;
import std.meta;
import std.stdio;
import std.traits;
void main() {
print(25.000000);
print(24.999999);
print(24.999999, 0.00001);
print(25.000100);
print(-2.1e120);
print(-5e-2);
print(real.nan);
print(real.infinity);
print(5.0+0.0i);
print(5-5i);
}
void print(T)(T v, real tol = 0.0) {
writefln("Is %0.10s an integer? %s", v, isInteger(v, tol));
}
/// Test for plain integers
bool isInteger(T)(T v)
if (isIntegral!T) {
return true;
}
unittest {
assert(isInteger(5));
assert(isInteger(-5));
assert(isInteger(2L));
assert(isInteger(-2L));
}
/// Test for floating point
bool isInteger(T)(T v, real tol = 0.0)
if (isFloatingPoint!T) {
return (v - floor(v)) <= tol || (ceil(v) - v) <= tol;
}
unittest {
assert(isInteger(25.000000));
assert(!isInteger(24.999999));
assert(isInteger(24.999999, 0.00001));
}
/// Test for complex numbers
bool isInteger(T)(Complex!T v, real tol = 0.0) {
return isInteger(v.re, tol) && abs(v.im) <= tol;
}
unittest {
assert(isInteger(complex(1.0)));
assert(!isInteger(complex(1.0, 0.0001)));
assert(isInteger(complex(1.0, 0.00009), 0.0001));
}
/// Test for built-in complex types
bool isInteger(T)(T v, real tol = 0.0)
if (staticIndexOf!(Unqual!T, AliasSeq!(cfloat, cdouble, creal)) >= 0) {
return isInteger(v.re, tol) && abs(v.im) <= tol;
}
unittest {
assert(isInteger(1.0 + 0.0i));
assert(!isInteger(1.0 + 0.0001i));
assert(isInteger(1.0 + 0.00009i, 0.0001));
}
/// Test for built-in imaginary types
bool isInteger(T)(T v, real tol = 0.0)
if (staticIndexOf!(Unqual!T, AliasSeq!(ifloat, idouble, ireal)) >= 0) {
return abs(v) <= tol;
}
unittest {
assert(isInteger(0.0i));
assert(!isInteger(0.0001i));
assert(isInteger(0.00009i, 0.0001));
} |
http://rosettacode.org/wiki/Text_processing/Max_licenses_in_use | Text processing/Max licenses in use | A company currently pays a fixed sum for the use of a particular licensed software package. In determining if it has a good deal it decides to calculate its maximum use of the software from its license management log file.
Assume the software's licensing daemon faithfully records a checkout event when a copy of the software starts and a checkin event when the software finishes to its log file.
An example of checkout and checkin events are:
License OUT @ 2008/10/03_23:51:05 for job 4974
...
License IN @ 2008/10/04_00:18:22 for job 4974
Task
Save the 10,000 line log file from here into a local file, then write a program to scan the file extracting both the maximum licenses that were out at any time, and the time(s) at which this occurs.
Mirror of log file available as a zip here (offsite mirror).
| #K | K | r:m@&a=x:|/a:+\{:[x[8+!3]~"OUT";1;-1]}'m:0:"mlijobs.txt";
`0:,/"Maximum simultaneous license use is ",$x;
`0:" at the following times:\n";`0:r[;14+!19] |
http://rosettacode.org/wiki/Text_processing/Max_licenses_in_use | Text processing/Max licenses in use | A company currently pays a fixed sum for the use of a particular licensed software package. In determining if it has a good deal it decides to calculate its maximum use of the software from its license management log file.
Assume the software's licensing daemon faithfully records a checkout event when a copy of the software starts and a checkin event when the software finishes to its log file.
An example of checkout and checkin events are:
License OUT @ 2008/10/03_23:51:05 for job 4974
...
License IN @ 2008/10/04_00:18:22 for job 4974
Task
Save the 10,000 line log file from here into a local file, then write a program to scan the file extracting both the maximum licenses that were out at any time, and the time(s) at which this occurs.
Mirror of log file available as a zip here (offsite mirror).
| #Kotlin | Kotlin | // version 1.1.51
import java.io.File
fun main(args: Array<String>) {
val filePath = "mlijobs.txt"
var licenses = 0
var maxLicenses = 0
val dates = mutableListOf<String>()
val f = File(filePath)
f.forEachLine { line ->
if (line.startsWith("License OUT")) {
licenses++
if (licenses > maxLicenses) {
maxLicenses = licenses
dates.clear()
dates.add(line.substring(14, 33))
}
else if(licenses == maxLicenses) {
dates.add(line.substring(14, 33))
}
}
else if (line.startsWith("License IN")) {
licenses--
}
}
println("Maximum simultaneous license use is $maxLicenses at the following time(s):")
println(dates.map { " $it" }.joinToString("\n"))
} |
http://rosettacode.org/wiki/Test_a_function | Test a function |
Task
Using a well-known testing-specific library/module/suite for your language, write some tests for your language's entry in Palindrome.
If your language does not have a testing specific library well known to the language's community then state this or omit the language.
| #Delphi | Delphi | Assert(IsPalindrome('salàlas'), 'salàlas is a valid palindrome');
Assert(IsPalindrome('Ingirumimusnocteetconsumimurigni'), 'Ingirumimusnocteetconsumimurigni is a valid palindrome');
Assert(not IsPalindrome('123'), '123 is not a valid palindrome'); |
http://rosettacode.org/wiki/Test_a_function | Test a function |
Task
Using a well-known testing-specific library/module/suite for your language, write some tests for your language's entry in Palindrome.
If your language does not have a testing specific library well known to the language's community then state this or omit the language.
| #E | E | #!/usr/bin/env rune
? def isPalindrome(string :String) {
> def upper := string.toUpperCase()
> def last := upper.size() - 1
> for i => c ? (upper[last - i] != c) in upper(0, upper.size() // 2) {
> return false
> }
> return true
> }
? isPalindrome("")
# value: true
? isPalindrome("a")
# value: true
? isPalindrome("aa")
# value: true
? isPalindrome("baa")
# value: false
? isPalindrome("baab")
# value: true
? isPalindrome("ba_ab")
# value: true
? isPalindrome("ba_ ab")
# value: false
? isPalindrome("ba _ ab")
# value: true
? isPalindrome("ab"*2)
# value: false
? def x := "ab" * 2**15; null
? x.size()
# value: 65536
? def xreversed := "ba" * 2**15; null
? isPalindrome(x + xreversed)
# value: true
? (x + xreversed).size()
# value: 131072 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.