task_url
stringlengths 30
116
| task_name
stringlengths 2
86
| task_description
stringlengths 0
14.4k
| language_url
stringlengths 2
53
| language_name
stringlengths 1
52
| code
stringlengths 0
61.9k
|
---|---|---|---|---|---|
http://rosettacode.org/wiki/Taxicab_numbers | Taxicab numbers |
A taxicab number (the definition that is being used here) is a positive integer that can be expressed as the sum of two positive cubes in more than one way.
The first taxicab number is 1729, which is:
13 + 123 and also
93 + 103.
Taxicab numbers are also known as:
taxi numbers
taxi-cab numbers
taxi cab numbers
Hardy-Ramanujan numbers
Task
Compute and display the lowest 25 taxicab numbers (in numeric order, and in a human-readable format).
For each of the taxicab numbers, show the number as well as it's constituent cubes.
Extra credit
Show the 2,000th taxicab number, and a half dozen more
See also
A001235: taxicab numbers on The On-Line Encyclopedia of Integer Sequences.
Hardy-Ramanujan Number on MathWorld.
taxicab number on MathWorld.
taxicab number on Wikipedia (includes the story on how taxi-cab numbers came to be called).
| #AWK | AWK |
# syntax: GAWK -f TAXICAB_NUMBERS.AWK
BEGIN {
stop = 99
for (a=1; a<=stop; a++) {
for (b=1; b<=stop; b++) {
n1 = a^3 + b^3
for (c=1; c<=stop; c++) {
if (a == c) { continue }
for (d=1; d<=stop; d++) {
n2 = c^3 + d^3
if (n1 == n2 && (a != d || b != c)) {
if (n1 in arr) { continue }
arr[n1] = sprintf("%7d = %2d^3 + %2d^3 = %2d^3 + %2d^3",n1,a,b,c,d)
}
}
}
}
}
PROCINFO["sorted_in"] = "@ind_num_asc"
for (i in arr) {
if (++count <= 25) {
printf("%2d: %s\n",count,arr[i])
}
}
printf("\nThere are %d taxicab numbers using bounds of %d\n",length(arr),stop)
exit(0)
}
|
http://rosettacode.org/wiki/Tau_number | Tau number | A Tau number is a positive integer divisible by the count of its positive divisors.
Task
Show the first 100 Tau numbers.
The numbers shall be generated during run-time (i.e. the code may not contain string literals, sets/arrays of integers, or alike).
Related task
Tau function
| #Arturo | Arturo | tau: function [x] -> size factors x
found: 0
i:1
while [found<100][
if 0 = i % tau i [
prints pad to :string i 5
found: found + 1
if 0 = found % 10 -> print ""
]
i: i + 1
] |
http://rosettacode.org/wiki/Tau_number | Tau number | A Tau number is a positive integer divisible by the count of its positive divisors.
Task
Show the first 100 Tau numbers.
The numbers shall be generated during run-time (i.e. the code may not contain string literals, sets/arrays of integers, or alike).
Related task
Tau function
| #AWK | AWK |
# syntax: GAWK -f TAU_NUMBER.AWK
BEGIN {
print("The first 100 tau numbers:")
while (count < 100) {
i++
if (i % count_divisors(i) == 0) {
printf("%4d ",i)
if (++count % 10 == 0) {
printf("\n")
}
}
}
exit(0)
}
function count_divisors(n, count,i) {
for (i=1; i*i<=n; i++) {
if (n % i == 0) {
count += (i == n / i) ? 1 : 2
}
}
return(count)
}
|
http://rosettacode.org/wiki/Tarjan | Tarjan |
This page uses content from Wikipedia. The original article was at Graph. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Tarjan's algorithm is an algorithm in graph theory for finding the strongly connected components of a graph.
It runs in linear time, matching the time bound for alternative methods including Kosaraju's algorithm and the path-based strong component algorithm.
Tarjan's Algorithm is named for its discoverer, Robert Tarjan.
References
The article on Wikipedia.
| #11l | 11l | T Graph
String name
[Char = [Char]] graph
Int _order
[Char = Int] disc
[Char = Int] low
[Char] stack
[[Char]] scc
F (name, connections)
.name = name
DefaultDict[Char, [Char]] g
L(n) connections
V (n1, n2) = (n[0], n[1])
I n1 != n2
g[n1].append(n2)
E
g[n1]
g[n2]
.graph = Dict(move(g))
.tarjan_algo()
F _visitor(this) -> N
‘
Recursive function that finds SCC's
using DFS traversal of vertices.
Arguments:
this --> Vertex to be visited in this call.
disc{} --> Discovery order of visited vertices.
low{} --> Connected vertex of earliest discovery order
stack --> Ancestor node stack during DFS.
’
.disc[this] = .low[this] = ._order
._order++
.stack.append(this)
L(neighbr) .graph[this]
I neighbr !C .disc
._visitor(neighbr)
.low[this] = min(.low[this], .low[neighbr])
E I neighbr C .stack
.low[this] = min(.low[this], .disc[neighbr])
I .low[this] == .disc[this]
[Char] new
L
V top = .stack.pop()
new.append(top)
I top == this
L.break
.scc.append(new)
F tarjan_algo()
‘
Recursive function that finds strongly connected components
using the Tarjan Algorithm and function _visitor() to visit nodes.
’
._order = 0
L(vertex) sorted(.graph.keys())
I vertex !C .disc
._visitor(vertex)
L(n, m) [(‘Tx1’, ‘10 02 21 03 34’.split(‘ ’)),
(‘Tx2’, ‘01 12 23’.split(‘ ’)),
(‘Tx3’, ‘01 12 20 13 14 16 35 45’.split(‘ ’)),
(‘Tx4’, ‘01 03 12 14 20 26 32 45 46 56 57 58 59 64 79 89 98 AA’.split(‘ ’)),
(‘Tx5’, ‘01 12 23 24 30 42’.split(‘ ’))
]
print("\n\nGraph('#.', #.):\n".format(n, m))
V g = Graph(n, m)
print(‘ : ’sorted(g.disc.keys()).map(v -> String(v)).join(‘ ’))
print(‘ DISC of ’(g.name‘:’)‘ ’sorted(g.disc.items()).map((_, v) -> v))
print(‘ LOW of ’(g.name‘:’)‘ ’sorted(g.low.items()).map((_, v) -> v))
V scc = (I !g.scc.empty {String(g.scc).replace(‘'’, ‘’).replace(‘,’, ‘’)[1 .< (len)-1]} E ‘’)
print("\n SCC's of "(g.name‘:’)‘ ’scc) |
http://rosettacode.org/wiki/Teacup_rim_text | Teacup rim text | On a set of coasters we have, there's a picture of a teacup. On the rim of the teacup the word TEA appears a number of times separated by bullet characters (•).
It occurred to me that if the bullet were removed and the words run together, you could start at any letter and still end up with a meaningful three-letter word.
So start at the T and read TEA. Start at the E and read EAT, or start at the A and read ATE.
That got me thinking that maybe there are other words that could be used rather that TEA. And that's just English. What about Italian or Greek or ... um ... Telugu.
For English, we will use the unixdict (now) located at: unixdict.txt.
(This will maintain continuity with other Rosetta Code tasks that also use it.)
Task
Search for a set of words that could be printed around the edge of a teacup. The words in each set are to be of the same length, that length being greater than two (thus precluding AH and HA, for example.)
Having listed a set, for example [ate tea eat], refrain from displaying permutations of that set, e.g.: [eat tea ate] etc.
The words should also be made of more than one letter (thus precluding III and OOO etc.)
The relationship between these words is (using ATE as an example) that the first letter of the first becomes the last letter of the second. The first letter of the second becomes the last letter of the third. So ATE becomes TEA and TEA becomes EAT.
All of the possible permutations, using this particular permutation technique, must be words in the list.
The set you generate for ATE will never included the word ETA as that cannot be reached via the first-to-last movement method.
Display one line for each set of teacup rim words.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #F.23 | F# |
// Teacup rim text. Nigel Galloway: August 7th., 2019
let N=System.IO.File.ReadAllLines("dict.txt")|>Array.filter(fun n->String.length n=3 && Seq.length(Seq.distinct n)>1)|>Set.ofArray
let fG z=Set.map(fun n->System.String(Array.ofSeq (Seq.permute(fun g->(g+z)%3)n))) N
Set.intersectMany [N;fG 1;fG 2]|>Seq.distinctBy(Seq.sort>>Array.ofSeq>>System.String)|>Seq.iter(printfn "%s")
|
http://rosettacode.org/wiki/Temperature_conversion | Temperature conversion | There are quite a number of temperature scales. For this task we will concentrate on four of the perhaps best-known ones:
Kelvin, Celsius, Fahrenheit, and Rankine.
The Celsius and Kelvin scales have the same magnitude, but different null points.
0 degrees Celsius corresponds to 273.15 kelvin.
0 kelvin is absolute zero.
The Fahrenheit and Rankine scales also have the same magnitude, but different null points.
0 degrees Fahrenheit corresponds to 459.67 degrees Rankine.
0 degrees Rankine is absolute zero.
The Celsius/Kelvin and Fahrenheit/Rankine scales have a ratio of 5 : 9.
Task
Write code that accepts a value of kelvin, converts it to values of the three other scales, and prints the result.
Example
K 21.00
C -252.15
F -421.87
R 37.80
| #8th | 8th | : KtoC \ n -- n
273.15 n:-
;
: KtoF \ n -- n
1.8 n:* 459.67 n:-
;
: KtoR \ n -- n
1.8 n:*
;
: KtoCFR \ n --
dup dup dup
. " degrees Kelvin" . cr
KtoC
. " degrees Celcius" . cr
KtoF
. " degrees Fahrenheit" . cr
KtoR
. " degrees Rankine" . cr
;
: app:main \
argc 0 n:=
if
"Syntax" . cr " temp.8th number" . cr
else
0 args >n KtoCFR
then
bye
;
|
http://rosettacode.org/wiki/Tau_function | Tau function | Given a positive integer, count the number of its positive divisors.
Task
Show the result for the first 100 positive integers.
Related task
Tau number
| #ALGOL_W | ALGOL W | begin % find the count of the divisors of the first 100 positive integers %
% calculates the number of divisors of v %
integer procedure divisor_count( integer value v ) ; begin
integer total, n, p;
total := 1; n := v;
% Deal with powers of 2 first %
while not odd( n ) do begin
total := total + 1;
n := n div 2
end while_not_odd_n ;
% Odd prime factors up to the square root %
p := 3;
while ( p * p ) <= n do begin
integer count;
count := 1;
while n rem p = 0 do begin
count := count + 1;
n := n div p
end while_n_rem_p_eq_0 ;
p := p + 2;
total := total * count
end while_p_x_p_le_n ;
% If n > 1 then it is prime %
if n > 1 then total := total * 2;
total
end divisor_count ;
begin
integer limit;
limit := 100;
write( i_w := 1, s_w := 0, "Count of divisors for the first ", limit, " positive integers:" );
for n := 1 until limit do begin
if n rem 20 = 1 then write();
writeon( i_w := 3, s_w := 1, divisor_count( n ) )
end for_n
end
end. |
http://rosettacode.org/wiki/Terminal_control/Clear_the_screen | Terminal control/Clear the screen | Task
Clear the terminal window.
| #Axe | Axe | ClrHome |
http://rosettacode.org/wiki/Terminal_control/Clear_the_screen | Terminal control/Clear the screen | Task
Clear the terminal window.
| #BaCon | BaCon | CLEAR |
http://rosettacode.org/wiki/Terminal_control/Clear_the_screen | Terminal control/Clear the screen | Task
Clear the terminal window.
| #BASIC | BASIC | CLS |
http://rosettacode.org/wiki/Ternary_logic | Ternary logic |
This page uses content from Wikipedia. The original article was at Ternary logic. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
In logic, a three-valued logic (also trivalent, ternary, or trinary logic, sometimes abbreviated 3VL) is any of several many-valued logic systems in which there are three truth values indicating true, false and some indeterminate third value.
This is contrasted with the more commonly known bivalent logics (such as classical sentential or boolean logic) which provide only for true and false.
Conceptual form and basic ideas were initially created by Łukasiewicz, Lewis and Sulski.
These were then re-formulated by Grigore Moisil in an axiomatic algebraic form, and also extended to n-valued logics in 1945.
Example Ternary Logic Operators in Truth Tables:
not a
¬
True
False
Maybe
Maybe
False
True
a and b
∧
True
Maybe
False
True
True
Maybe
False
Maybe
Maybe
Maybe
False
False
False
False
False
a or b
∨
True
Maybe
False
True
True
True
True
Maybe
True
Maybe
Maybe
False
True
Maybe
False
if a then b
⊃
True
Maybe
False
True
True
Maybe
False
Maybe
True
Maybe
Maybe
False
True
True
True
a is equivalent to b
≡
True
Maybe
False
True
True
Maybe
False
Maybe
Maybe
Maybe
Maybe
False
False
Maybe
True
Task
Define a new type that emulates ternary logic by storing data trits.
Given all the binary logic operators of the original programming language, reimplement these operators for the new Ternary logic type trit.
Generate a sampling of results using trit variables.
Kudos for actually thinking up a test case algorithm where ternary logic is intrinsically useful, optimises the test case algorithm and is preferable to binary logic.
Note: Setun (Сетунь) was a balanced ternary computer developed in 1958 at Moscow State University. The device was built under the lead of Sergei Sobolev and Nikolay Brusentsov. It was the only modern ternary computer, using three-valued ternary logic
| #Forth | Forth | 1 constant maybe
: tnot dup maybe <> if invert then ;
: tand and ;
: tor or ;
: tequiv 2dup and rot tnot rot tnot and or ;
: timply tnot tor ;
: txor tequiv tnot ;
: t. C" TF?" 2 + + c@ emit ;
: table2. ( xt -- )
cr ." T F ?"
cr ." --------"
2 true DO
cr I t. ." | "
2 true DO
dup I J rot execute t. ." "
LOOP
LOOP DROP ;
: table1. ( xt -- )
2 true DO
CR I t. ." | "
dup I swap execute t.
LOOP DROP ;
CR ." [NOT]" ' tnot table1. CR
CR ." [AND]" ' tand table2. CR
CR ." [OR]" ' tor table2. CR
CR ." [XOR]" ' txor table2. CR
CR ." [IMPLY]" ' timply table2. CR
CR ." [EQUIV]" ' tequiv table2. CR
|
http://rosettacode.org/wiki/Text_processing/1 | Text processing/1 | This task has been flagged for clarification. Code on this page in its current state may be flagged incorrect once this task has been clarified. See this page's Talk page for discussion.
Often data is produced by one program, in the wrong format for later use by another program or person. In these situations another program can be written to parse and transform the original data into a format useful to the other. The term "Data Munging" is often used in programming circles for this task.
A request on the comp.lang.awk newsgroup led to a typical data munging task:
I have to analyse data files that have the following format:
Each row corresponds to 1 day and the field logic is: $1 is the date,
followed by 24 value/flag pairs, representing measurements at 01:00,
02:00 ... 24:00 of the respective day. In short:
<date> <val1> <flag1> <val2> <flag2> ... <val24> <flag24>
Some test data is available at:
... (nolonger available at original location)
I have to sum up the values (per day and only valid data, i.e. with
flag>0) in order to calculate the mean. That's not too difficult.
However, I also need to know what the "maximum data gap" is, i.e. the
longest period with successive invalid measurements (i.e values with
flag<=0)
The data is free to download and use and is of this format:
Data is no longer available at that link. Zipped mirror available here (offsite mirror).
1991-03-30 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1
1991-03-31 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 20.000 1 20.000 1 20.000 1 35.000 1 50.000 1 60.000 1 40.000 1 30.000 1 30.000 1 30.000 1 25.000 1 20.000 1 20.000 1 20.000 1 20.000 1 20.000 1 35.000 1
1991-03-31 40.000 1 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2
1991-04-01 0.000 -2 13.000 1 16.000 1 21.000 1 24.000 1 22.000 1 20.000 1 18.000 1 29.000 1 44.000 1 50.000 1 43.000 1 38.000 1 27.000 1 27.000 1 24.000 1 23.000 1 18.000 1 12.000 1 13.000 1 14.000 1 15.000 1 13.000 1 10.000 1
1991-04-02 8.000 1 9.000 1 11.000 1 12.000 1 12.000 1 12.000 1 27.000 1 26.000 1 27.000 1 33.000 1 32.000 1 31.000 1 29.000 1 31.000 1 25.000 1 25.000 1 24.000 1 21.000 1 17.000 1 14.000 1 15.000 1 12.000 1 12.000 1 10.000 1
1991-04-03 10.000 1 9.000 1 10.000 1 10.000 1 9.000 1 10.000 1 15.000 1 24.000 1 28.000 1 24.000 1 18.000 1 14.000 1 12.000 1 13.000 1 14.000 1 15.000 1 14.000 1 15.000 1 13.000 1 13.000 1 13.000 1 12.000 1 10.000 1 10.000 1
Only a sample of the data showing its format is given above. The full example file may be downloaded here.
Structure your program to show statistics for each line of the file, (similar to the original Python, Perl, and AWK examples below), followed by summary statistics for the file. When showing example output just show a few line statistics and the full end summary.
| #Haskell | Haskell | import Data.List
import Numeric
import Control.Arrow
import Control.Monad
import Text.Printf
import System.Environment
import Data.Function
type Date = String
type Value = Double
type Flag = Bool
readFlg :: String -> Flag
readFlg = (> 0).read
readNum :: String -> Value
readNum = fst.head.readFloat
take2 = takeWhile(not.null).unfoldr (Just.splitAt 2)
parseData :: [String] -> (Date,[(Value,Flag)])
parseData = head &&& map(readNum.head &&& readFlg.last).take2.tail
sumAccs :: (Date,[(Value,Flag)]) -> (Date, ((Value,Int),[Flag]))
sumAccs = second (((sum &&& length).concat.uncurry(zipWith(\v f -> [v|f])) &&& snd).unzip)
maxNAseq :: [Flag] -> [(Int,Int)]
maxNAseq = head.groupBy((==) `on` fst).sortBy(flip compare)
. concat.uncurry(zipWith(\i (r,b)->[(r,i)|not b]))
. first(init.scanl(+)0). unzip
. map ((fst &&& id).(length &&& head)). group
main = do
file:_ <- getArgs
f <- readFile file
let dat :: [(Date,((Value,Int),[Flag]))]
dat = map (sumAccs. parseData. words).lines $ f
summ = ((sum *** sum). unzip *** maxNAseq.concat). unzip $ map snd dat
totalFmt = "\nSummary\t\t accept: %d\t total: %.3f \taverage: %6.3f\n\n"
lineFmt = "%8s\t accept: %2d\t total: %11.3f \taverage: %6.3f\n"
maxFmt = "Maximum of %d consecutive false readings, starting on line /%s/ and ending on line /%s/\n"
-- output statistics
putStrLn "\nSome lines:\n"
mapM_ (\(d,((v,n),_)) -> printf lineFmt d n v (v/fromIntegral n)) $ take 4 $ drop 2200 dat
(\(t,n) -> printf totalFmt n t (t/fromIntegral n)) $ fst summ
mapM_ ((\(l, d1,d2) -> printf maxFmt l d1 d2)
. (\(a,b)-> (a,(fst.(dat!!).(`div`24))b,(fst.(dat!!).(`div`24))(a+b)))) $ snd summ |
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.
| #REXX | REXX | /* REXX ---------------------------------------------------------------
* 24.07.2014 Walter Pachl translated from Pascal
* extend with decryption (following Pascal)
* 25.07.2014 WP changed i+=8 to I=I+8 (courtesy GS)
* 26.07-2014 WP removed extraneous semicolons
*--------------------------------------------------------------------*/
Numeric Digits 32
aa=0
bb=0
cc=0
mm.=0
randcnt=0
randrsl.=0
msg='a Top Secret secret'
key='this is my secret key'
iMode='iEncrypt'
Call iSeed key,1 /* 1) seed ISAAC with the key */
xctx=Vernam(msg) /* 2) Vernam XOR encryption */
mode='iEncrypt'
mctx=Vigenere(msg,mode) /* 3) MOD encryption */
Call iSeed key,1
xptx=Vernam(xctx) /* a) XOR (Vernam) */
mode='iDecrypt'
mptx=Vigenere(mctx,mode) /* b) MOD (Vigenere) */
/* program output */
Say 'Message: 'msg
Say 'Key : 'key
Say 'XOR : 'c2x(xctx)
Say 'MOD : 'c2x(mctx)
Say 'XOR dcr: 'xptx
Say 'MOD dcr: 'mptx
Exit
isaac: Procedure Expose mm. aa bb cc randrsl. randcnt
cc=add(cc,1)
bb=add(bb,cc)
Do i=0 To 255
x=mm.i
im4=i//4
Select
When im4=0 Then aa=xor(aa,shl(aa,13))
When im4=1 Then aa=xor(aa,shr(aa, 6))
When im4=2 Then aa=xor(aa,shl(aa, 2))
When im4=3 Then aa=xor(aa,shr(aa,16))
End
z=(i+128)//256
aa=add(mm.z,aa)
z=shr(x,2)//256
y=add(mm.z,aa,bb)
mm.i=y
z=shr(y,10)//256
bb=add(mm.z,x)
randrsl.i=bb
End
randcnt=0
Return
mix: Procedure Expose a b c d e f g h mm. aa bb cc randrsl. randcnt
a=xor(a,shl(b,11)); d=add(d,a); b=add(b,c)
b=xor(b,shr(c, 2)); e=add(e,b); c=add(c,d)
c=xor(c,shl(d, 8)); f=add(f,c); d=add(d,e)
d=xor(d,shr(e,16)); g=add(g,d); e=add(e,f)
e=xor(e,shl(f,10)); h=add(h,e); f=add(f,g)
f=xor(f,shr(g, 4)); a=add(a,f); g=add(g,h)
g=xor(g,shl(h, 8)); b=add(b,g); h=add(h,a)
h=xor(h,shr(a, 9)); c=add(c,h); a=add(a,b)
Return
iRandInit: Procedure Expose mm. randrsl. randcnt
Parse Arg flag
aa=0; bb=0; cc=0
a= 2654435769 /* $9e3779b9; // the golden ratio */
b=a; c=a; d=a; e=a; f=a; g=a; h=a
do i=0 TO 3
Call mix
End
i=0
do until i>255 /* fill in mm[] with messy stuff */
IF flag THEN Do /* use all the information in the seed */
Call setix
a=add(a,randrsl.i); b=add(b,randrsl.i1)
c=add(c,randrsl.i2); d=add(d,randrsl.i3)
e=add(e,randrsl.i4); f=add(f,randrsl.i5)
g=add(g,randrsl.i6); h=add(h,randrsl.i7)
End
Call mix
mm.i=a; mm.i1=b; mm.i2=c; mm.i3=d
mm.i4=e; mm.i5=f; mm.i6=g; mm.i7=h
i=i+8
End
IF flag THEN Do /* do a second pass to make all of the seed affect all of mm */
i=0
do until i>255 /* fill in mm[] with messy stuff */
Call setix
a=add(a,mm.i); b=add(b,mm.i1); c=add(c,mm.i2); d=add(d,mm.i3)
e=add(e,mm.i4); f=add(f,mm.i5); g=add(g,mm.i6); h=add(h,mm.i7)
Call mix
mm.i=a; mm.i1=b; mm.i2=c; mm.i3=d
mm.i4=e; mm.i5=f; mm.i6=g; mm.i7=h
i=i+8
End
End
Call isaac /* fill in the first set of results */
randcnt=0; /* prepare to use the first set of results */
Return
iseed: Procedure Expose aa bb cc randcnt randrsl. mm.
/*---------------------------------------------------------------------
* Seed ISAAC with a given string.
* The string can be any size. The first 256 values will be used.
*--------------------------------------------------------------------*/
Parse Arg seed,flag
mm.=0
m=Length(seed)-1
Do i=0 TO 255
IF i>m THEN /* in case seed has less than 256 elements */
randrsl.i=0
ELSE
randrsl.i=c2d(substr(seed,i+1,1))
end
Call iRandInit flag /* initialize ISAAC with seed */
Return
iRandom: Procedure Expose aa bb cc randcnt randrsl. mm.
/* Get a random 32-bit value 0..MAXINT */
iRandom=randrsl.randcnt
randcnt=randcnt+1
If randcnt>255 Then Do
Call isaac
randcnt=0
End
Return irandom
iRandA: Procedure Expose aa bb cc randcnt randrsl. mm.
/* Get a random character in printable ASCII range */
iRandA=iRandom()//95+32
Return iRandA
xor: Procedure Expose aa bb cc randcnt randrsl. mm.
Parse Arg a,b
ac=d2c(a,4)
bc=d2c(b,4)
res=c2d(bitxor(ac,bc))
return res//4294967296
Vernam: Procedure Expose aa bb cc randcnt randrsl. mm.
/* XOR encrypt on random stream. Output: string of hex chars */
Parse Arg msg
Vernam=''
Do i=1 to length(msg)
Vernam=Vernam||d2c(xor(iRandA(),c2d(substr(msg,i,1))))
End
Return Vernam
letternum: Procedure Expose aa bb cc randcnt randrsl. mm.
/* Get position of the letter in chosen alphabet */
Parse Arg letter,start
letternum=c2d(letter)-c2d(start)
Return letternum
Caesar: Procedure Expose aa bb cc randcnt randrsl. mm.
/* Caesar-shift a character <shift> places: Generalized Vigenere */
Parse Arg m,ch,shift,modulo,start
IF m='iDecrypt' TheN shift=-shift
n=letternum(ch,start)+shift
n=n//modulo
IF n<0 Then n=n+modulo
Caesar=d2c(c2d(start)+n)
Return Caesar
Vigenere: Procedure Expose aa bb cc randcnt randrsl. mm.
/* Vigenere mod 95 encryption. Output: string of hex chars */
Parse Arg msg,m
Vigenere=''
Do i=1 to length(msg)
Vigenere=Vigenere||Caesar(m,substr(msg,i,1),iRandA(),95,' ')
End
Return Vigenere
shl: Procedure
res=arg(1)*(2**arg(2))
return res//4294967296
shr: Procedure
res=arg(1)%(2**arg(2))
return res//4294967296
setix:
i1=i+1
i2=i+2
i3=i+3
i4=i+4
i5=i+5
i6=i+6
i7=i+7
Return
add: Procedure
/* add argumemnts modulo 4294967296 */
res=arg(1)+arg(2)
If arg(3)<>'' Then
res=res+arg(3)
return res//4294967296 |
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.)
| #XPL0 | XPL0 | real R;
[Format(20, 20);
repeat R:= RlIn(0);
RlOut(0, R);
Text(0, if R = float(fix(R)) then " is integer"
else " is not integer");
CrLf(0);
until R = 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.)
| #zkl | zkl | T(1, 2.0,4.1,"nope",self).apply((1).isType) |
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).
| #Rust | Rust | type Timestamp = String;
fn compute_usage<R, S, E>(lines: R) -> Result<(u32, Vec<Timestamp>), E>
where
S: AsRef<str>,
R: Iterator<Item = Result<S, E>>,
{
let mut timestamps = Vec::new();
let mut current = 0;
let mut maximum = 0;
for line in lines {
let line = line?;
let line = line.as_ref();
if line.starts_with("License IN") {
current -= 1;
} else if line.starts_with("License OUT") {
current += 1;
if maximum <= current {
let date = line.split_whitespace().nth(3).unwrap().to_string();
if maximum < current {
maximum = current;
timestamps.clear();
}
timestamps.push(date);
}
}
}
Ok((maximum, timestamps))
}
fn main() -> std::io::Result<()> {
use std::io::{BufRead, BufReader};
let file = std::fs::OpenOptions::new().read(true).open("mlijobs.txt")?;
let (max, timestamps) = compute_usage(BufReader::new(file).lines())?;
println!("Maximum licenses out: {}", max);
println!("At time(s): {:?}", timestamps);
Ok(())
} |
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).
| #Scala | Scala | import java.io.{BufferedReader, InputStreamReader}
import java.net.URL
object License0 extends App {
val url = new URL("https://raw.githubusercontent.com/def-/nim-unsorted/master/mlijobs.txt")
val in = new BufferedReader(new InputStreamReader(url.openStream()))
val dates = new collection.mutable.ListBuffer[String]
var (count: Int, max: Int) = (0, Int.MinValue)
var line: String = _
while ( {line = in.readLine; line} != null) {
if (line.startsWith("License OUT ")) count += 1
if (line.startsWith("License IN ")) count -= 1 // Redundant test when "OUT"
if (count > max) { // Fruitless execution when "License IN "
max = count
val date = line.split(" ")(3)
dates.clear()
dates += date
} else if (count == max) {
val date = line.split(" ")(3)
dates += date
}
}
println("Max licenses out: " + max)
println("At time(s): " + dates.mkString(", "))
} |
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.
| #Python | Python | def is_palindrome(s):
'''
>>> is_palindrome('')
True
>>> is_palindrome('a')
True
>>> is_palindrome('aa')
True
>>> is_palindrome('baa')
False
>>> is_palindrome('baab')
True
>>> is_palindrome('ba_ab')
True
>>> is_palindrome('ba_ ab')
False
>>> is_palindrome('ba _ ab')
True
>>> is_palindrome('ab'*2)
False
>>> x = 'ab' *2**15
>>> len(x)
65536
>>> xreversed = x[::-1]
>>> is_palindrome(x+xreversed)
True
>>> len(x+xreversed)
131072
>>>
'''
return s == s[::-1]
def _test():
import doctest
doctest.testmod()
#doctest.testmod(verbose=True)
if __name__ == "__main__":
_test() |
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.
| #Quackery | Quackery | checkTrue(palindroc("aba")) # TRUE
checkTrue(!palindroc("ab")) # TRUE
checkException(palindroc()) # TRUE
checkTrue(palindroc("")) # Error. Uh-oh, there's a bug in the function |
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
| #Eiffel | Eiffel |
class
APPLICATION
create
make
feature
make
do
twelve_days_of_christmas
end
feature {NONE}
twelve_days_of_christmas
-- Christmas carol: Twelve days of christmas.
local
i, j: INTEGER
do
create gifts.make_empty
create days.make_empty
gifts := <<"A partridge in a pear tree.", "Two turtle doves and", "Three french hens", "Four calling birds", "Five golden rings", "Six geese a-laying", "Seven swans a-swimming", "Eight maids a-milking", "Nine ladies dancing", "Ten lords a-leaping", "Eleven pipers piping", "Twelve drummers drumming", "And a partridge in a pear tree.", "Two turtle doves">>
days := <<"first", "second", "third", "fourth", "fifth", "sixth", "seventh", "eighth", "ninth", "tenth", "eleventh", "Twelfth">>
from
i := 1
until
i > days.count
loop
io.put_string ("On the " + days [i] + " day of Christmas.%N")
io.put_string ("My true love gave to me:%N")
from
j := i
until
j <= 0
loop
if i = 12 and j = 2 then
io.put_string (gifts [14] + "%N")
io.put_string (gifts [13] + "%N")
j := j - 1
else
io.put_string (gifts [j] + "%N")
end
j := j - 1
end
io.new_line
i := i + 1
end
end
gifts: ARRAY [STRING]
days: ARRAY [STRING]
end
|
http://rosettacode.org/wiki/Terminal_control/Dimensions | Terminal control/Dimensions | Determine the height and width of the terminal, and store this information into variables for subsequent use.
| #zkl | zkl | h,w:=System.popen("stty size","r").readln().split();
println(w," x ",h); |
http://rosettacode.org/wiki/Terminal_control/Coloured_text | Terminal control/Coloured text | Task
Display a word in various colours on the terminal.
The system palette, or colours such as Red, Green, Blue, Magenta, Cyan, and Yellow can be used.
Optionally demonstrate:
How the system should determine if the terminal supports colour
Setting of the background colour
How to cause blinking or flashing (if supported by the terminal)
| #Fortran | Fortran | ! Standard Fortran, should work with any modern compiler (tested gfortran 9)
! and ANSI supporting terminal (tested Linux, various terminals).
program coloured_terminal_text
use, intrinsic :: iso_fortran_env, only: ERROR_UNIT
implicit none
! Some parameters for our ANSI escape codes
character(*), parameter :: esc = achar(27) ! Escape character.
character(*), parameter :: reset = esc // '[0m' ! Terminates an ANSI code.
! Foreground(font) Colours
character(*), parameter :: red = esc // '[31m'
character(*), parameter :: green = esc // '[32m'
character(*), parameter :: yellow = esc // '[33m'
character(*), parameter :: blue = esc // '[34m'
character(*), parameter :: magenta = esc // '[35m'
character(*), parameter :: cyan = esc // '[36m'
character(*), parameter :: grey = esc // '[90m' !Bright-Black
! One background colour
character(*), parameter :: background_green = esc // '[42m'
! Some other formatting
character(*), parameter :: bold = esc // '[1m'
character(*), parameter :: bold_blink = esc // '[1;5m'
! Write to terminal (stderr, use OUTPUT_UNIT for stdout)
write(ERROR_UNIT, '(a)') bold // 'Coloured words:' // reset
write(ERROR_UNIT, '(4x, a)') &
red // 'Red' // reset, &
green // 'Green' // reset, &
yellow // 'Yellow' // reset, &
blue // 'Blue' // reset, &
magenta // 'Magenta' // reset, &
cyan // 'Cyan' // reset, &
grey // 'Grey' // reset
write(ERROR_UNIT, '(a)') bold_blink // 'THE END ;-)' // reset
write(ERROR_UNIT, '(a)') background_green // 'Bonus Round' // reset
end program coloured_terminal_text |
http://rosettacode.org/wiki/Terminal_control/Cursor_movement | Terminal control/Cursor movement | Task
Demonstrate how to achieve movement of the terminal cursor:
how to move the cursor one position to the left
how to move the cursor one position to the right
how to move the cursor up one line (without affecting its horizontal position)
how to move the cursor down one line (without affecting its horizontal position)
how to move the cursor to the beginning of the line
how to move the cursor to the end of the line
how to move the cursor to the top left corner of the screen
how to move the cursor to the bottom right corner of the screen
For the purpose of this task, it is not permitted to overwrite any characters or attributes on any part of the screen (so outputting a space is not a suitable solution to achieve a movement to the right).
Handling of out of bounds locomotion
This task has no specific requirements to trap or correct cursor movement beyond the terminal boundaries, so the implementer should decide what behavior fits best in terms of the chosen language. Explanatory notes may be added to clarify how an out of bounds action would behave and the generation of error messages relating to an out of bounds cursor position is permitted.
| #Phix | Phix | --
-- demo\rosetta\Cursor_movement.exw
-- ================================
--
-- These may vary by platform/hardware... (this program is ideal for sorting such things out)
--
constant HOME = 327,
END = 335,
UP = 328,
DOWN = 336,
LEFT = 331,
RIGHT = 333,
PGUP = 329, -- (goto top left)
PGDN = 337 -- (goto bottom right)
constant {maxl,maxc} = video_config()[VC_SCRNLINES..VC_SCRNCOLS]
procedure move_cursor(integer dy, integer dx)
integer {l,c} = sq_add(get_position(),{dy,dx})
if l>=1 and l<=maxl
and c>=1 and c<=maxc then
position(l,c)
end if
end procedure
procedure move_to(integer ny=-1, integer nx=-1)
integer {l,c} = get_position()
if ny!=-1 then l = ny end if
if nx!=-1 then c = nx end if
position(l,c)
end procedure
procedure showkey(integer key)
integer {l,c} = get_position()
position(2,maxc-5)
?key
position(l,c)
end procedure
while 1 do
integer key = wait_key()
if key=#1B then exit end if -- escape quits
showkey(key)
if key=HOME then move_to(nx:=1) -- home
elsif key=END then move_to(nx:=maxc) -- end
elsif key=UP then move_cursor(-1, 0) -- up
elsif key=DOWN then move_cursor(+1, 0) -- down
elsif key=LEFT then move_cursor( 0,-1) -- left
elsif key=RIGHT then move_cursor( 0,+1) -- right
elsif key=PGUP then move_to(1,1) -- page_up
elsif key=PGDN then move_to(maxl,maxc) -- page_down
end if
end while
|
http://rosettacode.org/wiki/Terminal_control/Cursor_positioning | Terminal control/Cursor positioning |
Task
Move the cursor to column 3, row 6, and display the word "Hello" (without the quotes), so that the letter H is in column 3 on row 6.
| #XPL0 | XPL0 | include c:\cxpl\codes; \intrinsic 'code' declarations
[Cursor(2, 5); \3rd column, 6th row
Text(0, "Hello"); \upper-left corner is coordinate 0, 0
] |
http://rosettacode.org/wiki/Terminal_control/Cursor_positioning | Terminal control/Cursor positioning |
Task
Move the cursor to column 3, row 6, and display the word "Hello" (without the quotes), so that the letter H is in column 3 on row 6.
| #Wren | Wren | System.write("\e[2J") // clear the terminal
System.print("\e[6;3HHello") // move to (6, 3) and print 'Hello' |
http://rosettacode.org/wiki/Terminal_control/Cursor_positioning | Terminal control/Cursor positioning |
Task
Move the cursor to column 3, row 6, and display the word "Hello" (without the quotes), so that the letter H is in column 3 on row 6.
| #Z80_Assembly | Z80 Assembly | ld hl,&0603 ;6 = ROW, 3 = COLUMN
call &BB75 ;set text cursor according to HL
ld hl,Message
call PrintString
ret ;return to basic
Message:
byte "Hello",0
PrintString:
ld a,(hl) ;read a byte from the string
or a ;check equality to zero
ret z ;if equal to zero, we're done
call &BB5A ;print accumulator as an ascii char to screen
inc hl ;next char
jr PrintString |
http://rosettacode.org/wiki/Terminal_control/Cursor_positioning | Terminal control/Cursor positioning |
Task
Move the cursor to column 3, row 6, and display the word "Hello" (without the quotes), so that the letter H is in column 3 on row 6.
| #zkl | zkl | print("\e[6;3H" "Hello"); |
http://rosettacode.org/wiki/Take_notes_on_the_command_line | Take notes on the command line | Take notes on the command line is part of Short Circuit's Console Program Basics selection.
Invoking NOTES without commandline arguments displays the current contents of the local NOTES.TXT if it exists.
If NOTES has arguments, the current date and time are appended to the local NOTES.TXT followed by a newline.
Then all the arguments, joined with spaces, prepended with a tab, and appended with a trailing newline, are written to NOTES.TXT.
If NOTES.TXT doesn't already exist in the current directory then a new NOTES.TXT file should be created.
| #11l | 11l | :start:
I :argv.len == 1
print(File(‘notes.txt’).read(), end' ‘’)
E
V f = File(‘notes.txt’, ‘a’)
f.write(Time().format("YYYY-MM-DD hh:mm:ss\n"))
f.write("\t"(:argv[1..].join(‘ ’))"\n") |
http://rosettacode.org/wiki/Taxicab_numbers | Taxicab numbers |
A taxicab number (the definition that is being used here) is a positive integer that can be expressed as the sum of two positive cubes in more than one way.
The first taxicab number is 1729, which is:
13 + 123 and also
93 + 103.
Taxicab numbers are also known as:
taxi numbers
taxi-cab numbers
taxi cab numbers
Hardy-Ramanujan numbers
Task
Compute and display the lowest 25 taxicab numbers (in numeric order, and in a human-readable format).
For each of the taxicab numbers, show the number as well as it's constituent cubes.
Extra credit
Show the 2,000th taxicab number, and a half dozen more
See also
A001235: taxicab numbers on The On-Line Encyclopedia of Integer Sequences.
Hardy-Ramanujan Number on MathWorld.
taxicab number on MathWorld.
taxicab number on Wikipedia (includes the story on how taxi-cab numbers came to be called).
| #Befunge | Befunge | v+1$$<_v#!`**::+1g42$$_v#<!`**::+1g43\g43::<<v,,.g42,<
>004p:0>1+24p:24g\:24g>>1+:34p::**24g::**+-|p>9,,,14v,
,,,"^3 + ^3= ^3 + ^3".\,,,9"= ".:\_v#g40g43<^v,,,,.g<^
5+,$$$\1+:38*`#@_\::"~"1+:24p34p0\0>14p24g04^>,04g.,,5 |
http://rosettacode.org/wiki/Taxicab_numbers | Taxicab numbers |
A taxicab number (the definition that is being used here) is a positive integer that can be expressed as the sum of two positive cubes in more than one way.
The first taxicab number is 1729, which is:
13 + 123 and also
93 + 103.
Taxicab numbers are also known as:
taxi numbers
taxi-cab numbers
taxi cab numbers
Hardy-Ramanujan numbers
Task
Compute and display the lowest 25 taxicab numbers (in numeric order, and in a human-readable format).
For each of the taxicab numbers, show the number as well as it's constituent cubes.
Extra credit
Show the 2,000th taxicab number, and a half dozen more
See also
A001235: taxicab numbers on The On-Line Encyclopedia of Integer Sequences.
Hardy-Ramanujan Number on MathWorld.
taxicab number on MathWorld.
taxicab number on Wikipedia (includes the story on how taxi-cab numbers came to be called).
| #C | C | #include <stdio.h>
#include <stdlib.h>
typedef unsigned long long xint;
typedef unsigned uint;
typedef struct {
uint x, y; // x > y always
xint value;
} sum_t;
xint *cube;
uint n_cubes;
sum_t *pq;
uint pq_len, pq_cap;
void add_cube(void)
{
uint x = n_cubes++;
cube = realloc(cube, sizeof(xint) * (n_cubes + 1));
cube[n_cubes] = (xint) n_cubes*n_cubes*n_cubes;
if (x < 2) return; // x = 0 or 1 is useless
if (++pq_len >= pq_cap) {
if (!(pq_cap *= 2)) pq_cap = 2;
pq = realloc(pq, sizeof(*pq) * pq_cap);
}
sum_t tmp = (sum_t) { x, 1, cube[x] + 1 };
// upheap
uint i, j;
for (i = pq_len; i >= 1 && pq[j = i>>1].value > tmp.value; i = j)
pq[i] = pq[j];
pq[i] = tmp;
}
void next_sum(void)
{
redo: while (!pq_len || pq[1].value >= cube[n_cubes]) add_cube();
sum_t tmp = pq[0] = pq[1]; // pq[0] always stores last seen value
if (++tmp.y >= tmp.x) { // done with this x; throw it away
tmp = pq[pq_len--];
if (!pq_len) goto redo; // refill empty heap
} else
tmp.value += cube[tmp.y] - cube[tmp.y-1];
uint i, j;
// downheap
for (i = 1; (j = i<<1) <= pq_len; pq[i] = pq[j], i = j) {
if (j < pq_len && pq[j+1].value < pq[j].value) ++j;
if (pq[j].value >= tmp.value) break;
}
pq[i] = tmp;
}
uint next_taxi(sum_t *hist)
{
do next_sum(); while (pq[0].value != pq[1].value);
uint len = 1;
hist[0] = pq[0];
do {
hist[len++] = pq[1];
next_sum();
} while (pq[0].value == pq[1].value);
return len;
}
int main(void)
{
uint i, l;
sum_t x[10];
for (i = 1; i <= 2006; i++) {
l = next_taxi(x);
if (25 < i && i < 2000) continue;
printf("%4u:%10llu", i, x[0].value);
while (l--) printf(" = %4u^3 + %4u^3", x[l].x, x[l].y);
putchar('\n');
}
return 0;
} |
http://rosettacode.org/wiki/Tau_number | Tau number | A Tau number is a positive integer divisible by the count of its positive divisors.
Task
Show the first 100 Tau numbers.
The numbers shall be generated during run-time (i.e. the code may not contain string literals, sets/arrays of integers, or alike).
Related task
Tau function
| #BASIC | BASIC | 10 DEFINT A-Z
20 S=0: N=1
30 C=1
40 IF N<>1 THEN FOR I=1 TO N/2: C=C-(N MOD I=0): NEXT
50 IF N MOD C=0 THEN PRINT N,: S=S+1
60 N=N+1
70 IF S<100 THEN 30
80 END |
http://rosettacode.org/wiki/Tau_number | Tau number | A Tau number is a positive integer divisible by the count of its positive divisors.
Task
Show the first 100 Tau numbers.
The numbers shall be generated during run-time (i.e. the code may not contain string literals, sets/arrays of integers, or alike).
Related task
Tau function
| #BCPL | BCPL | get "libhdr"
// Count the divisors of 1..N
let divcounts(v, n) be
$( // Every positive number is divisible by 1
for i=1 to n do v!i := 1;
for i=2 to n do
$( let j = i
while j <= n do
$( // J is divisible by I
v!j := v!j + 1
j := j + i
$)
$)
$)
// Given a stored vector of divisors counts, is a number a tau number?
let tau(v, i) = i rem v!i = 0
let start() be
$( let dvec = vec 1100
let n, seen = 1, 0
divcounts(dvec, 1100) // find amount of divisors for each number
while seen < 100 do
$( if tau(dvec, n) then
$( writed(n, 5)
seen := seen + 1
if seen rem 10 = 0 then wrch('*N')
$)
n := n + 1
$)
$) |
http://rosettacode.org/wiki/Tau_number | Tau number | A Tau number is a positive integer divisible by the count of its positive divisors.
Task
Show the first 100 Tau numbers.
The numbers shall be generated during run-time (i.e. the code may not contain string literals, sets/arrays of integers, or alike).
Related task
Tau function
| #C | C | #include <stdio.h>
unsigned int divisor_count(unsigned int n) {
unsigned int total = 1;
unsigned int p;
// Deal with powers of 2 first
for (; (n & 1) == 0; n >>= 1) {
++total;
}
// Odd prime factors up to the square root
for (p = 3; p * p <= n; p += 2) {
unsigned int count = 1;
for (; n % p == 0; n /= p) {
++count;
}
total *= count;
}
// If n > 1 then it's prime
if (n > 1) {
total *= 2;
}
return total;
}
int main() {
const unsigned int limit = 100;
unsigned int count = 0;
unsigned int n;
printf("The first %d tau numbers are:\n", limit);
for (n = 1; count < limit; ++n) {
if (n % divisor_count(n) == 0) {
printf("%6d", n);
++count;
if (count % 10 == 0) {
printf("\n");
}
}
}
return 0;
} |
http://rosettacode.org/wiki/Tarjan | Tarjan |
This page uses content from Wikipedia. The original article was at Graph. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Tarjan's algorithm is an algorithm in graph theory for finding the strongly connected components of a graph.
It runs in linear time, matching the time bound for alternative methods including Kosaraju's algorithm and the path-based strong component algorithm.
Tarjan's Algorithm is named for its discoverer, Robert Tarjan.
References
The article on Wikipedia.
| #C | C | #include <stddef.h>
#include <stdlib.h>
#include <stdbool.h>
#ifndef min
#define min(x, y) ((x)<(y) ? (x) : (y))
#endif
struct edge {
void *from;
void *to;
};
struct components {
int nnodes;
void **nodes;
struct components *next;
};
struct node {
int index;
int lowlink;
bool onStack;
void *data;
};
struct tjstate {
int index;
int sp;
int nedges;
struct edge *edges;
struct node **stack;
struct components *head;
struct components *tail;
};
static int nodecmp(const void *l, const void *r)
{
return (ptrdiff_t)l -(ptrdiff_t)((struct node *)r)->data;
}
static int strongconnect(struct node *v, struct tjstate *tj)
{
struct node *w;
/* Set the depth index for v to the smallest unused index */
v->index = tj->index;
v->lowlink = tj->index;
tj->index++;
tj->stack[tj->sp] = v;
tj->sp++;
v->onStack = true;
for (int i = 0; i<tj->nedges; i++) {
/* Only consider nodes reachable from v */
if (tj->edges[i].from != v) {
continue;
}
w = tj->edges[i].to;
/* Successor w has not yet been visited; recurse on it */
if (w->index == -1) {
int r = strongconnect(w, tj);
if (r != 0)
return r;
v->lowlink = min(v->lowlink, w->lowlink);
/* Successor w is in stack S and hence in the current SCC */
} else if (w->onStack) {
v->lowlink = min(v->lowlink, w->index);
}
}
/* If v is a root node, pop the stack and generate an SCC */
if (v->lowlink == v->index) {
struct components *ng = malloc(sizeof(struct components));
if (ng == NULL) {
return 2;
}
if (tj->tail == NULL) {
tj->head = ng;
} else {
tj->tail->next = ng;
}
tj->tail = ng;
ng->next = NULL;
ng->nnodes = 0;
do {
tj->sp--;
w = tj->stack[tj->sp];
w->onStack = false;
ng->nnodes++;
} while (w != v);
ng->nodes = malloc(ng->nnodes*sizeof(void *));
if (ng == NULL) {
return 2;
}
for (int i = 0; i<ng->nnodes; i++) {
ng->nodes[i] = tj->stack[tj->sp+i]->data;
}
}
return 0;
}
static int ptrcmp(const void *l, const void *r)
{
return (ptrdiff_t)((struct node *)l)->data
- (ptrdiff_t)((struct node *)r)->data;
}
/**
* Calculate the strongly connected components using Tarjan's algorithm:
* en.wikipedia.org/wiki/Tarjan%27s_strongly_connected_components_algorithm
*
* Returns NULL when there are invalid edges and sets the error to:
* 1 if there was a malformed edge
* 2 if malloc failed
*
* @param number of nodes
* @param data of the nodes (assumed to be unique)
* @param number of edges
* @param data of edges
* @param pointer to error code
*/
struct components *tarjans(
int nnodes, void *nodedata[],
int nedges, struct edge *edgedata[],
int *error)
{
struct node nodes[nnodes];
struct edge edges[nedges];
struct node *stack[nnodes];
struct node *from, *to;
struct tjstate tj = {0, 0, nedges, edges, stack, NULL, .tail=NULL};
// Populate the nodes
for (int i = 0; i<nnodes; i++) {
nodes[i] = (struct node){-1, -1, false, nodedata[i]};
}
qsort(nodes, nnodes, sizeof(struct node), ptrcmp);
// Populate the edges
for (int i = 0; i<nedges; i++) {
from = bsearch(edgedata[i]->from, nodes, nnodes,
sizeof(struct node), nodecmp);
if (from == NULL) {
*error = 1;
return NULL;
}
to = bsearch(edgedata[i]->to, nodes, nnodes,
sizeof(struct node), nodecmp);
if (to == NULL) {
*error = 1;
return NULL;
}
edges[i] = (struct edge){.from=from, .to=to};
}
//Tarjan's
for (int i = 0; i < nnodes; i++) {
if (nodes[i].index == -1) {
*error = strongconnect(&nodes[i], &tj);
if (*error != 0)
return NULL;
}
}
return tj.head;
}
|
http://rosettacode.org/wiki/Teacup_rim_text | Teacup rim text | On a set of coasters we have, there's a picture of a teacup. On the rim of the teacup the word TEA appears a number of times separated by bullet characters (•).
It occurred to me that if the bullet were removed and the words run together, you could start at any letter and still end up with a meaningful three-letter word.
So start at the T and read TEA. Start at the E and read EAT, or start at the A and read ATE.
That got me thinking that maybe there are other words that could be used rather that TEA. And that's just English. What about Italian or Greek or ... um ... Telugu.
For English, we will use the unixdict (now) located at: unixdict.txt.
(This will maintain continuity with other Rosetta Code tasks that also use it.)
Task
Search for a set of words that could be printed around the edge of a teacup. The words in each set are to be of the same length, that length being greater than two (thus precluding AH and HA, for example.)
Having listed a set, for example [ate tea eat], refrain from displaying permutations of that set, e.g.: [eat tea ate] etc.
The words should also be made of more than one letter (thus precluding III and OOO etc.)
The relationship between these words is (using ATE as an example) that the first letter of the first becomes the last letter of the second. The first letter of the second becomes the last letter of the third. So ATE becomes TEA and TEA becomes EAT.
All of the possible permutations, using this particular permutation technique, must be words in the list.
The set you generate for ATE will never included the word ETA as that cannot be reached via the first-to-last movement method.
Display one line for each set of teacup rim words.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Factor | Factor | USING: combinators.short-circuit fry grouping hash-sets
http.client kernel math prettyprint sequences sequences.extras
sets sorting splitting ;
"https://www.mit.edu/~ecprice/wordlist.10000" http-get nip
"\n" split [ { [ length 3 < ] [ all-equal? ] } 1|| ] reject
[ [ all-rotations ] map ] [ >hash-set ] bi
'[ [ _ in? ] all? ] filter [ natural-sort ] map members . |
http://rosettacode.org/wiki/Teacup_rim_text | Teacup rim text | On a set of coasters we have, there's a picture of a teacup. On the rim of the teacup the word TEA appears a number of times separated by bullet characters (•).
It occurred to me that if the bullet were removed and the words run together, you could start at any letter and still end up with a meaningful three-letter word.
So start at the T and read TEA. Start at the E and read EAT, or start at the A and read ATE.
That got me thinking that maybe there are other words that could be used rather that TEA. And that's just English. What about Italian or Greek or ... um ... Telugu.
For English, we will use the unixdict (now) located at: unixdict.txt.
(This will maintain continuity with other Rosetta Code tasks that also use it.)
Task
Search for a set of words that could be printed around the edge of a teacup. The words in each set are to be of the same length, that length being greater than two (thus precluding AH and HA, for example.)
Having listed a set, for example [ate tea eat], refrain from displaying permutations of that set, e.g.: [eat tea ate] etc.
The words should also be made of more than one letter (thus precluding III and OOO etc.)
The relationship between these words is (using ATE as an example) that the first letter of the first becomes the last letter of the second. The first letter of the second becomes the last letter of the third. So ATE becomes TEA and TEA becomes EAT.
All of the possible permutations, using this particular permutation technique, must be words in the list.
The set you generate for ATE will never included the word ETA as that cannot be reached via the first-to-last movement method.
Display one line for each set of teacup rim words.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Go | Go | package main
import (
"bufio"
"fmt"
"log"
"os"
"sort"
"strings"
)
func check(err error) {
if err != nil {
log.Fatal(err)
}
}
func readWords(fileName string) []string {
file, err := os.Open(fileName)
check(err)
defer file.Close()
var words []string
scanner := bufio.NewScanner(file)
for scanner.Scan() {
word := strings.ToLower(strings.TrimSpace(scanner.Text()))
if len(word) >= 3 {
words = append(words, word)
}
}
check(scanner.Err())
return words
}
func rotate(runes []rune) {
first := runes[0]
copy(runes, runes[1:])
runes[len(runes)-1] = first
}
func main() {
dicts := []string{"mit_10000.txt", "unixdict.txt"} // local copies
for _, dict := range dicts {
fmt.Printf("Using %s:\n\n", dict)
words := readWords(dict)
n := len(words)
used := make(map[string]bool)
outer:
for _, word := range words {
runes := []rune(word)
variants := []string{word}
for i := 0; i < len(runes)-1; i++ {
rotate(runes)
word2 := string(runes)
if word == word2 || used[word2] {
continue outer
}
ix := sort.SearchStrings(words, word2)
if ix == n || words[ix] != word2 {
continue outer
}
variants = append(variants, word2)
}
for _, variant := range variants {
used[variant] = true
}
fmt.Println(variants)
}
fmt.Println()
}
} |
http://rosettacode.org/wiki/Temperature_conversion | Temperature conversion | There are quite a number of temperature scales. For this task we will concentrate on four of the perhaps best-known ones:
Kelvin, Celsius, Fahrenheit, and Rankine.
The Celsius and Kelvin scales have the same magnitude, but different null points.
0 degrees Celsius corresponds to 273.15 kelvin.
0 kelvin is absolute zero.
The Fahrenheit and Rankine scales also have the same magnitude, but different null points.
0 degrees Fahrenheit corresponds to 459.67 degrees Rankine.
0 degrees Rankine is absolute zero.
The Celsius/Kelvin and Fahrenheit/Rankine scales have a ratio of 5 : 9.
Task
Write code that accepts a value of kelvin, converts it to values of the three other scales, and prints the result.
Example
K 21.00
C -252.15
F -421.87
R 37.80
| #Action.21 | Action! | INCLUDE "D2:REAL.ACT" ;from the Action! Tool Kit
PROC K2C(REAL POINTER k,c)
REAL tmp
ValR("273.15",tmp)
RealSub(k,tmp,c)
RETURN
PROC K2F(REAL POINTER k,f)
REAL tmp1,tmp2,tmp3
ValR("1.8",tmp1)
ValR("459.67",tmp2)
RealMult(k,tmp1,tmp3)
RealSub(tmp3,tmp2,f)
RETURN
PROC K2R(REAL POINTER k,f)
REAL tmp
ValR("1.8",tmp)
RealMult(k,tmp,f)
RETURN
PROC Test(CHAR ARRAY text REAL POINTER k)
REAL res
PrintE(text)
Print(" Kelvin: ") PrintRE(k)
K2C(k,res)
Print(" Celsius: ") PrintRE(res)
K2F(k,res)
Print(" Fahrenheit: ") PrintRE(res)
K2R(k,res)
Print(" Rankine: ") PrintRE(res)
PutE()
RETURN
PROC Main()
REAL k
Put(125) PutE() ;clear screen
ValR("0",k) Test("Absolute zero",k)
ValR("273.15",k) Test("Ice melts",k)
ValR("373.15",k) Test("Water boils",k)
RETURN
|
http://rosettacode.org/wiki/Tau_function | Tau function | Given a positive integer, count the number of its positive divisors.
Task
Show the result for the first 100 positive integers.
Related task
Tau number
| #APL | APL | tau ← 0+.=⍳|⊢
tau¨ 5 20⍴⍳100 |
http://rosettacode.org/wiki/Tau_function | Tau function | Given a positive integer, count the number of its positive divisors.
Task
Show the result for the first 100 positive integers.
Related task
Tau number
| #AppleScript | AppleScript | on factorCount(n)
if (n < 1) then return 0
set counter to 2
set sqrt to n ^ 0.5
if (sqrt mod 1 = 0) then set counter to 1
repeat with i from (sqrt div 1) to 2 by -1
if (n mod i = 0) then set counter to counter + 2
end repeat
return counter
end factorCount
-- Task code:
local output, n, astid
set output to {"Positive divisor counts for integers 1 to 100:"}
repeat with n from 1 to 100
if (n mod 20 = 1) then set end of output to linefeed
set end of output to text -3 thru -1 of (" " & factorCount(n))
end repeat
set astid to AppleScript's text item delimiters
set AppleScript's text item delimiters to ""
set output to output as text
set AppleScript's text item delimiters to astid
return output |
http://rosettacode.org/wiki/Terminal_control/Clear_the_screen | Terminal control/Clear the screen | Task
Clear the terminal window.
| #Batch_File | Batch File | CLS |
http://rosettacode.org/wiki/Terminal_control/Clear_the_screen | Terminal control/Clear the screen | Task
Clear the terminal window.
| #beeswax | beeswax | _3F..}`[2J` |
http://rosettacode.org/wiki/Terminal_control/Clear_the_screen | Terminal control/Clear the screen | Task
Clear the terminal window.
| #Befunge | Befunge | "J2["39*,,,,@ |
http://rosettacode.org/wiki/Ternary_logic | Ternary logic |
This page uses content from Wikipedia. The original article was at Ternary logic. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
In logic, a three-valued logic (also trivalent, ternary, or trinary logic, sometimes abbreviated 3VL) is any of several many-valued logic systems in which there are three truth values indicating true, false and some indeterminate third value.
This is contrasted with the more commonly known bivalent logics (such as classical sentential or boolean logic) which provide only for true and false.
Conceptual form and basic ideas were initially created by Łukasiewicz, Lewis and Sulski.
These were then re-formulated by Grigore Moisil in an axiomatic algebraic form, and also extended to n-valued logics in 1945.
Example Ternary Logic Operators in Truth Tables:
not a
¬
True
False
Maybe
Maybe
False
True
a and b
∧
True
Maybe
False
True
True
Maybe
False
Maybe
Maybe
Maybe
False
False
False
False
False
a or b
∨
True
Maybe
False
True
True
True
True
Maybe
True
Maybe
Maybe
False
True
Maybe
False
if a then b
⊃
True
Maybe
False
True
True
Maybe
False
Maybe
True
Maybe
Maybe
False
True
True
True
a is equivalent to b
≡
True
Maybe
False
True
True
Maybe
False
Maybe
Maybe
Maybe
Maybe
False
False
Maybe
True
Task
Define a new type that emulates ternary logic by storing data trits.
Given all the binary logic operators of the original programming language, reimplement these operators for the new Ternary logic type trit.
Generate a sampling of results using trit variables.
Kudos for actually thinking up a test case algorithm where ternary logic is intrinsically useful, optimises the test case algorithm and is preferable to binary logic.
Note: Setun (Сетунь) was a balanced ternary computer developed in 1958 at Moscow State University. The device was built under the lead of Sergei Sobolev and Nikolay Brusentsov. It was the only modern ternary computer, using three-valued ternary logic
| #Fortran | Fortran |
!-*- mode: compilation; default-directory: "/tmp/" -*-
!Compilation started at Mon May 20 23:05:46
!
!a=./f && make $a && $a < unixdict.txt
!gfortran -std=f2003 -Wall -ffree-form f.f03 -o f
!
!ternary not
! 1.0 0.5 0.0
!
!
!ternary and
! 0.0 0.0 0.0
! 0.0 0.5 0.5
! 0.0 0.5 1.0
!
!
!ternary or
! 0.0 0.5 1.0
! 0.5 0.5 1.0
! 1.0 1.0 1.0
!
!
!ternary if
! 1.0 1.0 1.0
! 0.5 0.5 1.0
! 0.0 0.5 1.0
!
!
!ternary eq
! 1.0 0.5 0.0
! 0.5 0.5 0.5
! 0.0 0.5 1.0
!
!
!Compilation finished at Mon May 20 23:05:46
!This program is based on the j implementation
!not=: -.
!and=: <.
!or =: >.
!if =: (>. -.)"0~
!eq =: (<.&-. >. <.)"0
module trit
real, parameter :: true = 1, false = 0, maybe = 0.5
contains
real function tnot(y)
real, intent(in) :: y
tnot = 1 - y
end function tnot
real function tand(x, y)
real, intent(in) :: x, y
tand = min(x, y)
end function tand
real function tor(x, y)
real, intent(in) :: x, y
tor = max(x, y)
end function tor
real function tif(x, y)
real, intent(in) :: x, y
tif = tor(y, tnot(x))
end function tif
real function teq(x, y)
real, intent(in) :: x, y
teq = tor(tand(tnot(x), tnot(y)), tand(x, y))
end function teq
end module trit
program ternaryLogic
use trit
integer :: i
real, dimension(3) :: a = [false, maybe, true] ! (/ ... /)
write(6,'(/a)')'ternary not' ; write(6, '(3f4.1/)') (tnot(a(i)), i = 1 , 3)
write(6,'(/a)')'ternary and' ; call table(tand, a, a)
write(6,'(/a)')'ternary or' ; call table(tor, a, a)
write(6,'(/a)')'ternary if' ; call table(tif, a, a)
write(6,'(/a)')'ternary eq' ; call table(teq, a, a)
contains
subroutine table(u, x, y) ! for now, show the table.
real, external :: u
real, dimension(3), intent(in) :: x, y
integer :: i, j
write(6, '(3(3f4.1/))') ((u(x(i), y(j)), j=1,3), i=1,3)
end subroutine table
end program ternaryLogic
|
http://rosettacode.org/wiki/Text_processing/1 | Text processing/1 | This task has been flagged for clarification. Code on this page in its current state may be flagged incorrect once this task has been clarified. See this page's Talk page for discussion.
Often data is produced by one program, in the wrong format for later use by another program or person. In these situations another program can be written to parse and transform the original data into a format useful to the other. The term "Data Munging" is often used in programming circles for this task.
A request on the comp.lang.awk newsgroup led to a typical data munging task:
I have to analyse data files that have the following format:
Each row corresponds to 1 day and the field logic is: $1 is the date,
followed by 24 value/flag pairs, representing measurements at 01:00,
02:00 ... 24:00 of the respective day. In short:
<date> <val1> <flag1> <val2> <flag2> ... <val24> <flag24>
Some test data is available at:
... (nolonger available at original location)
I have to sum up the values (per day and only valid data, i.e. with
flag>0) in order to calculate the mean. That's not too difficult.
However, I also need to know what the "maximum data gap" is, i.e. the
longest period with successive invalid measurements (i.e values with
flag<=0)
The data is free to download and use and is of this format:
Data is no longer available at that link. Zipped mirror available here (offsite mirror).
1991-03-30 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1
1991-03-31 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 20.000 1 20.000 1 20.000 1 35.000 1 50.000 1 60.000 1 40.000 1 30.000 1 30.000 1 30.000 1 25.000 1 20.000 1 20.000 1 20.000 1 20.000 1 20.000 1 35.000 1
1991-03-31 40.000 1 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2
1991-04-01 0.000 -2 13.000 1 16.000 1 21.000 1 24.000 1 22.000 1 20.000 1 18.000 1 29.000 1 44.000 1 50.000 1 43.000 1 38.000 1 27.000 1 27.000 1 24.000 1 23.000 1 18.000 1 12.000 1 13.000 1 14.000 1 15.000 1 13.000 1 10.000 1
1991-04-02 8.000 1 9.000 1 11.000 1 12.000 1 12.000 1 12.000 1 27.000 1 26.000 1 27.000 1 33.000 1 32.000 1 31.000 1 29.000 1 31.000 1 25.000 1 25.000 1 24.000 1 21.000 1 17.000 1 14.000 1 15.000 1 12.000 1 12.000 1 10.000 1
1991-04-03 10.000 1 9.000 1 10.000 1 10.000 1 9.000 1 10.000 1 15.000 1 24.000 1 28.000 1 24.000 1 18.000 1 14.000 1 12.000 1 13.000 1 14.000 1 15.000 1 14.000 1 15.000 1 13.000 1 13.000 1 13.000 1 12.000 1 10.000 1 10.000 1
Only a sample of the data showing its format is given above. The full example file may be downloaded here.
Structure your program to show statistics for each line of the file, (similar to the original Python, Perl, and AWK examples below), followed by summary statistics for the file. When showing example output just show a few line statistics and the full end summary.
| #Icon_and_Unicon | Icon and Unicon | record badrun(count,fromdate,todate) # record to track bad runs
procedure main()
return mungetask1("readings1-input.txt","readings1-output.txt")
end
procedure mungetask1(fin,fout)
fin := open(fin) | stop("Unable to open input file ",fin)
fout := open(fout,"w") | stop("Unable to open output file ",fout)
F_tot := F_acc := F_rej := 0 # data set totals
rejmax := badrun(-1) # longest reject runs
rejcur := badrun(0) # current reject runs
while line := read(fin) do {
line ? {
ldate := tab(many(&digits ++ '-')) # date (poorly checked)
fields := tot := rej := 0 # record counters & totals
while tab(many(' \t')) do { # whitespace before every pair
value := real(tab(many(&digits++'-.'))) | stop("Bad value in ",ldate)
tab(many(' \t'))
flag := integer(tab(many(&digits++'-'))) | stop("Bad flag in ",ldate)
fields +:= 1
if flag > 0 then { # good data, ends a bad run
if rejcur.count > rejmax.count then rejmax := rejcur
rejcur := badrun(0)
tot +:= value
}
else { # bad (flagged) data
if rejcur.count = 0 then rejcur.fromdate := ldate
rejcur.todate := ldate
rejcur.count +:= 1
rej +:= 1
}
}
}
F_tot +:= tot
F_acc +:= acc := fields - rej
F_rej +:= rej
write(fout,"Line: ",ldate," Reject: ", rej," Accept: ", acc," Line_tot: ",tot," Line_avg: ", if acc > 0 then tot / acc else 0)
}
write(fout,"\nTotal = ",F_tot,"\nReadings = ",F_acc,"\nRejects = ",F_rej,"\nAverage = ",F_tot / F_acc)
if rejmax.count > 0 then
write(fout,"Maximum run of bad data was ",rejmax.count," readings from ",rejmax.fromdate," to ",rejmax.todate)
else
write(fout,"No bad runs of data")
end |
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.
| #Rust | Rust |
//! includes the XOR version of the encryption scheme
use std::num::Wrapping as w;
const MSG: &str = "a Top Secret secret";
const KEY: &str = "this is my secret key";
fn main() {
let mut isaac = Isaac::new();
isaac.seed(KEY, true);
let encr = isaac.vernam(MSG.as_bytes());
println!("msg: {}", MSG);
println!("key: {}", KEY);
print!("XOR: ");
for a in &encr {
print!("{:02X}", *a);
}
let mut isaac = Isaac::new();
isaac.seed(KEY, true);
let decr = isaac.vernam(&encr[..]);
print!("\nXOR dcr: ");
println!("{}", String::from_utf8(decr).unwrap())
}
macro_rules! mix_v(
($a:expr) => (
{
$a[0] ^= $a[1] << 11; $a[3] += $a[0]; $a[1] += $a[2];
$a[1] ^= $a[2] >> 2; $a[4] += $a[1]; $a[2] += $a[3];
$a[2] ^= $a[3] << 8; $a[5] += $a[2]; $a[3] += $a[4];
$a[3] ^= $a[4] >> 16; $a[6] += $a[3]; $a[4] += $a[5];
$a[4] ^= $a[5] << 10; $a[7] += $a[4]; $a[5] += $a[6];
$a[5] ^= $a[6] >> 4; $a[0] += $a[5]; $a[6] += $a[7];
$a[6] ^= $a[7] << 8; $a[1] += $a[6]; $a[7] += $a[0];
$a[7] ^= $a[0] >> 9; $a[2] += $a[7]; $a[0] += $a[1];
} );
);
struct Isaac {
mm: [w<u32>; 256],
aa: w<u32>,
bb: w<u32>,
cc: w<u32>,
rand_rsl: [w<u32>; 256],
rand_cnt: u32,
}
impl Isaac {
fn new() -> Isaac {
Isaac {
mm: [w(0u32); 256],
aa: w(0),
bb: w(0),
cc: w(0),
rand_rsl: [w(0u32); 256],
rand_cnt: 0,
}
}
fn isaac(&mut self) {
self.cc += w(1);
self.bb += self.cc;
for i in 0..256 {
let w(x) = self.mm[i];
match i % 4 {
0 => self.aa ^= self.aa << 13,
1 => self.aa ^= self.aa >> 6,
2 => self.aa ^= self.aa << 2,
3 => self.aa ^= self.aa >> 16,
_ => unreachable!(),
}
self.aa += self.mm[((i + 128) % 256) as usize];
let w(y) = self.mm[((x >> 2) % 256) as usize] + self.aa + self.bb;
self.bb = self.mm[((y >> 10) % 256) as usize] + w(x);
self.rand_rsl[i] = self.bb;
}
self.rand_cnt = 0;
}
fn rand_init(&mut self, flag: bool) {
let mut a_v = [w(0x9e37_79b9u32); 8];
for _ in 0..4 {
// scramble it
mix_v!(a_v);
}
for i in (0..256).step_by(8) {
// fill in mm[] with messy stuff
if flag {
// use all the information in the seed
for (j, value) in a_v.iter_mut().enumerate().take(8) {
*value += self.rand_rsl[i + j];
}
}
mix_v!(a_v);
for (j, value) in a_v.iter().enumerate().take(8) {
self.mm[i + j] = *value;
}
}
if flag {
// do a second pass to make all of the seed affect all of mm
for i in (0..256).step_by(8) {
for (j, value) in a_v.iter_mut().enumerate().take(8) {
*value += self.mm[i + j];
}
mix_v!(a_v);
for (j, value) in a_v.iter().enumerate().take(8) {
self.mm[i + j] = *value;
}
}
}
self.isaac(); // fill in the first set of results
self.rand_cnt = 0; // prepare to use the first set of results
}
/// Get a random 32-bit value
fn i_random(&mut self) -> u32 {
let r = self.rand_rsl[self.rand_cnt as usize];
self.rand_cnt += 1;
if self.rand_cnt > 255 {
self.isaac();
self.rand_cnt = 0;
}
r.0
}
/// Seed ISAAC with a string
fn seed(&mut self, seed: &str, flag: bool) {
for i in 0..256 {
self.mm[i] = w(0);
}
for i in 0..256 {
self.rand_rsl[i] = w(0);
}
for i in 0..seed.len() {
self.rand_rsl[i] = w(u32::from(seed.as_bytes()[i]));
}
// initialize ISAAC with seed
self.rand_init(flag);
}
/// Get a random character in printable ASCII range
fn i_rand_ascii(&mut self) -> u8 {
(self.i_random() % 95 + 32) as u8
}
/// XOR message
fn vernam(&mut self, msg: &[u8]) -> Vec<u8> {
msg.iter()
.map(|&b| (self.i_rand_ascii() ^ b))
.collect::<Vec<u8>>()
}
}
impl Default for Isaac {
fn default() -> Self {
Isaac::new()
}
}
|
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).
| #Seed7 | Seed7 | $ include "seed7_05.s7i";
const proc: main is func
local
var file: inFile is STD_NULL;
var string: line is "";
var integer: currLicenses is 0;
var integer: maxLicenses is 0;
var array string: maxLicenseTimes is 0 times "";
var string: eventTime is "";
begin
inFile := open("mlijobs.txt", "r");
while hasNext(inFile) do
line := getln(inFile);
if line[9 len 3] = "OUT" then
incr(currLicenses);
if currLicenses >= maxLicenses then
if currLicenses > maxLicenses then
maxLicenses := currLicenses;
maxLicenseTimes := 0 times "";
end if;
maxLicenseTimes &:= line[15 len 19];
end if;
elsif currLicenses > 0 then
decr(currLicenses);
end if;
end while;
close(inFile);
writeln("Maximum simultaneous license use is " <& maxLicenses <& " at the following times:");
for eventTime range maxLicenseTimes do
writeln(eventTime);
end for;
end func; |
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).
| #Sidef | Sidef | var out = 0
var max_out = -1
var max_times = []
ARGF.each { |line|
out += (line ~~ /OUT/ ? 1 : -1)
if (out > max_out) {
max_out = out
max_times = []
}
if (out == max_out) {
max_times << line.split(' ')[3]
}
}
say "Maximum simultaneous license use is #{max_out} at the following times:"
max_times.each {|t| say " #{t}" } |
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.
| #R | R | checkTrue(palindroc("aba")) # TRUE
checkTrue(!palindroc("ab")) # TRUE
checkException(palindroc()) # TRUE
checkTrue(palindroc("")) # Error. Uh-oh, there's a bug in the 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.
| #Racket | Racket |
#lang racket
(module+ test (require rackunit))
;; from the Palindrome entry
(define (palindromb str)
(let* ([lst (string->list (string-downcase str))]
[slst (remove* '(#\space) lst)])
(string=? (list->string (reverse slst)) (list->string slst))))
;; this test module is not loaded unless it is
;; specifically requested for testing, allowing internal
;; unit test specification
(module+ test
(check-true (palindromb "racecar"))
(check-true (palindromb "avoova"))
(check-false (palindromb "potato")))
|
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
| #Elena | Elena | import extensions;
public program()
{
var days := new string[]{
"first", "second", "third", "fourth", "fifth", "sixth", "seventh", "eighth", "ninth",
"tenth", "eleventh", "twelfth"
};
var gifts := new string[]{
"And a partridge in a pear tree",
"Two turtle doves",
"Three french hens",
"Four calling birds",
"Five golden rings",
"Six geese a-laying",
"Seven swans a-swimming",
"Eight maids a-milking",
"Nine ladies dancing",
"Ten lords a-leaping",
"Eleven pipers piping",
"Twelve drummers drumming"
};
for(int i := 0, i < 12, i += 1)
{
console.printLine("On the ", days[i], " day of Christmas, my true love gave to me");
if (i == 0)
{
console.printLine("A partridge in a pear tree")
}
else
{
for(int j := i, j >= 0, j -= 1)
{
console.printLine(gifts[j])
}
};
console.printLine()
}
} |
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
| #Elixir | Elixir | gifts = """
A partridge in a pear tree
Two turtle doves and
Three french hens
Four calling birds
Five golden rings
Six geese a-laying
Seven swans a-swimming
Eight maids a-milking
Nine ladies dancing
Ten lords a-leaping
Eleven pipers piping
Twelve drummers drumming
""" |> String.split("\n", trim: true)
days = ~w(first second third fourth fifth sixth seventh eighth ninth tenth eleventh twelfth)
Enum.with_index(days) |> Enum.each(fn {day, i} ->
IO.puts "On the #{day} day of Christmas"
IO.puts "My true love gave to me:"
Enum.take(gifts, i+1) |> Enum.reverse |> Enum.each(&IO.puts &1)
IO.puts ""
end) |
http://rosettacode.org/wiki/Terminal_control/Coloured_text | Terminal control/Coloured text | Task
Display a word in various colours on the terminal.
The system palette, or colours such as Red, Green, Blue, Magenta, Cyan, and Yellow can be used.
Optionally demonstrate:
How the system should determine if the terminal supports colour
Setting of the background colour
How to cause blinking or flashing (if supported by the terminal)
| #FreeBASIC | FreeBASIC | for i as uinteger = 0 to 15
color i, 15-i
print "Colour "+str(i),
if i mod 4 = 3 then color 0,0: print
next i |
http://rosettacode.org/wiki/Terminal_control/Coloured_text | Terminal control/Coloured text | Task
Display a word in various colours on the terminal.
The system palette, or colours such as Red, Green, Blue, Magenta, Cyan, and Yellow can be used.
Optionally demonstrate:
How the system should determine if the terminal supports colour
Setting of the background colour
How to cause blinking or flashing (if supported by the terminal)
| #FunL | FunL | import console.*
bold()
blink()
if $os.toLowerCase().startsWith( 'win' )
println( 'not supported' )
else
println( 'good to go' )
reset()
println( RED + 'Red', GREEN + 'Green', BLUE + 'Blue', MAGENTA + 'Magenta', CYAN + 'Cyan', YELLOW + 'Yellow' + RESET ) |
http://rosettacode.org/wiki/Terminal_control/Cursor_movement | Terminal control/Cursor movement | Task
Demonstrate how to achieve movement of the terminal cursor:
how to move the cursor one position to the left
how to move the cursor one position to the right
how to move the cursor up one line (without affecting its horizontal position)
how to move the cursor down one line (without affecting its horizontal position)
how to move the cursor to the beginning of the line
how to move the cursor to the end of the line
how to move the cursor to the top left corner of the screen
how to move the cursor to the bottom right corner of the screen
For the purpose of this task, it is not permitted to overwrite any characters or attributes on any part of the screen (so outputting a space is not a suitable solution to achieve a movement to the right).
Handling of out of bounds locomotion
This task has no specific requirements to trap or correct cursor movement beyond the terminal boundaries, so the implementer should decide what behavior fits best in terms of the chosen language. Explanatory notes may be added to clarify how an out of bounds action would behave and the generation of error messages relating to an out of bounds cursor position is permitted.
| #PicoLisp | PicoLisp | (call 'tput "cub1") # one position to the left
(call 'tput "cuf1") # one position to the right
(call 'tput "cuu1") # up one line
(call 'tput "cud1") # down one line
(call 'tput "cr") # beginning of the line
(call 'tput "hpa" (sys "COLUMNS")) # end of the line
(call 'tput "home") # top left corner
(call 'tput "cup" (sys "LINES") (sys "COLUMNS")) # bottom right corner |
http://rosettacode.org/wiki/Terminal_control/Cursor_movement | Terminal control/Cursor movement | Task
Demonstrate how to achieve movement of the terminal cursor:
how to move the cursor one position to the left
how to move the cursor one position to the right
how to move the cursor up one line (without affecting its horizontal position)
how to move the cursor down one line (without affecting its horizontal position)
how to move the cursor to the beginning of the line
how to move the cursor to the end of the line
how to move the cursor to the top left corner of the screen
how to move the cursor to the bottom right corner of the screen
For the purpose of this task, it is not permitted to overwrite any characters or attributes on any part of the screen (so outputting a space is not a suitable solution to achieve a movement to the right).
Handling of out of bounds locomotion
This task has no specific requirements to trap or correct cursor movement beyond the terminal boundaries, so the implementer should decide what behavior fits best in terms of the chosen language. Explanatory notes may be added to clarify how an out of bounds action would behave and the generation of error messages relating to an out of bounds cursor position is permitted.
| #Python | Python | import curses
scr = curses.initscr()
# Demonstrate how to move the cursor one position to the left
def move_left():
y,x = curses.getyx()
curses.move(y,x-1)
# Demonstrate how to move the cursor one position to the right
def move_right():
y,x = curses.getyx()
curses.move(y,x+1)
# Demonstrate how to move the cursor up one line (without affecting its horizontal position)
def move_up():
y,x = curses.getyx()
curses.move(y-1,x)
# Demonstrate how to move the cursor down one line (without affecting its horizontal position)
def move_down():
y,x = curses.getyx()
curses.move(y+1,x)
# Demonstrate how to move the cursor to the beginning of the line
def move_line_home()
y,x = curses.getyx()
curses.move(y,0)
# Demonstrate how to move the cursor to the end of the line
def move_line_end()
y,x = curses.getyx()
maxy,maxx = scr.getmaxyx()
curses.move(y,maxx)
# Demonstrate how to move the cursor to the top left corner of the screen
def move_page_home():
curses.move(0,0)
# Demonstrate how to move the cursor to the bottom right corner of the screen
def move_page_end():
y,x = scr.getmaxyx()
curses.move(y,x)
|
http://rosettacode.org/wiki/Take_notes_on_the_command_line | Take notes on the command line | Take notes on the command line is part of Short Circuit's Console Program Basics selection.
Invoking NOTES without commandline arguments displays the current contents of the local NOTES.TXT if it exists.
If NOTES has arguments, the current date and time are appended to the local NOTES.TXT followed by a newline.
Then all the arguments, joined with spaces, prepended with a tab, and appended with a trailing newline, are written to NOTES.TXT.
If NOTES.TXT doesn't already exist in the current directory then a new NOTES.TXT file should be created.
| #8086_Assembly | 8086 Assembly | bits 16
cpu 8086
;;; MS-DOS PSP locations
cmdlen: equ 80h ; Amount of characters on cmdline
cmdtail: equ 82h ; Command line tail
;;; MS-DOS system calls
puts: equ 9h ; Print string to console
date: equ 2Ah ; Get system date
time: equ 2Ch ; Get system time
creat: equ 3Ch ; Create file
open: equ 3Dh ; Open file
close: equ 3Eh ; Close file
read: equ 3Fh ; Read from file
write: equ 40h ; Write to file
lseek: equ 42h ; Set current file position
exit: equ 4ch ; Exit
;;; File modes
O_RDONLY: equ 0
O_WRONLY: equ 1
;;; Error codes (well, we only need the one)
ENOTFOUND: equ 2
;;; File positions (again we need only the one)
FP_END: equ 2
;;; File buffer size
BUFSZ: equ 4096
section .text
org 100h
cmp byte [cmdlen],0 ; Is the command line empty?
je printnotes ; Then, go print current notes
;;; Retrieve and format current date and time
mov ah,date ; Retrieve date
int 21h
mov di,datefmt ; Fill in date string
xor ah,ah
mov al,dh ; Write month
mov bl,2 ; Two digits
call asciinum
add di,3 ; Onwards three positions
mov al,dl ; Write day
mov bl,2 ; Two digits
call asciinum
add di,3 ; Onwards three positions
mov ax,cx ; Write year
mov bl,4 ; Four digits
call asciinum
mov ah,time ; Get system time
int 21h
mov di,timefmt+6 ; Fill in time string
xor ah,ah
mov al,dh ; Write seconds
mov bl,2 ; Two digits
call asciinum
sub di,3 ; Back three positions
mov al,cl ; Write minutes
mov bl,2 ; Two digits
call asciinum
cmp ch,12 ; AM or PM?
jbe houram ; <=12, AM
sub ch,12 ; PM - subtract 12 hours,
mov byte [ampm],'P' ; And set the AM/PM to 'P'(M)
jmp wrhours
houram: and ch,ch ; Hour 0 is 12:XX:XX AM.
jnz wrhours
mov ch,12
wrhours: sub di,3 ; Back three positions
mov al,ch ; Write hours
mov bl,2 ; Two digits
call asciinum
;;; Open or create the NOTES.TXT file
mov dx,filnam
mov ax,open<<8|O_WRONLY
int 21h ; Try to open the file
jnc writenote ; If successful, go write the note
cmp al,ENOTFOUND ; File not found?
jne diefile ; Some other error = print error msg
mov ah,creat ; No notes file, try to create it
xor cx,cx ; Normal file (no attributes set)
int 21h
jc diefile ; If that fails too, print error msg
;;; Write the note to the file
writenote: mov bx,ax ; File handle in BX
mov ax,lseek<<8|FP_END ; Seek to end of file
xor cx,cx ; Offset 0
xor dx,dx
int 21h
jc diefile ; Error if it fails
mov dx,datetime ; Write the date/time string first
mov cx,dtsize
mov ah,write
int 21h
jc diefile ; Error if it fails
mov cx,bx ; Store file handle in CX
;;; Terminate note with \r\n
xor bx,bx ; BX = length of command line
mov bl,[cmdlen] ; Find 2 bytes past cmd input
add bx,cmdlen+1 ; Note: this might overwrite the first
mov word [bx],0A0Dh ; instruction, but we don't need it
sub bx,cmdtail-2 ; Get length (add 2 for the 0D0A)
xchg bx,cx ; File handle in BX, length in CX
mov dx,cmdtail ; Write what's on the command line
mov ah,write
int 21h
jc diefile ; Error if it fails.
jmp closeexit ; Close file and exit if it succeeds.
;;; Print the contents of the NOTES.TXT file
printnotes: mov dx,filnam ; Open file for reading
mov ax,open<<8|O_RDONLY
int 21h
jnc readnotes ; Carry flag set = error.
cmp al,ENOTFOUND ; File not found?
jne diefile ; Some other error = print error msg
jmp exitok ; Not found = no notes = just exit
readnotes: mov di,ax ; Keep the file handle in DI.
.loop mov bx,di ; Get file handle for file
mov cx,BUFSZ ; Read as many bytes as will fit in the
mov ah,read ; buffer
int 21h
jc diefile ; Carry flag set = error
and ax,ax ; If 0 bytes read, we're done.
jz .done
xor bx,bx ; File handle 0 = standard output
mov cx,ax ; Write as many bytes as we read
mov ah,write
int 21h
jc diefile
jmp .loop ; Go get more bytes if there are any
.done mov bx,di ; Done: close the file
closeexit: mov ah,close
int 21h
exitok: mov ax,exit<<8|0 ; Exit with errorlevel 0 (success)
int 21h
;;; Print 'File error' and exit.
diefile: mov dx,fileerror
;;; Print error message in DX and exit
die: mov ah,puts ; Print error message
int 21h
mov ax,exit<<8|2 ; Exit with errorlevel 2.
int 21h
;;; Subroutine: write AX as BL-digit ASCII number at [DI]
asciinum: push dx ; Store DX and CX
push cx
mov cx,10 ; CX = divisor
xor bh,bh ; We never need >255.
.loop: xor dx,dx ; Set high word of division to 0.
div cx ; AX /= CX; DX = AX % CX
add dl,'0' ; Make digit ASCII
dec bl ; Move forward one digit
mov [di+bx],dl ; Store digit
jnz .loop ; Are we there yet?
pop cx ; Restore DX and CX
pop dx
ret
section .data
datetime: equ $ ; Start of date/time string.
datefmt: db '**/**/**** ' ; Date placeholder,
timefmt: db '**:**:** ' ; Time placeholder,
ampm: db 'AM' ; AM/PM placeholder.
db 13,10,9 ; \r\n\t
dtsize: equ $-datetime ; Size of date/time string.
fileerror: db 'File error.$' ; Printed on error
filnam: db 'NOTES.TXT',0 ; File name to use
section .bss
filebuf: resb BUFSZ ; 4K file buffer |
http://rosettacode.org/wiki/Taxicab_numbers | Taxicab numbers |
A taxicab number (the definition that is being used here) is a positive integer that can be expressed as the sum of two positive cubes in more than one way.
The first taxicab number is 1729, which is:
13 + 123 and also
93 + 103.
Taxicab numbers are also known as:
taxi numbers
taxi-cab numbers
taxi cab numbers
Hardy-Ramanujan numbers
Task
Compute and display the lowest 25 taxicab numbers (in numeric order, and in a human-readable format).
For each of the taxicab numbers, show the number as well as it's constituent cubes.
Extra credit
Show the 2,000th taxicab number, and a half dozen more
See also
A001235: taxicab numbers on The On-Line Encyclopedia of Integer Sequences.
Hardy-Ramanujan Number on MathWorld.
taxicab number on MathWorld.
taxicab number on Wikipedia (includes the story on how taxi-cab numbers came to be called).
| #C.2B.2B | C++ | #include <algorithm>
#include <iomanip>
#include <iostream>
#include <map>
#include <sstream>
#include <vector>
template <typename T>
size_t indexOf(const std::vector<T> &v, const T &k) {
auto it = std::find(v.cbegin(), v.cend(), k);
if (it != v.cend()) {
return it - v.cbegin();
}
return -1;
}
int main() {
std::vector<size_t> cubes;
auto dump = [&cubes](const std::string &title, const std::map<int, size_t> &items) {
std::cout << title;
for (auto &item : items) {
std::cout << "\n" << std::setw(4) << item.first << " " << std::setw(10) << item.second;
for (auto x : cubes) {
auto y = item.second - x;
if (y < x) {
break;
}
if (std::count(cubes.begin(), cubes.end(), y)) {
std::cout << " = " << std::setw(4) << indexOf(cubes, y) << "^3 + " << std::setw(3) << indexOf(cubes, x) << "^3";
}
}
}
};
std::vector<size_t> sums;
// create sorted list of cube sums
for (size_t i = 0; i < 1190; i++) {
auto cube = i * i * i;
cubes.push_back(cube);
for (auto j : cubes) {
sums.push_back(cube + j);
}
}
std::sort(sums.begin(), sums.end());
// now seek consecutive sums that match
auto nm1 = sums[0];
auto n = sums[1];
int idx = 0;
std::map<int, size_t> task;
std::map<int, size_t> trips;
auto it = sums.cbegin();
auto end = sums.cend();
it++;
it++;
while (it != end) {
auto np1 = *it;
if (nm1 == np1) {
trips.emplace(idx, n);
}
if (nm1 != n && n == np1) {
if (++idx <= 25 || idx >= 2000 == idx <= 2006) {
task.emplace(idx, n);
}
}
nm1 = n;
n = np1;
it++;
}
dump("First 25 Taxicab Numbers, the 2000th, plus the next half-dozen:", task);
std::stringstream ss;
ss << "\n\nFound " << trips.size() << " triple Taxicabs under 2007:";
dump(ss.str(), trips);
return 0;
} |
http://rosettacode.org/wiki/Tau_number | Tau number | A Tau number is a positive integer divisible by the count of its positive divisors.
Task
Show the first 100 Tau numbers.
The numbers shall be generated during run-time (i.e. the code may not contain string literals, sets/arrays of integers, or alike).
Related task
Tau function
| #C.2B.2B | C++ | #include <iomanip>
#include <iostream>
// See https://en.wikipedia.org/wiki/Divisor_function
unsigned int divisor_count(unsigned int n) {
unsigned int total = 1;
// Deal with powers of 2 first
for (; (n & 1) == 0; n >>= 1)
++total;
// Odd prime factors up to the square root
for (unsigned int p = 3; p * p <= n; p += 2) {
unsigned int count = 1;
for (; n % p == 0; n /= p)
++count;
total *= count;
}
// If n > 1 then it's prime
if (n > 1)
total *= 2;
return total;
}
int main() {
const unsigned int limit = 100;
std::cout << "The first " << limit << " tau numbers are:\n";
unsigned int count = 0;
for (unsigned int n = 1; count < limit; ++n) {
if (n % divisor_count(n) == 0) {
std::cout << std::setw(6) << n;
++count;
if (count % 10 == 0)
std::cout << '\n';
}
}
} |
http://rosettacode.org/wiki/Tarjan | Tarjan |
This page uses content from Wikipedia. The original article was at Graph. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Tarjan's algorithm is an algorithm in graph theory for finding the strongly connected components of a graph.
It runs in linear time, matching the time bound for alternative methods including Kosaraju's algorithm and the path-based strong component algorithm.
Tarjan's Algorithm is named for its discoverer, Robert Tarjan.
References
The article on Wikipedia.
| #C.23 | C# | using System;
using System.Collections.Generic;
class Node
{
public int LowLink { get; set; }
public int Index { get; set; }
public int N { get; }
public Node(int n)
{
N = n;
Index = -1;
LowLink = 0;
}
}
class Graph
{
public HashSet<Node> V { get; }
public Dictionary<Node, HashSet<Node>> Adj { get; }
/// <summary>
/// Tarjan's strongly connected components algorithm
/// </summary>
public void Tarjan()
{
var index = 0; // number of nodes
var S = new Stack<Node>();
Action<Node> StrongConnect = null;
StrongConnect = (v) =>
{
// Set the depth index for v to the smallest unused index
v.Index = index;
v.LowLink = index;
index++;
S.Push(v);
// Consider successors of v
foreach (var w in Adj[v])
if (w.Index < 0)
{
// Successor w has not yet been visited; recurse on it
StrongConnect(w);
v.LowLink = Math.Min(v.LowLink, w.LowLink);
}
else if (S.Contains(w))
// Successor w is in stack S and hence in the current SCC
v.LowLink = Math.Min(v.LowLink, w.Index);
// If v is a root node, pop the stack and generate an SCC
if (v.LowLink == v.Index)
{
Console.Write("SCC: ");
Node w;
do
{
w = S.Pop();
Console.Write(w.N + " ");
} while (w != v);
Console.WriteLine();
}
};
foreach (var v in V)
if (v.Index < 0)
StrongConnect(v);
}
} |
http://rosettacode.org/wiki/Teacup_rim_text | Teacup rim text | On a set of coasters we have, there's a picture of a teacup. On the rim of the teacup the word TEA appears a number of times separated by bullet characters (•).
It occurred to me that if the bullet were removed and the words run together, you could start at any letter and still end up with a meaningful three-letter word.
So start at the T and read TEA. Start at the E and read EAT, or start at the A and read ATE.
That got me thinking that maybe there are other words that could be used rather that TEA. And that's just English. What about Italian or Greek or ... um ... Telugu.
For English, we will use the unixdict (now) located at: unixdict.txt.
(This will maintain continuity with other Rosetta Code tasks that also use it.)
Task
Search for a set of words that could be printed around the edge of a teacup. The words in each set are to be of the same length, that length being greater than two (thus precluding AH and HA, for example.)
Having listed a set, for example [ate tea eat], refrain from displaying permutations of that set, e.g.: [eat tea ate] etc.
The words should also be made of more than one letter (thus precluding III and OOO etc.)
The relationship between these words is (using ATE as an example) that the first letter of the first becomes the last letter of the second. The first letter of the second becomes the last letter of the third. So ATE becomes TEA and TEA becomes EAT.
All of the possible permutations, using this particular permutation technique, must be words in the list.
The set you generate for ATE will never included the word ETA as that cannot be reached via the first-to-last movement method.
Display one line for each set of teacup rim words.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Haskell | Haskell | import Data.List (groupBy, intercalate, sort, sortBy)
import qualified Data.Set as S
import Data.Ord (comparing)
import Data.Function (on)
main :: IO ()
main =
readFile "mitWords.txt" >>= (putStrLn . showGroups . circularWords . lines)
circularWords :: [String] -> [String]
circularWords ws =
let lexicon = S.fromList ws
in filter (isCircular lexicon) ws
isCircular :: S.Set String -> String -> Bool
isCircular lex w = 2 < length w && all (`S.member` lex) (rotations w)
rotations :: [a] -> [[a]]
rotations = fmap <$> rotated <*> (enumFromTo 0 . pred . length)
rotated :: [a] -> Int -> [a]
rotated [] _ = []
rotated xs n = zipWith const (drop n (cycle xs)) xs
showGroups :: [String] -> String
showGroups xs =
unlines $
intercalate " -> " . fmap snd <$>
filter
((1 <) . length)
(groupBy (on (==) fst) (sortBy (comparing fst) (((,) =<< sort) <$> xs))) |
http://rosettacode.org/wiki/Temperature_conversion | Temperature conversion | There are quite a number of temperature scales. For this task we will concentrate on four of the perhaps best-known ones:
Kelvin, Celsius, Fahrenheit, and Rankine.
The Celsius and Kelvin scales have the same magnitude, but different null points.
0 degrees Celsius corresponds to 273.15 kelvin.
0 kelvin is absolute zero.
The Fahrenheit and Rankine scales also have the same magnitude, but different null points.
0 degrees Fahrenheit corresponds to 459.67 degrees Rankine.
0 degrees Rankine is absolute zero.
The Celsius/Kelvin and Fahrenheit/Rankine scales have a ratio of 5 : 9.
Task
Write code that accepts a value of kelvin, converts it to values of the three other scales, and prints the result.
Example
K 21.00
C -252.15
F -421.87
R 37.80
| #Ada | Ada | with Ada.Float_Text_IO, Ada.Text_IO; use Ada.Float_Text_IO, Ada.Text_IO;
procedure Temperatur_Conversion is
K: Float;
function C return Float is (K - 273.15);
function F return Float is (K * 1.8 - 459.67);
function R return Float is (K * 1.8);
begin
Get(K); New_Line; -- Format
Put("K: "); Put(K, Fore => 4, Aft => 2, Exp => 0); New_Line;-- K: dddd.dd
Put("C: "); Put(C, Fore => 4, Aft => 2, Exp => 0); New_Line;-- C: dddd.dd
Put("F: "); Put(F, Fore => 4, Aft => 2, Exp => 0); New_Line;-- F: dddd.dd
Put("R: "); Put(R, Fore => 4, Aft => 2, Exp => 0); New_Line;-- R: dddd.dd
end; |
http://rosettacode.org/wiki/Tau_function | Tau function | Given a positive integer, count the number of its positive divisors.
Task
Show the result for the first 100 positive integers.
Related task
Tau number
| #ARM_Assembly | ARM Assembly |
/* ARM assembly Raspberry PI */
/* program taufunction.s */
/* REMARK 1 : this program use routines in a include file
see task Include a file language arm assembly
for the routine affichageMess conversion10
see at end of this program the instruction include */
/* for constantes see task include a file in arm assembly */
/************************************/
/* Constantes */
/************************************/
.include "../constantes.inc"
.equ MAXI, 100
/*********************************/
/* Initialized data */
/*********************************/
.data
sMessResult: .asciz " @ "
szCarriageReturn: .asciz "\n"
/*********************************/
/* UnInitialized data */
/*********************************/
.bss
sZoneConv: .skip 24
/*********************************/
/* code section */
/*********************************/
.text
.global main
main: @ entry of program
mov r0,#1 @ factor number one
bl displayResult
mov r0,#2 @ factor number two
bl displayResult
mov r2,#3 @ begin number three
1: @ begin loop
mov r5,#2 @ divisor counter
mov r4,#2 @ first divisor 1
2:
udiv r0,r2,r4 @ compute divisor 2
mls r3,r0,r4,r2 @ remainder
cmp r3,#0
bne 3f @ remainder = 0 ?
cmp r0,r4 @ same divisor ?
addeq r5,r5,#1 @ yes increment one
addne r5,r5,#2 @ no increment two
3:
add r4,r4,#1 @ increment divisor
cmp r4,r0 @ divisor 1 < divisor 2
blt 2b @ yes -> loop
mov r0,r5 @ equal -> display
bl displayResult
add r2,#1 @
cmp r2,#MAXI @ end ?
bls 1b @ no -> loop
ldr r0,iAdrszCarriageReturn
bl affichageMess
100: @ standard end of the program
mov r0, #0 @ return code
mov r7, #EXIT @ request to exit program
svc #0 @ perform the system call
iAdrszCarriageReturn: .int szCarriageReturn
/***************************************************/
/* display message number */
/***************************************************/
/* r0 contains the number */
displayResult:
push {r1,r2,lr} @ save registers
ldr r1,iAdrsZoneConv
bl conversion10 @ call décimal conversion
mov r2,#0
strb r2,[r1,r0]
ldr r0,iAdrsMessResult
ldr r1,iAdrsZoneConv @ insert conversion in message
bl strInsertAtCharInc
bl affichageMess @ display message
pop {r1,r2,pc} @ restaur des registres
iAdrsMessResult: .int sMessResult
iAdrsZoneConv: .int sZoneConv
/***************************************************/
/* ROUTINES INCLUDE */
/***************************************************/
.include "../affichage.inc"
|
http://rosettacode.org/wiki/Terminal_control/Clear_the_screen | Terminal control/Clear the screen | Task
Clear the terminal window.
| #Blast | Blast | clear |
http://rosettacode.org/wiki/Terminal_control/Clear_the_screen | Terminal control/Clear the screen | Task
Clear the terminal window.
| #Blue | Blue | global _start
: syscall ( num:eax -- result:eax ) syscall ;
: exit ( status:edi -- noret ) 60 syscall ;
: bye ( -- noret ) 0 exit ;
1 const stdout
: write ( buf:esi len:edx fd:edi -- ) 1 syscall drop ;
: print ( buf len -- ) stdout write ;
: clear-screen ( -- ) s" \033[2J\033[H" print ;
: _start ( -- noret ) clear-screen bye ; |
http://rosettacode.org/wiki/Terminal_control/Clear_the_screen | Terminal control/Clear the screen | Task
Clear the terminal window.
| #Bracmat | Bracmat | sys$cls& |
http://rosettacode.org/wiki/Ternary_logic | Ternary logic |
This page uses content from Wikipedia. The original article was at Ternary logic. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
In logic, a three-valued logic (also trivalent, ternary, or trinary logic, sometimes abbreviated 3VL) is any of several many-valued logic systems in which there are three truth values indicating true, false and some indeterminate third value.
This is contrasted with the more commonly known bivalent logics (such as classical sentential or boolean logic) which provide only for true and false.
Conceptual form and basic ideas were initially created by Łukasiewicz, Lewis and Sulski.
These were then re-formulated by Grigore Moisil in an axiomatic algebraic form, and also extended to n-valued logics in 1945.
Example Ternary Logic Operators in Truth Tables:
not a
¬
True
False
Maybe
Maybe
False
True
a and b
∧
True
Maybe
False
True
True
Maybe
False
Maybe
Maybe
Maybe
False
False
False
False
False
a or b
∨
True
Maybe
False
True
True
True
True
Maybe
True
Maybe
Maybe
False
True
Maybe
False
if a then b
⊃
True
Maybe
False
True
True
Maybe
False
Maybe
True
Maybe
Maybe
False
True
True
True
a is equivalent to b
≡
True
Maybe
False
True
True
Maybe
False
Maybe
Maybe
Maybe
Maybe
False
False
Maybe
True
Task
Define a new type that emulates ternary logic by storing data trits.
Given all the binary logic operators of the original programming language, reimplement these operators for the new Ternary logic type trit.
Generate a sampling of results using trit variables.
Kudos for actually thinking up a test case algorithm where ternary logic is intrinsically useful, optimises the test case algorithm and is preferable to binary logic.
Note: Setun (Сетунь) was a balanced ternary computer developed in 1958 at Moscow State University. The device was built under the lead of Sergei Sobolev and Nikolay Brusentsov. It was the only modern ternary computer, using three-valued ternary logic
| #Free_Pascal | Free Pascal | {$mode objfpc}
unit ternarylogic;
interface
type
{ ternary type, balanced }
trit = (tFalse=-1, tMaybe=0, tTrue=1);
{ ternary operators }
{ equivalence = multiplication }
operator * (const a,b:trit):trit;
operator and (const a,b:trit):trit;inline;
operator or (const a,b:trit):trit;inline;
operator not (const a:trit):trit;inline;
operator xor (const a,b:trit):trit;
{ imp ==>}
operator >< (const a,b:trit):trit;
implementation
operator and (const a,b:trit):trit;inline;
const lookupAnd:array[trit,trit] of trit =
((tFalse,tFalse,tFalse),
(tFalse,tMaybe,tMaybe),
(tFalse,tMaybe,tTrue));
begin
Result:= LookupAnd[a,b];
end;
operator or (const a,b:trit):trit;inline;
const lookupOr:array[trit,trit] of trit =
((tFalse,tMaybe,tTrue),
(tMaybe,tMaybe,tTrue),
(tTrue,tTrue,tTrue));
begin
Result := LookUpOr[a,b];
end;
operator not (const a:trit):trit;inline;
const LookupNot:array[trit] of trit =(tTrue,tMaybe,tFalse);
begin
Result:= LookUpNot[a];
end;
operator xor (const a,b:trit):trit;
const LookupXor:array[trit,trit] of trit =
((tFalse,tMaybe,tTrue),
(tMaybe,tMaybe,tMaybe),
(tTrue,tMaybe,tFalse));
begin
Result := LookupXor[a,b];
end;
operator * (const a,b:trit):trit;
begin
result := not (a xor b);
end;
{ imp ==>}
operator >< (const a,b:trit):trit;
begin
result := not(a) or b;
end;
end.
|
http://rosettacode.org/wiki/Text_processing/1 | Text processing/1 | This task has been flagged for clarification. Code on this page in its current state may be flagged incorrect once this task has been clarified. See this page's Talk page for discussion.
Often data is produced by one program, in the wrong format for later use by another program or person. In these situations another program can be written to parse and transform the original data into a format useful to the other. The term "Data Munging" is often used in programming circles for this task.
A request on the comp.lang.awk newsgroup led to a typical data munging task:
I have to analyse data files that have the following format:
Each row corresponds to 1 day and the field logic is: $1 is the date,
followed by 24 value/flag pairs, representing measurements at 01:00,
02:00 ... 24:00 of the respective day. In short:
<date> <val1> <flag1> <val2> <flag2> ... <val24> <flag24>
Some test data is available at:
... (nolonger available at original location)
I have to sum up the values (per day and only valid data, i.e. with
flag>0) in order to calculate the mean. That's not too difficult.
However, I also need to know what the "maximum data gap" is, i.e. the
longest period with successive invalid measurements (i.e values with
flag<=0)
The data is free to download and use and is of this format:
Data is no longer available at that link. Zipped mirror available here (offsite mirror).
1991-03-30 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1
1991-03-31 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 20.000 1 20.000 1 20.000 1 35.000 1 50.000 1 60.000 1 40.000 1 30.000 1 30.000 1 30.000 1 25.000 1 20.000 1 20.000 1 20.000 1 20.000 1 20.000 1 35.000 1
1991-03-31 40.000 1 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2
1991-04-01 0.000 -2 13.000 1 16.000 1 21.000 1 24.000 1 22.000 1 20.000 1 18.000 1 29.000 1 44.000 1 50.000 1 43.000 1 38.000 1 27.000 1 27.000 1 24.000 1 23.000 1 18.000 1 12.000 1 13.000 1 14.000 1 15.000 1 13.000 1 10.000 1
1991-04-02 8.000 1 9.000 1 11.000 1 12.000 1 12.000 1 12.000 1 27.000 1 26.000 1 27.000 1 33.000 1 32.000 1 31.000 1 29.000 1 31.000 1 25.000 1 25.000 1 24.000 1 21.000 1 17.000 1 14.000 1 15.000 1 12.000 1 12.000 1 10.000 1
1991-04-03 10.000 1 9.000 1 10.000 1 10.000 1 9.000 1 10.000 1 15.000 1 24.000 1 28.000 1 24.000 1 18.000 1 14.000 1 12.000 1 13.000 1 14.000 1 15.000 1 14.000 1 15.000 1 13.000 1 13.000 1 13.000 1 12.000 1 10.000 1 10.000 1
Only a sample of the data showing its format is given above. The full example file may be downloaded here.
Structure your program to show statistics for each line of the file, (similar to the original Python, Perl, and AWK examples below), followed by summary statistics for the file. When showing example output just show a few line statistics and the full end summary.
| #J | J | load 'files'
parseLine=: 10&({. ,&< (_99&".;._1)@:}.) NB. custom parser
summarize=: # , +/ , +/ % # NB. count,sum,mean
filter=: #~ 0&< NB. keep valid measurements
'Dates dat'=: |: parseLine;._2 CR -.~ fread jpath '~temp/readings.txt'
Vals=: (+: i.24){"1 dat
Flags=: (>: +: i.24){"1 dat
DailySummary=: Vals summarize@filter"1 Flags
RunLengths=: ([: #(;.1) 0 , }. *. }:) , 0 >: Flags
]MaxRun=: >./ RunLengths
589
]StartDates=: Dates {~ (>:@I.@e.&MaxRun (24 <.@%~ +/)@{. ]) RunLengths
1993-03-05 |
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.
| #Sidef | Sidef | require('Math::Random::ISAAC')
func xor_isaac(key, msg) {
var rng = %O<Math::Random::ISAAC>.new(unpack('C*', key))
msg.chars»ord()» \
-> »^« 256.of{ rng.irand % 95 + 32 }.last(msg.len).flip \
-> «%« '%02X' -> join
}
var msg = 'a Top Secret secret'
var key = 'this is my secret key'
var enc = xor_isaac(key, msg)
var dec = xor_isaac(key, pack('H*', enc))
say "Message: #{msg}"
say "Key : #{key}"
say "XOR : #{enc}"
say "XOR dcr: #{pack('H*', dec)}" |
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).
| #Tcl | Tcl | set out 0
set max_out -1
set max_times {}
foreach job [split [read [open "mlijobs.txt" "r"]] "\n"] {
if {[lindex $job 1] == "OUT"} {
incr out
} {
incr out -1
}
if {$out > $max_out} {
set max_out $out
set max_times {}
}
if {$out == $max_out} {
lappend max_times [lindex $job 3]
}
}
puts "Maximum simultaneous license use is $max_out at the following times:"
foreach t $max_times {
puts " $t"
} |
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.
| #Raku | Raku | use Test;
sub palin( Str $string) { so $string.lc.comb(/\w/) eq $string.flip.lc.comb(/\w/) }
my %tests =
'A man, a plan, a canal: Panama.' => True,
'My dog has fleas' => False,
"Madam, I'm Adam." => True,
'1 on 1' => False,
'In girum imus nocte et consumimur igni' => True,
'' => True,
;
plan %tests.elems;
for %tests.kv -> $test, $expected-result {
is palin($test), $expected-result,
"\"$test\" is {$expected-result??''!!'not '}a 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.
| #Retro | Retro | needs assertion'
needs hash'
: palindrome? ( $-f ) dup ^hash'hash [ ^strings'reverse ^hash'hash ] dip = ;
with assertion'
: t0 ( - ) "hello" palindrome? 0 assert= ; assertion
: t1 ( - ) "ingirumimusnocteetconsumimurigni" palindrome? -1 assert= ; assertion
: test ( - ) t0 t1 ;
test |
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
| #Erlang | Erlang | -module(twelve_days).
-export([gifts_for_day/1]).
names(N) -> lists:nth(N,
["first", "second", "third", "fourth", "fifth", "sixth",
"seventh", "eighth", "ninth", "tenth", "eleventh", "twelfth" ]).
gifts() -> [ "A partridge in a pear tree.", "Two turtle doves and",
"Three French hens,", "Four calling birds,",
"Five gold rings,", "Six geese a-laying,",
"Seven swans a-swimming,", "Eight maids a-milking,",
"Nine ladies dancing,", "Ten lords a-leaping,",
"Eleven pipers piping,", "Twelve drummers drumming," ].
gifts_for_day(N) ->
"On the " ++ names(N) ++ " day of Christmas, my true love sent to me:\n" ++
string:join(lists:reverse(lists:sublist(gifts(), N)), "\n").
main(_) -> lists:map(fun(N) -> io:fwrite("~s~n~n", [gifts_for_day(N)]) end,
lists:seq(1,12)).
|
http://rosettacode.org/wiki/Terminal_control/Coloured_text | Terminal control/Coloured text | Task
Display a word in various colours on the terminal.
The system palette, or colours such as Red, Green, Blue, Magenta, Cyan, and Yellow can be used.
Optionally demonstrate:
How the system should determine if the terminal supports colour
Setting of the background colour
How to cause blinking or flashing (if supported by the terminal)
| #Go | Go | package main
import (
"fmt"
"os"
"os/exec"
)
func main() {
color(red)
fmt.Println("Red")
color(green)
fmt.Println("Green")
color(blue)
fmt.Println("Blue")
}
const (
blue = "1"
green = "2"
red = "4"
)
func color(c string) {
cmd := exec.Command("tput", "setf", c)
cmd.Stdout = os.Stdout
cmd.Run()
} |
http://rosettacode.org/wiki/Terminal_control/Coloured_text | Terminal control/Coloured text | Task
Display a word in various colours on the terminal.
The system palette, or colours such as Red, Green, Blue, Magenta, Cyan, and Yellow can be used.
Optionally demonstrate:
How the system should determine if the terminal supports colour
Setting of the background colour
How to cause blinking or flashing (if supported by the terminal)
| #Golo | Golo | #!/usr/bin/env golosh
----
This module demonstrates terminal colours.
----
module Terminalcontrolcoloredtext
import gololang.AnsiCodes
function main = |args| {
# these are lists of pointers to the ansi functions in the golo library.
# {} doesn't do anything so it's got no effect on the text.
let foregrounds = vector[
^fg_red, ^fg_blue, ^fg_magenta, ^fg_white, ^fg_black, ^fg_cyan, ^fg_green, ^fg_yellow
]
let backgrounds = vector[
^bg_red, ^bg_blue, ^bg_magenta, ^bg_white, ^bg_black, ^bg_cyan, ^bg_green, ^bg_yellow
]
let effects = vector[
{}, ^bold, ^blink, ^underscore, ^concealed, ^reverse_video
]
println("Terminal supports ansi code: " + likelySupported())
foreach fg in foregrounds {
foreach bg in backgrounds {
foreach effect in effects {
fg()
bg()
effect()
print("Rosetta Code")
reset()
}
}
}
println("")
} |
http://rosettacode.org/wiki/Terminal_control/Cursor_movement | Terminal control/Cursor movement | Task
Demonstrate how to achieve movement of the terminal cursor:
how to move the cursor one position to the left
how to move the cursor one position to the right
how to move the cursor up one line (without affecting its horizontal position)
how to move the cursor down one line (without affecting its horizontal position)
how to move the cursor to the beginning of the line
how to move the cursor to the end of the line
how to move the cursor to the top left corner of the screen
how to move the cursor to the bottom right corner of the screen
For the purpose of this task, it is not permitted to overwrite any characters or attributes on any part of the screen (so outputting a space is not a suitable solution to achieve a movement to the right).
Handling of out of bounds locomotion
This task has no specific requirements to trap or correct cursor movement beyond the terminal boundaries, so the implementer should decide what behavior fits best in terms of the chosen language. Explanatory notes may be added to clarify how an out of bounds action would behave and the generation of error messages relating to an out of bounds cursor position is permitted.
| #Racket | Racket |
#lang racket
(require (planet neil/charterm:3:0))
(define x 0)
(define y 0)
(define (on-key k)
(match k
['down (move 0 -1)]
['up (move 0 +1)]
['right (move +1 0)]
['left (move -1 0)]
[else #f]))
(define (move dx dy)
(set! x (+ x dx))
(set! y (+ y dy))
(charterm-cursor x y))
(with-charterm
(charterm-clear-screen)
(charterm-cursor 0 0)
(let loop ([continue? #t])
(when continue?
(loop (on-key (charterm-read-key))))))
|
http://rosettacode.org/wiki/Terminal_control/Cursor_movement | Terminal control/Cursor movement | Task
Demonstrate how to achieve movement of the terminal cursor:
how to move the cursor one position to the left
how to move the cursor one position to the right
how to move the cursor up one line (without affecting its horizontal position)
how to move the cursor down one line (without affecting its horizontal position)
how to move the cursor to the beginning of the line
how to move the cursor to the end of the line
how to move the cursor to the top left corner of the screen
how to move the cursor to the bottom right corner of the screen
For the purpose of this task, it is not permitted to overwrite any characters or attributes on any part of the screen (so outputting a space is not a suitable solution to achieve a movement to the right).
Handling of out of bounds locomotion
This task has no specific requirements to trap or correct cursor movement beyond the terminal boundaries, so the implementer should decide what behavior fits best in terms of the chosen language. Explanatory notes may be added to clarify how an out of bounds action would behave and the generation of error messages relating to an out of bounds cursor position is permitted.
| #Raku | Raku | shell "tput cub1"; # one position to the left
shell "tput cuf1"; # one position to the right
shell "tput cuu1"; # up one line
shell "tput cud1"; # down one line
shell "tput cr"; # beginning of line
shell "tput home"; # top left corner
$_ = qx[stty -a </dev/tty 2>&1];
my $rows = +m/'rows ' <(\d+)>/;
my $cols = +m/'columns ' <(\d+)>/;
shell "tput hpa $cols"; # end of line
shell "tput cup $rows $cols"; # bottom right corner |
http://rosettacode.org/wiki/Terminal_control/Cursor_movement | Terminal control/Cursor movement | Task
Demonstrate how to achieve movement of the terminal cursor:
how to move the cursor one position to the left
how to move the cursor one position to the right
how to move the cursor up one line (without affecting its horizontal position)
how to move the cursor down one line (without affecting its horizontal position)
how to move the cursor to the beginning of the line
how to move the cursor to the end of the line
how to move the cursor to the top left corner of the screen
how to move the cursor to the bottom right corner of the screen
For the purpose of this task, it is not permitted to overwrite any characters or attributes on any part of the screen (so outputting a space is not a suitable solution to achieve a movement to the right).
Handling of out of bounds locomotion
This task has no specific requirements to trap or correct cursor movement beyond the terminal boundaries, so the implementer should decide what behavior fits best in terms of the chosen language. Explanatory notes may be added to clarify how an out of bounds action would behave and the generation of error messages relating to an out of bounds cursor position is permitted.
| #REXX | REXX | /*REXX pgm demonstrates how to achieve movement of the terminal cursor. */
parse value scrsize() with sd sw /*find the display screen size. */
parse value cursor() with row col /*find where the cursor is now. */
colL=col-1; if colL==0 then colL=sw /*prepare to move cursor to left.*/
call cursor row,colL /*move cursor to the left (wrap).*/
colR=col+1; if colR>sw then colL=1 /*prepare to move cursor to right*/
call cursor row,colR /*move cursor to the right (wrap)*/
rowU=row-1; if rowU==0 then rowU=sd /*prepare to move cursor up. */
call cursor rowU,col /*move cursor up (with wrap). */
rowD=row+1; if rowD>sd then rowD=1 /*prepare to move cursor down. */
call cursor rowD,col /*move cursor down (with wrap). */
call cursor row,1 /*move cursor to beginning of row*/
call cursor row,sw /*move cursor to end of row*/
call cursor 1,1 /*move cursor to top left corner.*/
call cursor sd,sw /*move cursor to bot right corner*/
/*stick a fork in it, we're done.*/ |
http://rosettacode.org/wiki/Table_creation/Postal_addresses | Table creation/Postal addresses | Task
Create a table to store addresses.
You may assume that all the addresses to be stored will be located in the USA. As such, you will need (in addition to a field holding a unique identifier) a field holding the street address, a field holding the city, a field holding the state code, and a field holding the zipcode. Choose appropriate types for each field.
For non-database languages, show how you would open a connection to a database (your choice of which) and create an address table in it. You should follow the existing models here for how you would structure the table.
| #ALGOL_68 | ALGOL 68 | MODE ADDRESS = STRUCT(
INT page,
FLEX[50]CHAR street,
FLEX[25]CHAR city,
FLEX[2]CHAR state,
FLEX[10]CHAR zip
);
FORMAT address repr = $"Page: "gl"Street: "gl"City: "gl"State: "gl"Zip: "gll$;
INT errno;
FILE sequence; errno := open(sequence, "sequence.txt", stand back channel);
SEMA sequence sema := LEVEL 1;
OP NEXTVAL = ([]CHAR table name)INT: (
INT out;
# INT table page = 0; # # only one sequence implemented #
# DOWN sequence sema; # # NO interprocess concurrency protection #
on open error(sequence,
(REF FILE f)BOOL: (
reset(sequence); #set(table page,1,1);#
put(sequence, 0);
try again;
FALSE
)
);
try again:
reset(sequence); #set(table page,1,1);# get(sequence,out);
out +:=1;
reset(sequence); #set(table page,1,1);# put(sequence,out);
# UP sequence sema; #
out
);
OP INIT = (REF ADDRESS self)REF ADDRESS: ( page OF self := NEXTVAL "address"; self);
REF ADDRESS john brown = INIT LOC ADDRESS;
john brown := (page OF john brown, "10 Downing Street","London","England","SW1A 2AA");
printf((address repr, john brown));
FILE address table;
errno := open(address table,"address.txt",stand back channel);
# set(address table, page OF john brown,1,1); - standard set page not available in a68g #
put bin(address table, john brown);
close(address table) |
http://rosettacode.org/wiki/Take_notes_on_the_command_line | Take notes on the command line | Take notes on the command line is part of Short Circuit's Console Program Basics selection.
Invoking NOTES without commandline arguments displays the current contents of the local NOTES.TXT if it exists.
If NOTES has arguments, the current date and time are appended to the local NOTES.TXT followed by a newline.
Then all the arguments, joined with spaces, prepended with a tab, and appended with a trailing newline, are written to NOTES.TXT.
If NOTES.TXT doesn't already exist in the current directory then a new NOTES.TXT file should be created.
| #Ada | Ada | with Ada.Calendar.Formatting;
with Ada.Characters.Latin_1;
with Ada.Command_Line;
with Ada.IO_Exceptions;
with Ada.Text_IO;
procedure Notes is
Notes_Filename : constant String := "notes.txt";
Notes_File : Ada.Text_IO.File_Type;
Argument_Count : Natural := Ada.Command_Line.Argument_Count;
begin
if Argument_Count = 0 then
begin
Ada.Text_IO.Open
(File => Notes_File,
Mode => Ada.Text_IO.In_File,
Name => Notes_Filename);
while not Ada.Text_IO.End_Of_File (File => Notes_File) loop
Ada.Text_IO.Put_Line (Ada.Text_IO.Get_Line (File => Notes_File));
end loop;
exception
when Ada.IO_Exceptions.Name_Error =>
null;
end;
else
begin
Ada.Text_IO.Open
(File => Notes_File,
Mode => Ada.Text_IO.Append_File,
Name => Notes_Filename);
exception
when Ada.IO_Exceptions.Name_Error =>
Ada.Text_IO.Create (File => Notes_File, Name => Notes_Filename);
end;
Ada.Text_IO.Put_Line
(File => Notes_File,
Item => Ada.Calendar.Formatting.Image (Date => Ada.Calendar.Clock));
Ada.Text_IO.Put (File => Notes_File, Item => Ada.Characters.Latin_1.HT);
for I in 1 .. Argument_Count loop
Ada.Text_IO.Put
(File => Notes_File,
Item => Ada.Command_Line.Argument (I));
if I /= Argument_Count then
Ada.Text_IO.Put (File => Notes_File, Item => ' ');
end if;
end loop;
Ada.Text_IO.Flush (File => Notes_File);
end if;
if Ada.Text_IO.Is_Open (File => Notes_File) then
Ada.Text_IO.Close (File => Notes_File);
end if;
end Notes; |
http://rosettacode.org/wiki/Taxicab_numbers | Taxicab numbers |
A taxicab number (the definition that is being used here) is a positive integer that can be expressed as the sum of two positive cubes in more than one way.
The first taxicab number is 1729, which is:
13 + 123 and also
93 + 103.
Taxicab numbers are also known as:
taxi numbers
taxi-cab numbers
taxi cab numbers
Hardy-Ramanujan numbers
Task
Compute and display the lowest 25 taxicab numbers (in numeric order, and in a human-readable format).
For each of the taxicab numbers, show the number as well as it's constituent cubes.
Extra credit
Show the 2,000th taxicab number, and a half dozen more
See also
A001235: taxicab numbers on The On-Line Encyclopedia of Integer Sequences.
Hardy-Ramanujan Number on MathWorld.
taxicab number on MathWorld.
taxicab number on Wikipedia (includes the story on how taxi-cab numbers came to be called).
| #C.23 | C# | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace TaxicabNumber
{
class Program
{
static void Main(string[] args)
{
IDictionary<long, IList<Tuple<int, int>>> taxicabNumbers = GetTaxicabNumbers(2006);
PrintTaxicabNumbers(taxicabNumbers);
Console.ReadKey();
}
private static IDictionary<long, IList<Tuple<int, int>>> GetTaxicabNumbers(int length)
{
SortedList<long, IList<Tuple<int, int>>> sumsOfTwoCubes = new SortedList<long, IList<Tuple<int, int>>>();
for (int i = 1; i < int.MaxValue; i++)
{
for (int j = 1; j < int.MaxValue; j++)
{
long sum = (long)(Math.Pow((double)i, 3) + Math.Pow((double)j, 3));
if (!sumsOfTwoCubes.ContainsKey(sum))
{
sumsOfTwoCubes.Add(sum, new List<Tuple<int, int>>());
}
sumsOfTwoCubes[sum].Add(new Tuple<int, int>(i, j));
if (j >= i)
{
break;
}
}
// Found that you need to keep going for a while after the length, because higher i values fill in gaps
if (sumsOfTwoCubes.Count(t => t.Value.Count >= 2) >= length * 1.1)
{
break;
}
}
IDictionary<long, IList<Tuple<int, int>>> values = (from t in sumsOfTwoCubes where t.Value.Count >= 2 select t)
.Take(2006)
.ToDictionary(u => u.Key, u => u.Value);
return values;
}
private static void PrintTaxicabNumbers(IDictionary<long, IList<Tuple<int, int>>> values)
{
int i = 1;
foreach (long taxicabNumber in values.Keys)
{
StringBuilder output = new StringBuilder().AppendFormat("{0,10}\t{1,4}", i, taxicabNumber);
foreach (Tuple<int, int> numbers in values[taxicabNumber])
{
output.AppendFormat("\t= {0}^3 + {1}^3", numbers.Item1, numbers.Item2);
}
if (i <= 25 || (i >= 2000 && i <= 2006))
{
Console.WriteLine(output.ToString());
}
i++;
}
}
}
} |
http://rosettacode.org/wiki/Tau_number | Tau number | A Tau number is a positive integer divisible by the count of its positive divisors.
Task
Show the first 100 Tau numbers.
The numbers shall be generated during run-time (i.e. the code may not contain string literals, sets/arrays of integers, or alike).
Related task
Tau function
| #CLU | CLU | % Count the divisors of [1..N]
count_divisors = proc (n: int) returns (sequence[int])
divs: array[int] := array[int]$fill(1, n, 1)
for i: int in int$from_to(2, n) do
for j: int in int$from_to_by(i, n, i) do
divs[j] := divs[j] + 1
end
end
return(sequence[int]$a2s(divs))
end count_divisors
% Find Tau numbers up to a given limit
tau_numbers = iter (lim: int) yields (int)
divs: sequence[int] := count_divisors(lim)
n: int := 0
while n < lim do
n := n + 1
if n // divs[n] = 0 then yield(n) end
end
end tau_numbers
% Show the first 100 Tau numbers
start_up = proc ()
po: stream := stream$primary_output()
seen: int := 0
for n: int in tau_numbers(1100) do
seen := seen + 1
stream$putright(po, int$unparse(n), 5)
if seen // 10 = 0 then stream$putl(po, "") end
if seen >= 100 then break end
end
end start_up |
http://rosettacode.org/wiki/Tau_number | Tau number | A Tau number is a positive integer divisible by the count of its positive divisors.
Task
Show the first 100 Tau numbers.
The numbers shall be generated during run-time (i.e. the code may not contain string literals, sets/arrays of integers, or alike).
Related task
Tau function
| #Cowgol | Cowgol | include "cowgol.coh";
# Get count of positive divisors of number
sub pos_div(num: uint16): (count: uint16) is
count := 1;
if num != 1 then
var cur: uint16 := 1;
while cur <= num/2 loop
if num % cur == 0 then
count := count + 1;
end if;
cur := cur + 1;
end loop;
end if;
end sub;
# Print first 100 Tau numbers
var nums: uint8 := 0;
var cur: uint16 := 0;
var col: uint16 := 10;
while nums < 100 loop
cur := cur + 1;
if cur % pos_div(cur) == 0 then
print_i16(cur);
col := col - 1;
if col == 0 then
print_nl();
col := 10;
else
print_char('\t');
end if;
nums := nums + 1;
end if;
end loop; |
http://rosettacode.org/wiki/Tau_number | Tau number | A Tau number is a positive integer divisible by the count of its positive divisors.
Task
Show the first 100 Tau numbers.
The numbers shall be generated during run-time (i.e. the code may not contain string literals, sets/arrays of integers, or alike).
Related task
Tau function
| #D | D | import std.stdio;
uint divisor_count(uint n) {
uint total = 1;
// Deal with powers of 2 first
for (; (n & 1) == 0; n >>= 1) {
++total;
}
// Odd prime factors up to the square root
for (uint p = 3; p * p <= n; p += 2) {
uint count = 1;
for (; n % p == 0; n /= p) {
++count;
}
total *= count;
}
// If n > 1 then it's prime
if (n > 1) {
total *= 2;
}
return total;
}
void main() {
immutable limit = 100;
writeln("The first ", limit, " tau numbers are:");
uint count = 0;
for (uint n = 1; count < limit; ++n) {
if (n % divisor_count(n) == 0) {
writef("%6d", n);
++count;
if (count % 10 == 0) {
writeln;
}
}
}
} |
http://rosettacode.org/wiki/Tarjan | Tarjan |
This page uses content from Wikipedia. The original article was at Graph. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Tarjan's algorithm is an algorithm in graph theory for finding the strongly connected components of a graph.
It runs in linear time, matching the time bound for alternative methods including Kosaraju's algorithm and the path-based strong component algorithm.
Tarjan's Algorithm is named for its discoverer, Robert Tarjan.
References
The article on Wikipedia.
| #C.2B.2B | C++ | //
// C++ implementation of Tarjan's strongly connected components algorithm
// See https://en.wikipedia.org/wiki/Tarjan%27s_strongly_connected_components_algorithm
//
#include <algorithm>
#include <iostream>
#include <list>
#include <string>
#include <vector>
struct noncopyable {
noncopyable() {}
noncopyable(const noncopyable&) = delete;
noncopyable& operator=(const noncopyable&) = delete;
};
template <typename T>
class tarjan;
template <typename T>
class vertex : private noncopyable {
public:
explicit vertex(const T& t) : data_(t) {}
void add_neighbour(vertex* v) {
neighbours_.push_back(v);
}
void add_neighbours(const std::initializer_list<vertex*>& vs) {
neighbours_.insert(neighbours_.end(), vs);
}
const T& get_data() {
return data_;
}
private:
friend tarjan<T>;
T data_;
int index_ = -1;
int lowlink_ = -1;
bool on_stack_ = false;
std::vector<vertex*> neighbours_;
};
template <typename T>
class graph : private noncopyable {
public:
vertex<T>* add_vertex(const T& t) {
vertexes_.emplace_back(t);
return &vertexes_.back();
}
private:
friend tarjan<T>;
std::list<vertex<T>> vertexes_;
};
template <typename T>
class tarjan : private noncopyable {
public:
using component = std::vector<vertex<T>*>;
std::list<component> run(graph<T>& graph) {
index_ = 0;
stack_.clear();
strongly_connected_.clear();
for (auto& v : graph.vertexes_) {
if (v.index_ == -1)
strongconnect(&v);
}
return strongly_connected_;
}
private:
void strongconnect(vertex<T>* v) {
v->index_ = index_;
v->lowlink_ = index_;
++index_;
stack_.push_back(v);
v->on_stack_ = true;
for (auto w : v->neighbours_) {
if (w->index_ == -1) {
strongconnect(w);
v->lowlink_ = std::min(v->lowlink_, w->lowlink_);
}
else if (w->on_stack_) {
v->lowlink_ = std::min(v->lowlink_, w->index_);
}
}
if (v->lowlink_ == v->index_) {
strongly_connected_.push_back(component());
component& c = strongly_connected_.back();
for (;;) {
auto w = stack_.back();
stack_.pop_back();
w->on_stack_ = false;
c.push_back(w);
if (w == v)
break;
}
}
}
int index_ = 0;
std::list<vertex<T>*> stack_;
std::list<component> strongly_connected_;
};
template <typename T>
void print_vector(const std::vector<vertex<T>*>& vec) {
if (!vec.empty()) {
auto i = vec.begin();
std::cout << (*i)->get_data();
for (++i; i != vec.end(); ++i)
std::cout << ' ' << (*i)->get_data();
}
std::cout << '\n';
}
int main() {
graph<std::string> g;
auto andy = g.add_vertex("Andy");
auto bart = g.add_vertex("Bart");
auto carl = g.add_vertex("Carl");
auto dave = g.add_vertex("Dave");
auto earl = g.add_vertex("Earl");
auto fred = g.add_vertex("Fred");
auto gary = g.add_vertex("Gary");
auto hank = g.add_vertex("Hank");
andy->add_neighbour(bart);
bart->add_neighbour(carl);
carl->add_neighbour(andy);
dave->add_neighbours({bart, carl, earl});
earl->add_neighbours({dave, fred});
fred->add_neighbours({carl, gary});
gary->add_neighbour(fred);
hank->add_neighbours({earl, gary, hank});
tarjan<std::string> t;
for (auto&& s : t.run(g))
print_vector(s);
return 0;
} |
http://rosettacode.org/wiki/Teacup_rim_text | Teacup rim text | On a set of coasters we have, there's a picture of a teacup. On the rim of the teacup the word TEA appears a number of times separated by bullet characters (•).
It occurred to me that if the bullet were removed and the words run together, you could start at any letter and still end up with a meaningful three-letter word.
So start at the T and read TEA. Start at the E and read EAT, or start at the A and read ATE.
That got me thinking that maybe there are other words that could be used rather that TEA. And that's just English. What about Italian or Greek or ... um ... Telugu.
For English, we will use the unixdict (now) located at: unixdict.txt.
(This will maintain continuity with other Rosetta Code tasks that also use it.)
Task
Search for a set of words that could be printed around the edge of a teacup. The words in each set are to be of the same length, that length being greater than two (thus precluding AH and HA, for example.)
Having listed a set, for example [ate tea eat], refrain from displaying permutations of that set, e.g.: [eat tea ate] etc.
The words should also be made of more than one letter (thus precluding III and OOO etc.)
The relationship between these words is (using ATE as an example) that the first letter of the first becomes the last letter of the second. The first letter of the second becomes the last letter of the third. So ATE becomes TEA and TEA becomes EAT.
All of the possible permutations, using this particular permutation technique, must be words in the list.
The set you generate for ATE will never included the word ETA as that cannot be reached via the first-to-last movement method.
Display one line for each set of teacup rim words.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #J | J |
read=: CR -.~ 1!:1@boxopen NB. dang that line end!
Filter=:(#~`)(`:6)
prep=: (;~ /:~);._2
gba=: <@:([: ,/ (>@}."1))/.~ 0&{"1
ew=: (>:&# {.)S:_1 Filter
le=: (2 < #@{.)S:_1 Filter
ra=: a: -.~ rotations&>
NB. prep was separated for fun, not necessity
teacup=: ra@:le@:ew@:gba
rotations=: 3 :0
subset=: 0 = #@:-.
assert. 0 1 -: 'ab'(subset~ , subset)'cabag'
N=. # {. y
for_word. y do.
a=. N ]\ (, (<: N)&{.) word
if. a subset y do. word return. end.
end.
''
)
|
http://rosettacode.org/wiki/Teacup_rim_text | Teacup rim text | On a set of coasters we have, there's a picture of a teacup. On the rim of the teacup the word TEA appears a number of times separated by bullet characters (•).
It occurred to me that if the bullet were removed and the words run together, you could start at any letter and still end up with a meaningful three-letter word.
So start at the T and read TEA. Start at the E and read EAT, or start at the A and read ATE.
That got me thinking that maybe there are other words that could be used rather that TEA. And that's just English. What about Italian or Greek or ... um ... Telugu.
For English, we will use the unixdict (now) located at: unixdict.txt.
(This will maintain continuity with other Rosetta Code tasks that also use it.)
Task
Search for a set of words that could be printed around the edge of a teacup. The words in each set are to be of the same length, that length being greater than two (thus precluding AH and HA, for example.)
Having listed a set, for example [ate tea eat], refrain from displaying permutations of that set, e.g.: [eat tea ate] etc.
The words should also be made of more than one letter (thus precluding III and OOO etc.)
The relationship between these words is (using ATE as an example) that the first letter of the first becomes the last letter of the second. The first letter of the second becomes the last letter of the third. So ATE becomes TEA and TEA becomes EAT.
All of the possible permutations, using this particular permutation technique, must be words in the list.
The set you generate for ATE will never included the word ETA as that cannot be reached via the first-to-last movement method.
Display one line for each set of teacup rim words.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Java | Java | import java.io.*;
import java.util.*;
public class Teacup {
public static void main(String[] args) {
if (args.length != 1) {
System.err.println("usage: java Teacup dictionary");
System.exit(1);
}
try {
findTeacupWords(loadDictionary(args[0]));
} catch (Exception ex) {
System.err.println(ex.getMessage());
}
}
// The file is expected to contain one lowercase word per line
private static Set<String> loadDictionary(String fileName) throws IOException {
Set<String> words = new TreeSet<>();
try (BufferedReader reader = new BufferedReader(new FileReader(fileName))) {
String word;
while ((word = reader.readLine()) != null)
words.add(word);
return words;
}
}
private static void findTeacupWords(Set<String> words) {
List<String> teacupWords = new ArrayList<>();
Set<String> found = new HashSet<>();
for (String word : words) {
int len = word.length();
if (len < 3 || found.contains(word))
continue;
teacupWords.clear();
teacupWords.add(word);
char[] chars = word.toCharArray();
for (int i = 0; i < len - 1; ++i) {
String rotated = new String(rotate(chars));
if (rotated.equals(word) || !words.contains(rotated))
break;
teacupWords.add(rotated);
}
if (teacupWords.size() == len) {
found.addAll(teacupWords);
System.out.print(word);
for (int i = 1; i < len; ++i)
System.out.print(" " + teacupWords.get(i));
System.out.println();
}
}
}
private static char[] rotate(char[] ch) {
char c = ch[0];
System.arraycopy(ch, 1, ch, 0, ch.length - 1);
ch[ch.length - 1] = c;
return ch;
}
} |
http://rosettacode.org/wiki/Temperature_conversion | Temperature conversion | There are quite a number of temperature scales. For this task we will concentrate on four of the perhaps best-known ones:
Kelvin, Celsius, Fahrenheit, and Rankine.
The Celsius and Kelvin scales have the same magnitude, but different null points.
0 degrees Celsius corresponds to 273.15 kelvin.
0 kelvin is absolute zero.
The Fahrenheit and Rankine scales also have the same magnitude, but different null points.
0 degrees Fahrenheit corresponds to 459.67 degrees Rankine.
0 degrees Rankine is absolute zero.
The Celsius/Kelvin and Fahrenheit/Rankine scales have a ratio of 5 : 9.
Task
Write code that accepts a value of kelvin, converts it to values of the three other scales, and prints the result.
Example
K 21.00
C -252.15
F -421.87
R 37.80
| #Aime | Aime | void
show(integer symbol, real temperature)
{
o_form("%c /d2p2w8/\n", symbol, temperature);
}
integer
main(void)
{
real k;
k = atof(argv(1));
show('K', k);
show('C', k - 273.15);
show('F', k * 1.8 - 459.67);
show('R', k * 1.8);
return 0;
} |
http://rosettacode.org/wiki/Tau_function | Tau function | Given a positive integer, count the number of its positive divisors.
Task
Show the result for the first 100 positive integers.
Related task
Tau number
| #Arturo | Arturo | tau: function [x] -> size factors x
loop split.every:20 1..100 => [
print map & => [pad to :string tau & 3]
] |
http://rosettacode.org/wiki/Tau_function | Tau function | Given a positive integer, count the number of its positive divisors.
Task
Show the result for the first 100 positive integers.
Related task
Tau number
| #AWK | AWK |
# syntax: GAWK -f TAU_FUNCTION.AWK
BEGIN {
print("The tau functions for the first 100 positive integers:")
for (i=1; i<=100; i++) {
printf("%2d ",count_divisors(i))
if (i % 10 == 0) {
printf("\n")
}
}
exit(0)
}
function count_divisors(n, count,i) {
for (i=1; i*i<=n; i++) {
if (n % i == 0) {
count += (i == n / i) ? 1 : 2
}
}
return(count)
}
|
http://rosettacode.org/wiki/Terminal_control/Clear_the_screen | Terminal control/Clear the screen | Task
Clear the terminal window.
| #C_.2F_C.2B.2B | C / C++ | void cls(void) {
printf("\33[2J");
} |
http://rosettacode.org/wiki/Terminal_control/Clear_the_screen | Terminal control/Clear the screen | Task
Clear the terminal window.
| #C.23 | C# | System.Console.Clear(); |
http://rosettacode.org/wiki/Terminal_control/Clear_the_screen | Terminal control/Clear the screen | Task
Clear the terminal window.
| #COBOL | COBOL | PROGRAM-ID. blank-terminal.
DATA DIVISION.
SCREEN SECTION.
01 blank-screen BLANK SCREEN.
PROCEDURE DIVISION.
DISPLAY blank-screen
GOBACK
. |
http://rosettacode.org/wiki/Ternary_logic | Ternary logic |
This page uses content from Wikipedia. The original article was at Ternary logic. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
In logic, a three-valued logic (also trivalent, ternary, or trinary logic, sometimes abbreviated 3VL) is any of several many-valued logic systems in which there are three truth values indicating true, false and some indeterminate third value.
This is contrasted with the more commonly known bivalent logics (such as classical sentential or boolean logic) which provide only for true and false.
Conceptual form and basic ideas were initially created by Łukasiewicz, Lewis and Sulski.
These were then re-formulated by Grigore Moisil in an axiomatic algebraic form, and also extended to n-valued logics in 1945.
Example Ternary Logic Operators in Truth Tables:
not a
¬
True
False
Maybe
Maybe
False
True
a and b
∧
True
Maybe
False
True
True
Maybe
False
Maybe
Maybe
Maybe
False
False
False
False
False
a or b
∨
True
Maybe
False
True
True
True
True
Maybe
True
Maybe
Maybe
False
True
Maybe
False
if a then b
⊃
True
Maybe
False
True
True
Maybe
False
Maybe
True
Maybe
Maybe
False
True
True
True
a is equivalent to b
≡
True
Maybe
False
True
True
Maybe
False
Maybe
Maybe
Maybe
Maybe
False
False
Maybe
True
Task
Define a new type that emulates ternary logic by storing data trits.
Given all the binary logic operators of the original programming language, reimplement these operators for the new Ternary logic type trit.
Generate a sampling of results using trit variables.
Kudos for actually thinking up a test case algorithm where ternary logic is intrinsically useful, optimises the test case algorithm and is preferable to binary logic.
Note: Setun (Сетунь) was a balanced ternary computer developed in 1958 at Moscow State University. The device was built under the lead of Sergei Sobolev and Nikolay Brusentsov. It was the only modern ternary computer, using three-valued ternary logic
| #FreeBASIC | FreeBASIC | enum trit
F=-1, M=0, T=1
end enum
dim as string symbol(-1 to 1) = {"F", "?", "T"}, outstr
dim as trit i
operator not ( x as trit ) as trit
return -x
end operator
operator and (x as trit, y as trit) as trit
if x>y then return y and x
return x
end operator
operator or ( x as trit, y as trit ) as trit
if x<y then return y or x
return x
end operator
operator eqv ( x as trit, y as trit ) as trit
return x*y
end operator
operator imp ( x as trit, y as trit ) as trit
if -y>x then return -y
return x
end operator
print " (AND) ( OR) (EQV) (IMP) (NOT)"
print " F ? T F ? T F ? T F ? T "
print " -------------------------------------------------"
for i = F to T
outstr = " "+symbol(i)+" | "
outstr += symbol(F and i) + " " + symbol(M and i) + " " + symbol(T and i)
outstr += " "
outstr += symbol(F or i) + " " + symbol(M or i) + " " + symbol(T or i)
outstr += " "
outstr += symbol(F eqv i) + " " + symbol(M eqv i) + " " + symbol(T eqv i)
outstr += " "
outstr += symbol(F imp i) + " " + symbol(M imp i) + " " + symbol(T imp i)
outstr += " " + symbol(not(i))
print outstr
next i |
http://rosettacode.org/wiki/Text_processing/1 | Text processing/1 | This task has been flagged for clarification. Code on this page in its current state may be flagged incorrect once this task has been clarified. See this page's Talk page for discussion.
Often data is produced by one program, in the wrong format for later use by another program or person. In these situations another program can be written to parse and transform the original data into a format useful to the other. The term "Data Munging" is often used in programming circles for this task.
A request on the comp.lang.awk newsgroup led to a typical data munging task:
I have to analyse data files that have the following format:
Each row corresponds to 1 day and the field logic is: $1 is the date,
followed by 24 value/flag pairs, representing measurements at 01:00,
02:00 ... 24:00 of the respective day. In short:
<date> <val1> <flag1> <val2> <flag2> ... <val24> <flag24>
Some test data is available at:
... (nolonger available at original location)
I have to sum up the values (per day and only valid data, i.e. with
flag>0) in order to calculate the mean. That's not too difficult.
However, I also need to know what the "maximum data gap" is, i.e. the
longest period with successive invalid measurements (i.e values with
flag<=0)
The data is free to download and use and is of this format:
Data is no longer available at that link. Zipped mirror available here (offsite mirror).
1991-03-30 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1
1991-03-31 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 20.000 1 20.000 1 20.000 1 35.000 1 50.000 1 60.000 1 40.000 1 30.000 1 30.000 1 30.000 1 25.000 1 20.000 1 20.000 1 20.000 1 20.000 1 20.000 1 35.000 1
1991-03-31 40.000 1 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2
1991-04-01 0.000 -2 13.000 1 16.000 1 21.000 1 24.000 1 22.000 1 20.000 1 18.000 1 29.000 1 44.000 1 50.000 1 43.000 1 38.000 1 27.000 1 27.000 1 24.000 1 23.000 1 18.000 1 12.000 1 13.000 1 14.000 1 15.000 1 13.000 1 10.000 1
1991-04-02 8.000 1 9.000 1 11.000 1 12.000 1 12.000 1 12.000 1 27.000 1 26.000 1 27.000 1 33.000 1 32.000 1 31.000 1 29.000 1 31.000 1 25.000 1 25.000 1 24.000 1 21.000 1 17.000 1 14.000 1 15.000 1 12.000 1 12.000 1 10.000 1
1991-04-03 10.000 1 9.000 1 10.000 1 10.000 1 9.000 1 10.000 1 15.000 1 24.000 1 28.000 1 24.000 1 18.000 1 14.000 1 12.000 1 13.000 1 14.000 1 15.000 1 14.000 1 15.000 1 13.000 1 13.000 1 13.000 1 12.000 1 10.000 1 10.000 1
Only a sample of the data showing its format is given above. The full example file may be downloaded here.
Structure your program to show statistics for each line of the file, (similar to the original Python, Perl, and AWK examples below), followed by summary statistics for the file. When showing example output just show a few line statistics and the full end summary.
| #Java | Java | import java.io.File;
import java.util.*;
import static java.lang.System.out;
public class TextProcessing1 {
public static void main(String[] args) throws Exception {
Locale.setDefault(new Locale("en", "US"));
Metrics metrics = new Metrics();
int dataGap = 0;
String gapBeginDate = null;
try (Scanner lines = new Scanner(new File("readings.txt"))) {
while (lines.hasNextLine()) {
double lineTotal = 0.0;
int linePairs = 0;
int lineInvalid = 0;
String lineDate;
try (Scanner line = new Scanner(lines.nextLine())) {
lineDate = line.next();
while (line.hasNext()) {
final double value = line.nextDouble();
if (line.nextInt() <= 0) {
if (dataGap == 0)
gapBeginDate = lineDate;
dataGap++;
lineInvalid++;
continue;
}
lineTotal += value;
linePairs++;
metrics.addDataGap(dataGap, gapBeginDate, lineDate);
dataGap = 0;
}
}
metrics.addLine(lineTotal, linePairs);
metrics.lineResult(lineDate, lineInvalid, linePairs, lineTotal);
}
metrics.report();
}
}
private static class Metrics {
private List<String[]> gapDates;
private int maxDataGap = -1;
private double total;
private int pairs;
private int lineResultCount;
void addLine(double tot, double prs) {
total += tot;
pairs += prs;
}
void addDataGap(int gap, String begin, String end) {
if (gap > 0 && gap >= maxDataGap) {
if (gap > maxDataGap) {
maxDataGap = gap;
gapDates = new ArrayList<>();
}
gapDates.add(new String[]{begin, end});
}
}
void lineResult(String date, int invalid, int prs, double tot) {
if (lineResultCount >= 3)
return;
out.printf("%10s out: %2d in: %2d tot: %10.3f avg: %10.3f%n",
date, invalid, prs, tot, (prs > 0) ? tot / prs : 0.0);
lineResultCount++;
}
void report() {
out.printf("%ntotal = %10.3f%n", total);
out.printf("readings = %6d%n", pairs);
out.printf("average = %010.3f%n", total / pairs);
out.printf("%nmaximum run(s) of %d invalid measurements: %n",
maxDataGap);
for (String[] dates : gapDates)
out.printf("begins at %s and ends at %s%n", dates[0], dates[1]);
}
}
} |
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.
| #Tcl | Tcl | package require Tcl 8.6
oo::class create ISAAC {
variable aa bb cc mm randrsl randcnt
constructor {seed} {
namespace eval tcl {
namespace eval mathfunc {
proc mm {idx} {
upvar 1 mm list
lindex $list [expr {$idx % [llength $list]}]
}
proc clamp {value} {
expr {$value & 0xFFFFFFFF}
}
}
}
proc mix1 {i v} {
upvar 1 a a
lset a $i [expr {clamp([lindex $a $i] ^ $v)}]
lset a [set idx [expr {($i+3)%8}]] \
[expr {clamp([lindex $a $idx] + [lindex $a $i])}]
lset a [set idx [expr {($i+1)%8}]] \
[expr {clamp([lindex $a $idx] + [lindex $a [expr {($i+2)%8}]])}]
}
binary scan $seed[string repeat \u0000 256] c256 randrsl
set mm [lrepeat 256 0]
set randcnt [set aa [set bb [set cc 0]]]
set a [lrepeat 8 0x9e3779b9]
foreach i {1 2 3 4} {
mix1 0 [expr {[lindex $a 1] << 11}]
mix1 1 [expr {[lindex $a 2] >> 2}]
mix1 2 [expr {[lindex $a 3] << 8}]
mix1 3 [expr {[lindex $a 4] >> 16}]
mix1 4 [expr {[lindex $a 5] << 10}]
mix1 5 [expr {[lindex $a 6] >> 4}]
mix1 6 [expr {[lindex $a 7] << 8}]
mix1 7 [expr {[lindex $a 0] >> 9}]
}
for {set i 0} {$i < 256} {incr i 8} {
set a [lmap av $a bv [lrange $randrsl $i [expr {$i+7}]] {
expr {clamp($av + $bv)}
}]
mix1 0 [expr {[lindex $a 1] << 11}]
mix1 1 [expr {[lindex $a 2] >> 2}]
mix1 2 [expr {[lindex $a 3] << 8}]
mix1 3 [expr {[lindex $a 4] >> 16}]
mix1 4 [expr {[lindex $a 5] << 10}]
mix1 5 [expr {[lindex $a 6] >> 4}]
mix1 6 [expr {[lindex $a 7] << 8}]
mix1 7 [expr {[lindex $a 0] >> 9}]
for {set j 0} {$j < 8} {incr j} {
lset mm [expr {$i+$j}] [lindex $a $j]
}
}
for {set i 0} {$i < 256} {incr i 8} {
set a [lmap av $a bv [lrange $mm $i [expr {$i+7}]] {
expr {clamp($av + $bv)}
}]
mix1 0 [expr {[lindex $a 1] << 11}]
mix1 1 [expr {[lindex $a 2] >> 2}]
mix1 2 [expr {[lindex $a 3] << 8}]
mix1 3 [expr {[lindex $a 4] >> 16}]
mix1 4 [expr {[lindex $a 5] << 10}]
mix1 5 [expr {[lindex $a 6] >> 4}]
mix1 6 [expr {[lindex $a 7] << 8}]
mix1 7 [expr {[lindex $a 0] >> 9}]
for {set j 0} {$j < 8} {incr j} {
lset mm [expr {$i+$j}] [lindex $a $j]
}
}
my Step
}
method Step {} {
incr bb [incr cc]
set i -1
foreach x $mm {
set shift [lindex {13 -6 2 -16} [expr {[incr i] % 4}]]
set aa [expr {$aa ^ ($shift>0 ? $aa<<$shift : $aa>>-$shift)}]
set aa [expr {clamp($aa + mm($i+128))}]
set y [expr {clamp(mm($x>>2) + $aa + $bb)}]
lset mm $i $y
set bb [expr {clamp(mm($y>>10) + $x)}]
lset randrsl $i $bb
}
}
method random {} {
set r [lindex $randrsl $randcnt]
if {[incr randcnt] == 256} {
my Step
set randcnt 0
}
return $r
}
method RandA {} {
expr {([my random] % 95) + 32}
}
method vernam {msg} {
binary scan $msg c* b
for {set i 0} {$i < [llength $b]} {incr i} {
lset b $i [expr {[lindex $b $i] & 255 ^ [my RandA]}]
}
return [binary encode hex [binary format c* $b]]
}
} |
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).
| #TUSCRIPT | TUSCRIPT |
$$ MODE TUSCRIPT
joblog="mlijobs.txt",jobnrout=0
log=FILE (joblog)
DICT jobnrout CREATE
LOOP l=log
jobout=EXTRACT (l,":License :"|,": :")
IF (jobout=="out") THEN
time=EXTRACT (l,":@ :"|,": :"), jobnrout=jobnrout+1
DICT jobnrout APPEND/QUIET jobnrout,num,cnt,time;" "
ELSE
jobnrout=jobnrout-1
ENDIF
ENDLOOP
DICT jobnrout UNLOAD jobnrout,num,cnt,time
DICT jobnrout SIZE maxlicout
times=SELECT (time,#maxlicout)
PRINT "The max. number of licences out is ", maxlicout
PRINT "at these times: ", times
|
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).
| #TXR | TXR |
@(bind *times* #H((:eql-based) nil))
@(bind *licenses-out* 0)
@(bind *maximum-licenses-out* 0)
@(collect)
License @statuses @@ @dateTimes for job @jobNumbers
@(end)
@(do (each ((status statuses)
(dateTime dateTimes)
(jobNumber jobNumbers))
(set *licenses-out*
(if (equal status "OUT")
(progn
(when (>= (+ *licenses-out* 1) *maximum-licenses-out*)
(set *maximum-licenses-out* (+ *licenses-out* 1))
(pushhash *times* *maximum-licenses-out* dateTime))
(+ *licenses-out* 1))
(+ *licenses-out* -1)))))
@(output)
Maximum # of licenses out: @{*maximum-licenses-out*}
Peak time(s): @{(reverse (gethash *times* *maximum-licenses-out*))}
@(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.
| #REXX | REXX | /*REXX program stresses various REXX functions (BIFs), many BIFs are used as variables. */
signal=(interpret=value); value=(interpret<parse); do upper=value to value; end
exit=upper*upper*upper*upper-value-upper; say=' '; return=say say say; with.=signal
do then=value to exit; pull=''; do otherwise= upper to then-,
value; select=otherwise-value; if.otherwise=with.otherwise+with.select; end
if.value=value; if.then=value; do otherwise=value to exit-then; pull=pull,
say''say; end; do otherwise=value to then; pull=pull center(if.otherwise,,
length(return)); end; say pull; do otherwise=value to exit; with.otherwise=,
if.otherwise; end; end; exit 0 /*stick a fork in it, we're all done. */ |
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.
| #Ring | Ring |
assert(IsPalindrome("racecar"))
assert(IsPalindrome("alice"))
|
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
| #F.23 | F# | let gifts = [
"And a partridge in a pear tree";
"Two turtle doves";
"Three french hens";
"Four calling birds";
"FIVE GOLDEN RINGS";
"Six geese a-laying";
"Seven swans a-swimming";
"Eight maids a-milking";
"Nine ladies dancing";
"Ten lords a-leaping";
"Eleven pipers piping";
"Twelve drummers drumming"
]
let days = [
"first"; "second"; "third"; "fourth"; "fifth"; "sixth"; "seventh"; "eighth";
"ninth"; "tenth"; "eleventh"; "twelfth"
]
let displayGifts day =
printfn "On the %s day of Christmas, my true love gave to me" days.[day]
if day = 0 then
printfn "A partridge in a pear tree"
else
List.iter (fun i -> printfn "%s" gifts.[i]) [day..(-1)..0]
printf "\n"
List.iter displayGifts [0..11] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.