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/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)
| #GW-BASIC | GW-BASIC | 10 FOR I = 0 TO 31
20 COLOR I, 7 - (I MOD 8)
30 PRINT I;
40 IF I MOD 4 = 3 THEN COLOR 7, 0 : PRINT
50 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)
| #Haskell | Haskell | #!/usr/bin/runhaskell
import System.Console.ANSI
colorStrLn :: ColorIntensity -> Color -> ColorIntensity -> Color -> String -> IO ()
colorStrLn fgi fg bgi bg str = do
setSGR [SetColor Foreground fgi fg, SetColor Background bgi bg]
putStr str
setSGR []
putStrLn ""
main = do
colorStrLn Vivid White Vivid Red "This is red on white."
colorStrLn Vivid White Dull Blue "This is white on blue."
colorStrLn Vivid Green Dull Black "This is green on black."
colorStrLn Vivid Yellow Dull Black "This is yellow on black."
colorStrLn Dull Black Vivid Blue "This is black on light blue." |
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.
| #Scala | Scala | object CursorMovement extends App {
val ESC = "\u001B" // escape code
print(s"$ESC[2J$ESC[10;10H") // clear terminal first, move cursor to (10, 10) say
val aecs = Seq(
"[1D", // left
"[1C", // right
"[1A", // up
"[1B", // down
"[9D", // line start
"[H", // top left
"[24;79H" // bottom right - assuming 80 x 24 terminal
)
for (aec <- aecs) {
Thread.sleep(3000) // three second display between cursor movements
print(s"$ESC$aec")
}
} |
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.
| #Tcl | Tcl | # Simplification wrapper for when we're actually affecting the terminal
proc tput args {
exec tput {*}$args >@stdout <@stdin
}
tput cub1; # one position to the left
tput cuf1; # one position to the right
tput cuu1; # up one line
tput cud1; # down one line
tput cr; # beginning of line
tput home; # top left corner
# For line ends and bottom, we need to determine size of terminal
set width [exec tput cols]
set height [exec tput lines]
tput hpa $width; # end of line
tput cpu $height $width; # 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.
| #UNIX_Shell | UNIX Shell | tput cub1 # one position to the left
tput cuf1 # one position to the right
tput cuu1 # up one line
tput cud1 # down one line
tput cr # beginning of line
tput home # top left corner
# For line ends and bottom, we need to determine size
# of terminal
WIDTH=`tput cols`
HEIGHT=`tput lines`
tput hpa $WIDTH # end of line
tput cup $HEIGHT $WIDTH # bottom right corner |
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.
| #Apache_Derby | Apache Derby | CREATE TABLE Address (
addrID INTEGER PRIMARY KEY generated BY DEFAULT AS IDENTITY,
addrStreet VARCHAR(50) NOT NULL,
addrCity VARCHAR(50) NOT NULL,
addrState CHAR(2) NOT NULL,
addrZip CHAR(10) NOT NULL
);
|
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.
| #Arturo | Arturo | db: open.sqlite "addresses.db"
query db {!sql
CREATE TABLE address (
addrID INTEGER PRIMARY KEY AUTOINCREMENT,
addrStreet TEXT NOT NULL,
addrCity TEXT NOT NULL,
addrState TEXT NOT NULL,
addrZIP TEXT NOT NULL
)
}
close db |
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.
| #Aime | Aime | #! /usr/local/bin/aime -a
if (argc() == 1) {
file f;
text s;
f.affix("NOTES.TXT");
while (~f.line(s)) {
o_(s, "\n");
}
} else {
date d;
file f;
f.open("NOTES.TXT", OPEN_APPEND | OPEN_CREATE | OPEN_WRITEONLY, 0644);
d.now;
f.form("/f4/-/f2/-/f2/ /f2/:/f2/:/f2/\n", d.year, d.y_month,
d.m_day, d.d_hour, d.h_minute, d.m_second);
for (integer i, text s in 1.args) {
f.bytes(i ? ' ' : '\t', s);
}
f.byte('\n');
} |
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.
| #APL | APL | #!/usr/local/bin/apl -s --
∇r←ch Join ls ⍝ Join list of strings with character
r←1↓∊ch,¨ls
∇
∇d←Date ⍝ Get system date as formatted string
d←'/'Join ⍕¨1⌽3↑⎕TS
∇
∇t←Time;t24 ⍝ Get system time as formatted string
t←t24←3↑3↓⎕TS ⍝ Get system time
t[1]←t[1]-12×t24[1]≥12 ⍝ If PM (hour≥12), subtract 12 from hour
t[1]←t[1]+12×t[1]=0 ⍝ Hour 0 is hour 12 (AM)
t←¯2↑¨'0',¨⍕¨t ⍝ Convert numbers to 2-digit strings
t←(':'Join t),(1+t24[1]≥12)⊃' AM' ' PM' ⍝ Add AM/PM and ':' separator
∇
∇Read;f
→(¯2≡f←⎕FIO[49]'notes.txt')/0 ⍝ Read file, stop if not found
⎕←⊃f ⍝ Output file line by line
∇
∇Write note;f;_
note←' 'Join note ⍝ flatten input and separate with spaces
note←Date,' ',Time,(⎕UCS 10 9),note,⎕UCS 10 ⍝ note format
f←'a'⎕FIO[3]'notes.txt' ⍝ append to file
_←(⎕UCS note)⎕FIO[7]f ⍝ write note to end of file
_←⎕FIO[4]f ⍝ close the file
∇
∇Notes;note
⍎∊('Read' 'Write note')[1+0≠⍴note←4↓⎕ARG]
∇
Notes
)OFF |
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).
| #Clojure | Clojure | (ns test-project-intellij.core
(:gen-class))
(defn cube [x]
"Cube a number through triple multiplication"
(* x x x))
(defn sum3 [[i j]]
" [i j] -> i^3 + j^3"
(+ (cube i) (cube j)))
(defn next-pair [[i j]]
" Generate next [i j] pair of sequence (producing lower triangle pairs) "
(if (< j i)
[i (inc j)]
[(inc i) 1]))
;; Pair sequence generator [1 1] [2 1] [2 2] [3 1] [3 2] [3 3] ...
(def pairs-seq (iterate next-pair [1 1]))
(defn dict-inc [m pair]
" Add pair to pair map m, with the key of the map based upon the cubic sum (sum3) and the value appends the pair "
(update-in m [(sum3 pair)] (fnil #(conj % pair) [])))
(defn enough? [m n-to-generate]
" Checks if we have enough taxi numbers (i.e. if number in map >= count-needed "
(->> m ; hash-map of sum of cube of numbers [key] and their pairs as value
(filter #(if (> (count (second %)) 1) true false)) ; filter out ones which don't have more than 1 entry
(count) ; count the item remaining
(<= n-to-generate))) ; true iff count-needed is less or equal to the nubmer filtered
(defn find-taxi-numbers [n-to-generate]
" Generates 1st n-to-generate taxi numbers"
(loop [m {} ; Hash-map containing cube of pairs (key) and set of pairs that produce sum (value)
p pairs-seq ; select pairs from our pair sequence generator (i.e. [1 1] [2 1] [2 2] ...)
num-tried 0 ; Since its expensve to count how many taxi numbers we have found
check-after 1] ; we only check if we have enough numbers every time (num-tried equals check-after)
; num-tried increments by 1 each time we try the next pair and
; check-after doubles if we don't have enough taxi numbers
(if (and (= num-tried check-after) (enough? m n-to-generate)) ; check if we found enough taxi numbers
(sort-by first (into [] (filter #(> (count (second %)) 1) m))) ; sort the taxi numbers and this is the result
(if (= num-tried check-after) ; Check if we need to increase our count between checking
(recur (dict-inc m (first p)) (rest p) (inc num-tried) (* 2 check-after)) ; increased count between checking
(recur (dict-inc m (first p)) (rest p) (inc num-tried) check-after))))) ; didn't increase the count
; Generate 1st 2006 taxi numbers
(def result (find-taxi-numbers 2006))
;; Show First 25
(defn show-result [n sample]
" Prints one line of result "
(print (format "%4d:%10d" n (first sample)))
(doseq [q (second sample)
:let [[i j] q]]
(print (format " = %4d^3 + %4d^3" i j)))
(println))
; 1st 25 taxi numbers
(doseq [n (range 1 26)
:let [sample (nth result (dec n))]]
(show-result n sample))
; taxi numbers from 2000th to 2006th
(doseq [n (range 2000 2007)
:let [sample (nth result (dec n))]]
(show-result n sample))
} |
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
| #Delphi | Delphi |
program Tau_number;
{$APPTYPE CONSOLE}
uses
System.SysUtils;
function CountDivisors(n: Integer): Integer;
begin
Result := 0;
var i := 1;
var k := 2;
if (n mod 2) = 0 then
k := 1;
while i * i <= n do
begin
if (n mod i) = 0 then
begin
inc(Result);
var j := n div i;
if j <> i then
inc(Result);
end;
inc(i, k);
end;
end;
begin
Writeln('The first 100 tau numbers are:');
var count := 0;
var i := 1;
while count < 100 do
begin
var tf := CountDivisors(i);
if i mod tf = 0 then
begin
write(format('%4d ', [i]));
inc(count);
if count mod 10 = 0 then
writeln;
end;
inc(i);
end;
{$IFNDEF UNIX} readln; {$ENDIF}
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
| #Draco | Draco | /* Generate a table of the amount of divisors for each number */
proc nonrec div_count([*]word divs) void:
word max, i, j;
max := dim(divs,1)-1;
divs[0] := 0;
for i from 1 upto max do divs[i] := 1 od;
for i from 2 upto max do
for j from i by i upto max do
divs[j] := divs[j] + 1
od
od
corp
/* Find Tau numbers */
proc nonrec main() void:
[1100]word divs;
word n, seen;
div_count(divs);
seen := 0;
n := 0;
while n := n + 1; seen < 100 do
if n % divs[n] = 0 then
seen := seen + 1;
write(n:5);
if seen % 10 = 0 then writeln() fi
fi
od
corp |
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.
| #Go | Go | package main
import (
"fmt"
"math/big"
)
// (same data as zkl example)
var g = [][]int{
0: {1},
2: {0},
5: {2, 6},
6: {5},
1: {2},
3: {1, 2, 4},
4: {5, 3},
7: {4, 7, 6},
}
func main() {
tarjan(g, func(c []int) { fmt.Println(c) })
}
// the function calls the emit argument for each component identified.
// each component is a list of nodes.
func tarjan(g [][]int, emit func([]int)) {
var indexed, stacked big.Int
index := make([]int, len(g))
lowlink := make([]int, len(g))
x := 0
var S []int
var sc func(int) bool
sc = func(n int) bool {
index[n] = x
indexed.SetBit(&indexed, n, 1)
lowlink[n] = x
x++
S = append(S, n)
stacked.SetBit(&stacked, n, 1)
for _, nb := range g[n] {
if indexed.Bit(nb) == 0 {
if !sc(nb) {
return false
}
if lowlink[nb] < lowlink[n] {
lowlink[n] = lowlink[nb]
}
} else if stacked.Bit(nb) == 1 {
if index[nb] < lowlink[n] {
lowlink[n] = index[nb]
}
}
}
if lowlink[n] == index[n] {
var c []int
for {
last := len(S) - 1
w := S[last]
S = S[:last]
stacked.SetBit(&stacked, w, 0)
c = append(c, w)
if w == n {
emit(c)
break
}
}
}
return true
}
for n := range g {
if indexed.Bit(n) == 0 && !sc(n) {
return
}
}
} |
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
| #JavaScript | JavaScript | (() => {
'use strict';
// main :: IO ()
const main = () =>
showGroups(
circularWords(
// Local copy of:
// https://www.mit.edu/~ecprice/wordlist.10000
lines(readFile('~/mitWords.txt'))
)
);
// circularWords :: [String] -> [String]
const circularWords = ws =>
ws.filter(isCircular(new Set(ws)), ws);
// isCircular :: Set String -> String -> Bool
const isCircular = lexicon => w => {
const iLast = w.length - 1;
return 1 < iLast && until(
([i, bln, s]) => iLast < i || !bln,
([i, bln, s]) => [1 + i, lexicon.has(s), rotated(s)],
[0, true, rotated(w)]
)[1];
};
// DISPLAY --------------------------------------------
// showGroups :: [String] -> String
const showGroups = xs =>
unlines(map(
gp => map(snd, gp).join(' -> '),
groupBy(
(a, b) => fst(a) === fst(b),
sortBy(
comparing(fst),
map(x => Tuple(concat(sort(chars(x))), x),
xs
)
)
).filter(gp => 1 < gp.length)
));
// MAC OS JS FOR AUTOMATION ---------------------------
// readFile :: FilePath -> IO String
const readFile = fp => {
const
e = $(),
uw = ObjC.unwrap,
s = uw(
$.NSString.stringWithContentsOfFileEncodingError(
$(fp)
.stringByStandardizingPath,
$.NSUTF8StringEncoding,
e
)
);
return undefined !== s ? (
s
) : uw(e.localizedDescription);
};
// GENERIC FUNCTIONS ----------------------------------
// Tuple (,) :: a -> b -> (a, b)
const Tuple = (a, b) => ({
type: 'Tuple',
'0': a,
'1': b,
length: 2
});
// chars :: String -> [Char]
const chars = s => s.split('');
// comparing :: (a -> b) -> (a -> a -> Ordering)
const comparing = f =>
(x, y) => {
const
a = f(x),
b = f(y);
return a < b ? -1 : (a > b ? 1 : 0);
};
// concat :: [[a]] -> [a]
// concat :: [String] -> String
const concat = xs =>
0 < xs.length ? (() => {
const unit = 'string' !== typeof xs[0] ? (
[]
) : '';
return unit.concat.apply(unit, xs);
})() : [];
// fst :: (a, b) -> a
const fst = tpl => tpl[0];
// groupBy :: (a -> a -> Bool) -> [a] -> [[a]]
const groupBy = (f, xs) => {
const tpl = xs.slice(1)
.reduce((a, x) => {
const h = a[1].length > 0 ? a[1][0] : undefined;
return (undefined !== h) && f(h, x) ? (
Tuple(a[0], a[1].concat([x]))
) : Tuple(a[0].concat([a[1]]), [x]);
}, Tuple([], 0 < xs.length ? [xs[0]] : []));
return tpl[0].concat([tpl[1]]);
};
// lines :: String -> [String]
const lines = s => s.split(/[\r\n]/);
// map :: (a -> b) -> [a] -> [b]
const map = (f, xs) =>
(Array.isArray(xs) ? (
xs
) : xs.split('')).map(f);
// rotated :: String -> String
const rotated = xs =>
xs.slice(1) + xs[0];
// showLog :: a -> IO ()
const showLog = (...args) =>
console.log(
args
.map(JSON.stringify)
.join(' -> ')
);
// snd :: (a, b) -> b
const snd = tpl => tpl[1];
// sort :: Ord a => [a] -> [a]
const sort = xs => xs.slice()
.sort((a, b) => a < b ? -1 : (a > b ? 1 : 0));
// sortBy :: (a -> a -> Ordering) -> [a] -> [a]
const sortBy = (f, xs) =>
xs.slice()
.sort(f);
// unlines :: [String] -> String
const unlines = xs => xs.join('\n');
// until :: (a -> Bool) -> (a -> a) -> a -> a
const until = (p, f, x) => {
let v = x;
while (!p(v)) v = f(v);
return v;
};
// MAIN ---
return main();
})(); |
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
| #ALGOL_68 | ALGOL 68 |
BEGIN
REAL kelvin;
read (kelvin);
FORMAT f = $g(8,2), " K = ", g(8,2)xgl$;
printf ((f, kelvin, kelvin - 273.15, "C"));
printf ((f, kelvin, 9.0 * kelvin / 5.0, "R"));
printf ((f, kelvin, 9.0 * kelvin / 5.0 - 459.67, "F"))
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
| #BASIC | BASIC | 10 DEFINT A-Z
20 FOR I=1 TO 100
30 N=I: GOSUB 100
40 PRINT USING " ##";T;
50 IF I MOD 20=0 THEN PRINT
60 NEXT
70 END
100 T=1
110 IF (N AND 1)=0 THEN N=N\2: T=T+1: GOTO 110
120 P=3
130 GOTO 180
140 C=1
150 IF N MOD P=0 THEN N=N\P: C=C+1: GOTO 150
160 T=T*C
170 P=P+2
180 IF P*P<=N GOTO 140
190 IF N>1 THEN T=T*2
200 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
| #BCPL | BCPL | get "libhdr"
let tau(n) = valof
$( let total = 1 and p = 3
while (n & 1) = 0
$( total := total + 1
n := n >> 1
$)
while p*p <= n
$( let count = 1
while n rem p = 0
$( count := count + 1
n := n / p
$)
total := total * count
p := p + 2
$)
if n>1 then total := total * 2
resultis total
$)
let start() be
for n=1 to 100
$( writed(tau(n), 3)
if n rem 20 = 0 then wrch('*N')
$) |
http://rosettacode.org/wiki/Terminal_control/Clear_the_screen | Terminal control/Clear the screen | Task
Clear the terminal window.
| #Comal | Comal | PAGE |
http://rosettacode.org/wiki/Terminal_control/Clear_the_screen | Terminal control/Clear the screen | Task
Clear the terminal window.
| #Common_Lisp | Common Lisp |
(format t "~C[2J" #\Esc)
|
http://rosettacode.org/wiki/Terminal_control/Clear_the_screen | Terminal control/Clear the screen | Task
Clear the terminal window.
| #D | D | extern (C) nothrow {
void disp_open();
void disp_move(int, int);
void disp_eeop();
void disp_close();
}
void main() {
disp_open();
disp_move(0, 0);
disp_eeop();
disp_close();
} |
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
| #Go | Go | package main
import "fmt"
type trit int8
const (
trFalse trit = iota - 1
trMaybe
trTrue
)
func (t trit) String() string {
switch t {
case trFalse:
return "False"
case trMaybe:
return "Maybe"
case trTrue:
return "True "
}
panic("Invalid trit")
}
func trNot(t trit) trit {
return -t
}
func trAnd(s, t trit) trit {
if s < t {
return s
}
return t
}
func trOr(s, t trit) trit {
if s > t {
return s
}
return t
}
func trEq(s, t trit) trit {
return s * t
}
func main() {
trSet := []trit{trFalse, trMaybe, trTrue}
fmt.Println("t not t")
for _, t := range trSet {
fmt.Println(t, trNot(t))
}
fmt.Println("\ns t s and t")
for _, s := range trSet {
for _, t := range trSet {
fmt.Println(s, t, trAnd(s, t))
}
}
fmt.Println("\ns t s or t")
for _, s := range trSet {
for _, t := range trSet {
fmt.Println(s, t, trOr(s, t))
}
}
fmt.Println("\ns t s eq t")
for _, s := range trSet {
for _, t := range trSet {
fmt.Println(s, t, trEq(s, t))
}
}
} |
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.
| #JavaScript | JavaScript | var filename = 'readings.txt';
var show_lines = 5;
var file_stats = {
'num_readings': 0,
'total': 0,
'reject_run': 0,
'reject_run_max': 0,
'reject_run_date': ''
};
var fh = new ActiveXObject("Scripting.FileSystemObject").openTextFile(filename, 1); // 1 = for reading
while ( ! fh.atEndOfStream) {
var line = fh.ReadLine();
line_stats(line, (show_lines-- > 0));
}
fh.close();
WScript.echo(
"\nFile(s) = " + filename + "\n" +
"Total = " + dec3(file_stats.total) + "\n" +
"Readings = " + file_stats.num_readings + "\n" +
"Average = " + dec3(file_stats.total / file_stats.num_readings) + "\n\n" +
"Maximum run of " + file_stats.reject_run_max +
" consecutive false readings ends at " + file_stats.reject_run_date
);
function line_stats(line, print_line) {
var readings = 0;
var rejects = 0;
var total = 0;
var fields = line.split('\t');
var date = fields.shift();
while (fields.length > 0) {
var value = parseFloat(fields.shift());
var flag = parseInt(fields.shift(), 10);
readings++;
if (flag <= 0) {
rejects++;
file_stats.reject_run++;
}
else {
total += value;
if (file_stats.reject_run > file_stats.reject_run_max) {
file_stats.reject_run_max = file_stats.reject_run;
file_stats.reject_run_date = date;
}
file_stats.reject_run = 0;
}
}
file_stats.num_readings += readings - rejects;
file_stats.total += total;
if (print_line) {
WScript.echo(
"Line: " + date + "\t" +
"Reject: " + rejects + "\t" +
"Accept: " + (readings - rejects) + "\t" +
"Line_tot: " + dec3(total) + "\t" +
"Line_avg: " + ((readings == rejects) ? "0.0" : dec3(total / (readings - rejects)))
);
}
}
// round a number to 3 decimal places
function dec3(value) {
return Math.round(value * 1e3) / 1e3;
} |
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.
| #Wren | Wren | import "/trait" for Stepped
import "/dynamic" for Enum
import "/fmt" for Fmt
/* external results */
var randrsl = List.filled(256, 0)
var randcnt = 0
/* internal state */
var mm = List.filled(256, 0)
var aa = 0
var bb = 0
var cc = 0
var GOLDEN_RATIO = 0x9e3779b9
var isaac = Fn.new {
cc = cc + 1 // cc just gets incremented once per 256 results
bb = bb + cc // then combined with bb
for (i in 0..255) {
var x = mm[i]
var j = i % 4
aa = (j == 0) ? aa ^ (aa << 13) :
(j == 1) ? aa ^ (aa >> 6) :
(j == 2) ? aa ^ (aa << 2) :
(j == 3) ? aa ^ (aa >> 16) : aa
aa = aa + mm[(i + 128) % 256]
var y = mm[(x >> 2) % 256] + aa + bb
mm[i] = y
bb = mm[(y >> 10) % 256] + x
randrsl[i] = bb
}
randcnt = 0
}
/* if (flag == true), then use the contents of randrsl to initialize mm. */
var mix = Fn.new { |n|
n[0] = n[0] ^ (n[1] << 11)
n[3] = n[3] + n[0]
n[1] = n[1] + n[2]
n[1] = n[1] ^ (n[2] >> 2)
n[4] = n[4] + n[1]
n[2] = n[2] + n[3]
n[2] = n[2] ^ (n[3] << 8)
n[5] = n[5] + n[2]
n[3] = n[3] + n[4]
n[3] = n[3] ^ (n[4] >> 16)
n[6] = n[6] + n[3]
n[4] = n[4] + n[5]
n[4] = n[4] ^ (n[5] << 10)
n[7] = n[7] + n[4]
n[5] = n[5] + n[6]
n[5] = n[5] ^ (n[6] >> 4)
n[0] = n[0] + n[5]
n[6] = n[6] + n[7]
n[6] = n[6] ^ (n[7] << 8)
n[1] = n[1] + n[6]
n[7] = n[7] + n[0]
n[7] = n[7] ^ (n[0] >> 9)
n[2] = n[2] + n[7]
n[0] = n[0] + n[1]
}
var randinit = Fn.new { |flag|
aa = 0
bb = 0
cc = 0
var n = List.filled(8, GOLDEN_RATIO)
for (i in 0..3) mix.call(n) // scramble the array
for (i in Stepped.new(0..255, 8)) { // fill in mm with messy stuff
if (flag) { // use all the information in the seed
for (j in 0..7) {
n[j] = n[j] + randrsl[i + j]
}
}
mix.call(n)
for (j in 0..7) mm[i + j] = n[j]
}
if (flag) {
/* do a second pass to make all of the seed affect all of mm */
for (i in Stepped.new(0..255, 8)) {
for (j in 0..7) n[j] = n[j] + mm[i + j]
mix.call(n)
for (j in 0..7) mm[i + j] = n[j]
}
}
isaac.call() // fill in the first set of results
randcnt = 0 // prepare to use the first set of results
}
var iRandom = Fn.new {
var r = randrsl[randcnt]
randcnt = randcnt + 1
if (randcnt > 255) {
isaac.call()
randcnt = 0
}
return r & 0xffffffff
}
/* Get a random character (as Num) in printable ASCII range */
var iRandA = Fn.new { (iRandom.call() % 95 + 32) }
/* Seed ISAAC with a string */
var iSeed = Fn.new { |seed, flag|
for (i in 0..255) mm[i] = 0
var m = seed.count
for (i in 0..255) {
/* in case seed has less than 256 elements */
randrsl[i] = (i >= m) ? 0 : seed[i].bytes[0]
}
/* initialize ISAAC with seed */
randinit.call(flag)
}
/* XOR cipher on random stream. Output: ASCII string */
var vernam = Fn.new { |msg|
var len = msg.count
var v = List.filled(len, 0)
var i = 0
for (b in msg.bytes) {
v[i] = (iRandA.call() ^ b) & 0xff
i = i + 1
}
return v.map { |b| String.fromByte(b) }.join()
}
/* constants for Caesar */
var MOD = 95
var START = 32
/* cipher modes for Caesar */
var CipherMode = Enum.create("CipherMode", ["ENCIPHER", "DECIPHER", "NONE"])
/* Caesar-shift a printable character */
var caesar = Fn.new { |m, ch, shift, modulo, start|
var sh = (m == CipherMode.DECIPHER) ? -shift : shift
var n = (ch - start) + sh
n = n % modulo
if (n < 0) n = n + modulo
return String.fromByte(start + n)
}
/* Caesar-shift a string on a pseudo-random stream */
var caesarStr = Fn.new { |m, msg, modulo, start|
var sb = ""
/* Caesar-shift message */
for (b in msg.bytes) {
sb = sb + caesar.call(m, b, iRandA.call(), modulo, start)
}
return sb
}
var toHexByteString = Fn.new { |s|
return s.bytes.map { |b| Fmt.swrite("$02X", b) }.join()
}
var msg = "a Top Secret secret"
var key = "this is my secret key"
// Vernam & Caesar ciphertext
iSeed.call(key, true)
var vctx = vernam.call(msg)
var cctx = caesarStr.call(CipherMode.ENCIPHER, msg, MOD, START)
// Vernam & Caesar plaintext
iSeed.call(key, true)
var vptx = vernam.call(vctx)
var cptx = caesarStr.call(CipherMode.DECIPHER, cctx, MOD, START)
// Program output
System.print("Message : %(msg)")
System.print("Key : %(key)")
System.print("XOR : %(toHexByteString.call(vctx))")
System.print("XOR dcr : %(vptx)")
System.print("MOD : %(toHexByteString.call(cctx))")
System.print("MOD dcr : %(cptx)") |
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).
| #Ursala | Ursala |
#import std
#import nat
log = ^(~&hh==`O,~&tth)*FtPS sep` *F mlijobs_dot_txt
scan = @NiX ~&ar^& ^C/~&alrhr2X ~&arlh?/~&faNlCrtPXPR ~&fabt2R
search = @lSzyCrSPp leql$^&hl@lK2; ^/length@hl ~&rS
format = ^|C\~& --' licenses in use at'@h+ %nP
#show+
main = format search scan log |
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).
| #Vedit_macro_language | Vedit macro language |
File_Open("|(PATH_ONLY)\data\mlijobs.txt", BROWSE)
#1 = 0 // Number of licenses active
#2 = 0 // Max number of active licenses found
Repeat(ALL) {
Search("|{OUT,IN}|W@", ADVANCE+ERRBREAK)
if (Match_Item == 1) { // "OUT"
#1++
if (#1 > #2) { // new high value
#2 = #1
Reg_Empty(10) // empty the time list
}
if (#1 == #2) { // same as high value
Reg_Copy(10, 1, APPEND) // store time
}
} else { // "IN"
#1--
}
}
Message("Maximum simultaneous license use is ")
Num_Type(#2, LEFT+NOCR)
Message(" at the following times:\n")
Reg_Type(10)
Buf_Quit(OK)
|
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.
| #Ruby | Ruby | def palindrome?(s)
s == s.reverse
end
require 'test/unit'
class MyTests < Test::Unit::TestCase
def test_palindrome_ok
assert(palindrome? "aba")
end
def test_palindrome_nok
assert_equal(false, palindrome?("ab"))
end
def test_object_without_reverse
assert_raise(NoMethodError) {palindrome? 42}
end
def test_wrong_number_args
assert_raise(ArgumentError) {palindrome? "a", "b"}
end
def test_show_failing_test
assert(palindrome?("ab"), "this test case fails on purpose")
end
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.
| #Rust | Rust | /// Tests if the given string slice is a palindrome (with the respect to
/// codepoints, not graphemes).
///
/// # Examples
///
/// ```
/// # use playground::palindrome::is_palindrome;
/// assert!(is_palindrome("abba"));
/// assert!(!is_palindrome("baa"));
/// ```
pub fn is_palindrome(s: &str) -> bool {
let half = s.len();
s.chars().take(half).eq(s.chars().rev().take(half))
}
#[cfg(test)]
mod tests {
use super::is_palindrome;
#[test]
fn test_is_palindrome() {
assert!(is_palindrome("abba"));
}
} |
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
| #Factor | Factor | USING: formatting io kernel math math.ranges qw sequences ;
IN: rosetta-code.twelve-days-of-christmas
CONSTANT: opener
"On the %s day of Christmas, my true love sent to me:\n"
CONSTANT: ordinals qw{
first second third fourth fifth sixth seventh eighth ninth
tenth eleventh twelfth
}
CONSTANT: 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,"
}
: descend ( n -- ) 0 [a,b] [ gifts nth print ] each nl ;
: verse ( n -- )
1 - [ ordinals nth opener printf ] [ descend ] bi ;
: twelve-days-of-christmas ( -- ) 12 [1,b] [ verse ] each ;
MAIN: twelve-days-of-christmas |
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
| #Forth | Forth | create ordinals s" first" 2, s" second" 2, s" third" 2, s" fourth" 2,
s" fifth" 2, s" sixth" 2, s" seventh" 2, s" eighth" 2,
s" ninth" 2, s" tenth" 2, s" eleventh" 2, s" twelfth" 2,
: ordinal ordinals swap 2 * cells + 2@ ;
create gifts s" A partridge in a pear tree." 2,
s" Two turtle doves and" 2,
s" Three French hens," 2,
s" Four calling birds," 2,
s" Five gold rings," 2,
s" Six geese a-laying," 2,
s" Seven swans a-swimming," 2,
s" Eight maids a-milking," 2,
s" Nine ladies dancing," 2,
s" Ten lords a-leaping," 2,
s" Eleven pipers piping," 2,
s" Twelve drummers drumming," 2,
: gift gifts swap 2 * cells + 2@ ;
: day
s" On the " type
dup ordinal type
s" day of Christmas, my true love sent to me:" type
cr
-1 swap -do
i gift type cr
1 -loop
cr
;
: main
12 0 do i day loop
;
main
bye
|
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)
| #J | J | NB. relies on an vt100 terminal
CSI=: 27 91 { a.
'BLACK BLUE CYAN WHITE'=: 0 4 6 7
'OFF REVERSEVIDEO'=: 0 7
HIDECURSOR=: CSI,'?25l'
SHOWCURSOR=: CSI,'?25h'
csi=: (,~ (CSI , (' '&=)`(,:&';')}@:":))~
clear=: csi&'J'
attributes=: csi&'m'
color=: BLACK&$: : (attributes@:(40 30 + ,)) NB. BACKGROUND color FOREGROUND
move=: csi&'H'
upward=: csi&'A'
downward=: csi&'B'
foreward=: csi&'C'
backward=: csi&'D'
DB=: (downward , backward) ''
NB. J is character vector to simulate the J icon.
J=: (BLUE color WHITE[CYAN)
J=: J , (backward 1),' T ',(backward 1),DB,,3#,:'|',DB
J=: J , (backward 5),'* |',DB
J=: J , (backward 5),'\____/'
smoutput(color BLACK),(clear 2),(move 8 22),J,(WHITE color BLACK),(downward 2)
|
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.
| #Wren | Wren | import "timer" for Timer
import "io" for Stdout
System.write("\e[2J") // clear terminal
System.write("\e[12;40H") // move to (12, 40)
Stdout.flush()
Timer.sleep(2000)
System.write("\e[D") // move left
Stdout.flush()
Timer.sleep(2000)
System.write("\e[C") // move right
Stdout.flush()
Timer.sleep(2000)
System.write("\e[A") // move up
Stdout.flush()
Timer.sleep(2000)
System.write("\e[B") // move down
Stdout.flush()
Timer.sleep(2000)
System.write("\e[G") // move to beginning of line
Stdout.flush()
Timer.sleep(2000)
System.write("\e[79C") // move to end of line (assuming 80 column terminal)
Stdout.flush()
Timer.sleep(2000)
System.write("\e[1;1H") // move to top left corner
Stdout.flush()
Timer.sleep(2000)
System.write("\e[24;80H") // move to bottom right corner (assuming 80 x 24 terminal)
Stdout.flush()
Timer.sleep(2000)
System.write("\e[1;1H") // home cursor again before quitting |
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.
| #AWK | AWK | #!/bin/sh -f
awk '
BEGIN {
print "Creating table..."
dbExec("address.db", "create table address (street, city, state, zip);")
print "Done."
exit
}
function dbExec(db, qry, result) {
dbMakeQuery(db, qry) | getline result
dbErrorCheck(result)
}
function dbMakeQuery(db, qry, q) {
q = dbEscapeQuery(qry) ";"
return "echo \"" q "\" | sqlite3 " db
}
function dbEscapeQuery(qry, q) {
q = qry
gsub(/"/, "\\\"", q)
return q
}
function dbErrorCheck(res) {
if (res ~ "SQL error") {
print res
exit
}
}
' |
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.
| #AppleScript | AppleScript | #!/usr/bin/osascript
-- format a number as a string with leading zero if needed
to format(aNumber)
set resultString to aNumber as text
if length of resultString < 2
set resultString to "0" & resultString
end if
return resultString
end format
-- join a list with a delimiter
to concatenation of aList given delimiter:aDelimiter
set tid to AppleScript's text item delimiters
set AppleScript's text item delimiters to { aDelimiter }
set resultString to aList as text
set AppleScript's text item delimiters to tid
return resultString
end join
-- apply a handler to every item in a list, returning
-- a list of the results
to mapping of aList given function:aHandler
set resultList to {}
global h
set h to aHandler
repeat with anItem in aList
set resultList to resultList & h(anItem)
end repeat
return resultList
end mapping
-- return an ISO-8601-formatted string representing the current date and time
-- in UTC
to iso8601()
set { year:y, month:m, day:d, ¬
hours:hr, minutes:min, seconds:sec } to ¬
(current date) - (time to GMT)
set ymdList to the mapping of { y, m as integer, d } given function:format
set ymd to the concatenation of ymdList given delimiter:"-"
set hmsList to the mapping of { hr, min, sec } given function:format
set hms to the concatenation of hmsList given delimiter:":"
set dateTime to the concatenation of {ymd, hms} given delimiter:"T"
return dateTime & "Z"
end iso8601
to exists(filePath)
try
filePath as alias
return true
on error
return false
end try
end exists
on run argv
set curDir to (do shell script "pwd")
set notesFile to POSIX file (curDir & "/NOTES.TXT")
if (count argv) is 0 then
if exists(notesFile) then
set text item delimiters to {linefeed}
return paragraphs of (read notesFile) as text
else
log "No notes here."
return
end if
else
try
set fd to open for access notesFile with write permission
write (iso8601() & linefeed & tab) to fd starting at eof
set AppleScript's text item delimiters to {" "}
write ((argv as text) & linefeed) to fd starting at eof
close access fd
return true
on error errMsg number errNum
try
close access fd
end try
return "unable to open " & notesFile & ": " & errMsg
end try
end if
end run |
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).
| #D | D | void main() /*@safe*/ {
import std.stdio, std.range, std.algorithm, std.typecons, std.string;
auto iCubes = iota(1u, 1201u).map!(x => tuple(x, x ^^ 3));
bool[Tuple!(uint, uint)][uint] sum2cubes;
foreach (i, immutable i3; iCubes)
foreach (j, immutable j3; iCubes[i .. $])
sum2cubes[i3 + j3][tuple(i, j)] = true;
const taxis = sum2cubes.byKeyValue.filter!(p => p.value.length > 1)
.array.schwartzSort!(p => p.key).release;
foreach (/*immutable*/ const r; [[0, 25], [2000 - 1, 2000 + 6]]) {
foreach (immutable i, const t; taxis[r[0] .. r[1]])
writefln("%4d: %10d =%-(%s =%)", i + r[0] + 1, t.key,
t.value.keys.sort().map!q{"%4d^3 + %4d^3".format(a[])});
writeln;
}
} |
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
| #F.23 | F# |
// Tau number. Nigel Galloway: March 9th., 2021
Seq.initInfinite((+)1)|>Seq.filter(fun n->n%(tau n)=0)|>Seq.take 100|>Seq.iter(printf "%d "); printfn ""
|
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
| #Factor | Factor | USING: assocs grouping io kernel lists lists.lazy math
math.functions math.primes.factors prettyprint sequences
sequences.extras ;
: tau ( n -- count ) group-factors values [ 1 + ] map-product ;
: tau? ( n -- ? ) dup tau divisor? ;
: taus ( -- list ) 1 lfrom [ tau? ] lfilter ;
! Task
"The first 100 tau numbers are:" print
100 taus ltake list>array 10 group simple-table.
|
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
| #Fermat | Fermat | Func Istau(t) =
if t<3 then Return(1) else
numdiv:=2;
for q = 2 to t\2 do
if Divides(q, t) then numdiv:=numdiv+1 fi;
od;
if Divides(numdiv, t)=1 then Return(1) else Return(0) fi;
fi;
.;
numtau:=0;
i:=0;
while numtau<100 do
i:=i+1;
if Istau(i) = 1 then
numtau:=numtau+1;
!(i,' ');
if Divides(10, numtau) then !! fi;
fi;
od; |
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.
| #jq | jq | # Input: an integer
def Node:
{ n: .,
index: -1, # -1 signifies undefined
lowLink: -1,
onStack: false
} ;
# Input: a DirectedGraph
# Output: a stream of Node ids
def successors($vn): .es[$vn][];
# Input: a DirectedGraph
# Output: an array of integer arrays
def tarjan:
. + { sccs: [], # strongly connected components
index: 0,
s: [] # Stack
}
# input: {es, vs, sccs, index, s}
| def strongConnect($vn):
# Set the depth index for v to the smallest unused index
.vs[$vn].index = .index
| .vs[$vn].lowLink = .index
| .index += 1
| .s += [ $vn ]
| .vs[$vn].onStack = true
# consider successors of v
| reduce successors($vn) as $wn (.;
if .vs[$wn].index < 0
then
# Successor w has not yet been visited; recurse on it
strongConnect($wn)
| .vs[$vn].lowLink = ([.vs[$vn].lowLink, .vs[$wn].lowLink] | min )
elif .vs[$wn].onStack
then
# Successor w is in stack s and hence in the current SCC
.vs[$vn].lowLink = ([.vs[$vn].lowLink, .vs[$wn].index] | min )
else .
end
)
# If v is a root node, pop the stack and generate an SCC
| if .vs[$vn] | (.lowLink == .index)
then .scc = []
| .stop = false
| until(.stop;
.s[-1] as $wn
| .s |= .[:-1] # pop
| .vs[$wn].onStack = false
| .scc += [$wn]
| if $wn == $vn then .stop = true else . end )
| .sccs += [.scc]
else .
end
;
reduce .vs[].n as $vn (.;
if .vs[$vn].index < 0
then strongConnect($vn)
else . end
)
| .sccs
;
# Vertices
def vs: [range(0;8) | Node ];
# Edges
def es:
[ [1],
[2],
[0],
[1, 2, 4],
[5, 3],
[2, 6],
[5],
[4, 7, 6]
]
;
{ vs: vs, es: es }
| tarjan |
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.
| #Julia | Julia | using LightGraphs
edge_list=[(1,2),(3,1),(6,3),(6,7),(7,6),(2,3),(4,2),(4,3),(4,5),(5,6),(5,4),(8,5),(8,8),(8,7)]
grph = SimpleDiGraph(Edge.(edge_list))
tarj = strongly_connected_components(grph)
inzerobase(arrarr) = map(x -> sort(x .- 1, rev=true), arrarr)
println("Results in the zero-base scheme: $(inzerobase(tarj))")
|
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.
| #Kotlin | Kotlin | // version 1.1.3
import java.util.Stack
typealias Nodes = List<Node>
class Node(val n: Int) {
var index = -1 // -1 signifies undefined
var lowLink = -1
var onStack = false
override fun toString() = n.toString()
}
class DirectedGraph(val vs: Nodes, val es: Map<Node, Nodes>)
fun tarjan(g: DirectedGraph): List<Nodes> {
val sccs = mutableListOf<Nodes>()
var index = 0
val s = Stack<Node>()
fun strongConnect(v: Node) {
// Set the depth index for v to the smallest unused index
v.index = index
v.lowLink = index
index++
s.push(v)
v.onStack = true
// consider successors of v
for (w in g.es[v]!!) {
if (w.index < 0) {
// Successor w has not yet been visited; recurse on it
strongConnect(w)
v.lowLink = minOf(v.lowLink, w.lowLink)
}
else if (w.onStack) {
// Successor w is in stack s and hence in the current SCC
v.lowLink = minOf(v.lowLink, w.index)
}
}
// If v is a root node, pop the stack and generate an SCC
if (v.lowLink == v.index) {
val scc = mutableListOf<Node>()
do {
val w = s.pop()
w.onStack = false
scc.add(w)
}
while (w != v)
sccs.add(scc)
}
}
for (v in g.vs) if (v.index < 0) strongConnect(v)
return sccs
}
fun main(args: Array<String>) {
val vs = (0..7).map { Node(it) }
val es = mapOf(
vs[0] to listOf(vs[1]),
vs[2] to listOf(vs[0]),
vs[5] to listOf(vs[2], vs[6]),
vs[6] to listOf(vs[5]),
vs[1] to listOf(vs[2]),
vs[3] to listOf(vs[1], vs[2], vs[4]),
vs[4] to listOf(vs[5], vs[3]),
vs[7] to listOf(vs[4], vs[7], vs[6])
)
val g = DirectedGraph(vs, es)
val sccs = tarjan(g)
println(sccs.joinToString("\n"))
} |
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
| #jq | jq | # Output: an array of the words when read around the rim
def read_teacup:
. as $in
| [range(0; length) | $in[.:] + $in[:.] ];
# Boolean
def is_teacup_word($dict):
. as $in
| all( range(1; length); . as $i | $dict[ $in[$i:] + $in[:$i] ]) ;
# Output: a stream of the eligible teacup words
def teacup_words:
def same_letters:
explode
| .[0] as $first
| all( .[1:][]; . == $first);
# Only consider one word in a teacup cycle
def consider: explode | .[0] == min;
# Create the dictionary
reduce (inputs
| select(length>2 and (same_letters|not))) as $w ( {};
.[$w]=true )
| . as $dict
| keys[]
| select(consider and is_teacup_word($dict)) ;
# The task:
teacup_words
| read_teacup |
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
| #Julia | Julia | using HTTP
rotate(s, n) = String(circshift(Vector{UInt8}(s), n))
isliketea(w, d) = (n = length(w); n > 2 && any(c -> c != w[1], w) &&
all(i -> haskey(d, rotate(w, i)), 1:n-1))
function getteawords(listuri)
req = HTTP.request("GET", listuri)
wdict = Dict{String, Int}((lowercase(string(x)), 1) for x in split(String(req.body), r"\s+"))
sort(unique([sort([rotate(word, i) for i in 1:length(word)])
for word in collect(keys(wdict)) if isliketea(word, wdict)]))
end
foreach(println, getteawords("https://www.mit.edu/~ecprice/wordlist.10000"))
|
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
| #ALGOL-M | ALGOL-M | BEGIN
DECIMAL K, C, F, R;
WRITE( "Temperature in Kelvin:" );
READ( K );
C := K - 273.15;
F := K * 1.8 - 459.67;
R := K * 1.8;
WRITE( K, " Kelvin is equivalent to" );
WRITE( C, " degrees Celsius" );
WRITE( F, " degrees Fahrenheit" );
WRITE( R, " degrees Rankine" );
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
| #BQN | BQN | Tau ← +´0=(1+↕)|⊢
Tau¨ 5‿20⥊1+↕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
| #C | C | #include <stdio.h>
// 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;
unsigned int n;
printf("Count of divisors for the first %d positive integers:\n", limit);
for (n = 1; n <= limit; ++n) {
printf("%3d", divisor_count(n));
if (n % 20 == 0) {
printf("\n");
}
}
return 0;
} |
http://rosettacode.org/wiki/Terminal_control/Clear_the_screen | Terminal control/Clear the screen | Task
Clear the terminal window.
| #Dc | Dc | !clear |
http://rosettacode.org/wiki/Terminal_control/Clear_the_screen | Terminal control/Clear the screen | Task
Clear the terminal window.
| #Delphi | Delphi |
uses
System.SysUtils,
Winapi.Windows;
procedure ClearScreen;
var
stdout: THandle;
csbi: TConsoleScreenBufferInfo;
ConsoleSize: DWORD;
NumWritten: DWORD;
Origin: TCoord;
begin
stdout := GetStdHandle(STD_OUTPUT_HANDLE);
Win32Check(stdout<>INVALID_HANDLE_VALUE);
Win32Check(GetConsoleScreenBufferInfo(stdout, csbi));
ConsoleSize := csbi.dwSize.X * csbi.dwSize.Y;
Origin.X := 0;
Origin.Y := 0;
Win32Check(FillConsoleOutputCharacter(stdout, ' ', ConsoleSize, Origin,
NumWritten));
Win32Check(FillConsoleOutputAttribute(stdout, csbi.wAttributes, ConsoleSize, Origin,
NumWritten));
Win32Check(SetConsoleCursorPosition(stdout, Origin));
end; |
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
| #Groovy | Groovy | enum Trit {
TRUE, MAYBE, FALSE
private Trit nand(Trit that) {
switch ([this,that]) {
case { FALSE in it }: return TRUE
case { MAYBE in it }: return MAYBE
default : return FALSE
}
}
private Trit nor(Trit that) { this.or(that).not() }
Trit and(Trit that) { this.nand(that).not() }
Trit or(Trit that) { this.not().nand(that.not()) }
Trit not() { this.nand(this) }
Trit imply(Trit that) { this.nand(that.not()) }
Trit equiv(Trit that) { this.and(that).or(this.nor(that)) }
} |
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.
| #jq | jq | foreach STREAM as $row ( INITIAL; EXPRESSION; VALUE ). |
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).
| #Wren | Wren | import "io" for File
var lines = File.read("mlijobs.txt").replace("\r", "").split("\n")
var out = 0
var max = 0
var times = []
for (line in lines) {
if (line.startsWith("License OUT")) {
out = out + 1
if (out >= max) {
var sp = line.split(" ")
if (out > max) {
max = out
times.clear()
}
times.add(sp[3])
}
} else if (line.startsWith("License IN")) {
out = out - 1
}
}
System.print("The maximum licenses that were out = %(max) at time(s):")
System.print(" " + times.join("\n ")) |
http://rosettacode.org/wiki/Test_a_function | Test a function |
Task
Using a well-known testing-specific library/module/suite for your language, write some tests for your language's entry in Palindrome.
If your language does not have a testing specific library well known to the language's community then state this or omit the language.
| #Scala | Scala | import org.scalacheck._
import Prop._
import Gen._
object PalindromeCheck extends Properties("Palindrome") {
property("A string concatenated with its reverse is a palindrome") =
forAll { s: String => isPalindrome(s + s.reverse) }
property("A string concatenated with any character and its reverse is a palindrome") =
forAll { (s: String, c: Char) => isPalindrome(s + c + s.reverse) }
property("If the first half of a string is equal to the reverse of its second half, it is a palindrome") =
forAll { (s: String) => s.take(s.length / 2) != s.drop((s.length + 1) / 2).reverse || isPalindrome(s) }
property("If the first half of a string is different than the reverse of its second half, it isn't a palindrome") =
forAll { (s: String) => s.take(s.length / 2) == s.drop((s.length + 1) / 2).reverse || !isPalindrome(s) }
} |
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.
| #Scheme | Scheme |
(import (srfi 64))
(test-begin "palindrome-tests")
(test-assert (palindrome? "ingirumimusnocteetconsumimurigni"))
(test-assert (not (palindrome? "This is not a palindrome")))
(test-equal #t (palindrome? "ingirumimusnocteetconsumimurigni")) ; another of several test functions
(test-end)
|
http://rosettacode.org/wiki/The_Twelve_Days_of_Christmas | The Twelve Days of Christmas | Task
Write a program that outputs the lyrics of the Christmas carol The Twelve Days of Christmas.
The lyrics can be found here.
(You must reproduce the words in the correct order, but case, format, and punctuation are left to your discretion.)
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Fortran | Fortran | program twelve_days
character days(12)*8
data days/'first', 'second', 'third', 'fourth',
c 'fifth', 'sixth', 'seventh', 'eighth',
c 'ninth', 'tenth', 'eleventh', 'twelfth'/
character gifts(12)*27
data gifts/'A partridge in a pear tree.',
c 'Two turtle doves and',
c 'Three French hens,',
c 'Four calling birds,',
c 'Five gold rings,',
c 'Six geese a-laying,',
c 'Seven swans a-swimming,',
c 'Eight maids a-milking,',
c 'Nine ladies dancing,',
c 'Ten lords a-leaping,',
c 'Eleven pipers piping,',
c 'Twelve drummers drumming,'/
integer day, gift
do 10 day=1,12
write (*,'(a)') 'On the ', trim(days(day)),
c ' day of Christmas, my true love sent to me:'
do 20 gift=day,1,-1
write (*,'(a)') trim(gifts(gift))
20 continue
write(*,*)
10 continue
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)
| #Julia | Julia |
using AnsiColor
function showbasecolors()
for color in keys(Base.text_colors)
print_with_color(color, " ", string(color), " ")
end
println()
end
function showansicolors()
for fore in keys(AnsiColor.COLORS)
print(@sprintf("%15s ", fore))
for back in keys(AnsiColor.COLORS)
print(" ", colorize(fore, "RC", background=back), " ")
end
println()
end
println()
for eff in keys(AnsiColor.MODES)
print(@sprintf(" %s ", eff), colorize("default", "RC", mode=eff))
end
println()
end
if Base.have_color
println()
println("Base Colors")
showbasecolors()
println("\nusing AnsiColor")
showansicolors()
println()
else
println("This terminal appears not to support color.")
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)
| #Kotlin | Kotlin | // version 1.1.2
const val ESC = "\u001B"
const val NORMAL = ESC + "[0"
const val BOLD = ESC + "[1"
const val BLINK = ESC + "[5" // not working on my machine
const val BLACK = ESC + "[0;40m" // black background
const val WHITE = ESC + "[0;37m" // normal white foreground
fun main(args: Array<String>) {
print("${ESC}c") // clear terminal first
print(BLACK) // set background color to black
val foreColors = listOf(
";31m" to "red",
";32m" to "green",
";33m" to "yellow",
";34m" to "blue",
";35m" to "magenta",
";36m" to "cyan",
";37m" to "white"
)
for (attr in listOf(NORMAL, BOLD, BLINK)) {
for (color in foreColors) println("$attr${color.first}${color.second}")
}
println(WHITE) // set foreground color to normal white
} |
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.
| #XPL0 | XPL0 | include c:\cxpl\codes; \intrinsic 'code' declarations
int I, X, Y, W, H;
[Cursor(10, 13); \set cursor to arbitrary location on screen
I:= ChIn(1); \wait for keystroke (no echo to display)
ChOut(0, $08\BS\); \backspace moves one position right
I:= ChIn(1);
X:= Peek($40, $50); \get cursor location from BIOS data
Y:= Peek($40, $51);
Cursor(X+1, Y); \move one position right
I:= ChIn(1);
Cursor(X+1, Y-1); \move up one line
I:= ChIn(1);
ChOut(0, $0A\LF\); \line feed moves down one line
I:= ChIn(1);
ChOut(0, $0D\CR\); \carriage return moves to beginning of current line
I:= ChIn(1);
W:= Peek($40, $4A); \get width of display (standard = 80; mine = 94)
Cursor(W-1, Y); \move to end of current line
I:= ChIn(1);
Cursor(0, 0); \move to top left corner
I:= ChIn(1);
H:= Peek($40, $84) + 1; \get height of display (standard = 25; mine = 50)
Cursor(W-1, H-1); \move to bottom right corner
I:= ChIn(1);
] |
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.
| #zkl | zkl | print("\e[2J\e[6;3H"); // clear screen, move to an initial position
Atomic.sleep(1); // pause to let cursor blink
print("\e[D"); // left
Atomic.sleep(1);
print("\e[C"); // right
Atomic.sleep(1);
print("\e[A"); // up
Atomic.sleep(1);
print("\e[B"); // down
Atomic.sleep(1);
print("\e[;H"); // top left
Atomic.sleep(1); |
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.
| #ZX_Spectrum_Basic | ZX Spectrum Basic | 10 PRINT CHR$(8);:REM cursor one position left
20 PRINT CHR$(9);:REM cursor one position right
30 GO SUB 500: REM get cursor position
40 IF cr>0 THEN LET cr=cr-1: GO SUB 550: REM cursor up one line
50 IF cr<22 THEN LET cr=cr+1: GO SUB 550: REM cursor down one line
60 POKE 23688,33: REM cursor to beginning of the line
70 POKE 23688,0: REM cursor to end of line
80 POKE 23688,33:POKE 23689,24: REM cursor to top left
90 REM bottom two rows are reserved for input and errors
100 REM so we reserve those lines here
110 POKE 23688,0: POKE 23689,2: REM bottom right
499 STOP: REM do not overrun into subroutines
500 REM get cursor position
510 LET cc=33-PEEK 23688:REM current column
520 LET cr=24-PEEK 23689:REM current row
530 RETURN
550 REM set cursor position
560 PRINT AT cr,cc;
570 RETURN
600 REM alternative set cursor position
610 POKE 23688,33-cc
620 POKE 23689,24-cr
630 RETURN |
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.
| #C | C | #include <stdio.h>
#include <stdlib.h>
#include <sqlite3.h>
const char *code =
"CREATE TABLE address (\n"
" addrID INTEGER PRIMARY KEY AUTOINCREMENT,\n"
" addrStreet TEXT NOT NULL,\n"
" addrCity TEXT NOT NULL,\n"
" addrState TEXT NOT NULL,\n"
" addrZIP TEXT NOT NULL)\n" ;
int main()
{
sqlite3 *db = NULL;
char *errmsg;
if ( sqlite3_open("address.db", &db) == SQLITE_OK ) {
if ( sqlite3_exec(db, code, NULL, NULL, &errmsg) != SQLITE_OK ) {
fprintf(stderr, errmsg);
sqlite3_free(errmsg);
sqlite3_close(db);
exit(EXIT_FAILURE);
}
sqlite3_close(db);
} else {
fprintf(stderr, "cannot open db...\n");
sqlite3_close(db);
exit(EXIT_FAILURE);
}
return EXIT_SUCCESS;
} |
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.
| #Clojure | Clojure | (require '[clojure.java.jdbc :as sql])
; Using h2database for this simple example.
(def db {:classname "org.h2.Driver"
:subprotocol "h2:file"
:subname "db/my-dbname"})
(sql/db-do-commands db
(sql/create-table-ddl :address
[:id "bigint primary key auto_increment"]
[:street "varchar"]
[:city "varchar"]
[:state "varchar"]
[:zip "varchar"]))
|
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.
| #Arturo | Arturo | notes: "notes.txt"
if? empty? arg [
if exists? notes -> print read notes
]
else [
output: (to :string now) ++ "\n" ++
"\t" ++ (join.with:" " to [:string] arg) ++ "\n"
write.append notes output
] |
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.
| #AutoHotkey | AutoHotkey | Notes := "Notes.txt"
If 0 = 0 ; no arguments
{
If FileExist(Notes) {
FileRead, Content, %Notes%
MsgBox, %Content%
} Else
MsgBox, %Notes% does not exist
Goto, EOF
}
; date and time, colon, newline (CRLF), tab
Date := A_DD "/" A_MM "/" A_YYYY
Time := A_Hour ":" A_Min ":" A_Sec "." A_MSec
FileAppend, %Date% %Time%:`r`n%A_Tab%, %Notes%
; command line parameters, trailing newline (CRLF)
Loop, %0%
FileAppend, % %A_Index% " ", %Notes%
FileAppend, `r`n, %Notes%
EOF: |
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).
| #DCL | DCL | $ close /nolog sums_of_cubes
$ on control_y then $ goto clean
$ open /write sums_of_cubes sums_of_cubes.txt
$ i = 1
$ loop1:
$ write sys$output i
$ j = 1
$ loop2:
$ sum = i * i * i + j * j * j
$ if sum .lt. 0
$ then
$ write sys$output "overflow at ", j
$ goto next_i
$ endif
$ write sums_of_cubes f$fao( "!10SL,!10SL,!10SL", sum, i, j )
$ j = j + 1
$ if j .le. i then $ goto loop2
$ next_i:
$ i = i + 1
$ if i .le. 1289 then $ goto loop1 ! cube_root of 2^31-1
$ close sums_of_cubes
$ sort sums_of_cubes.txt sorted_sums_of_cubes.txt
$ close /nolog sorted_sums_of_cubes
$ open sorted_sums_of_cubes sorted_sums_of_cubes.txt
$ count = 0
$ read sorted_sums_of_cubes prev_prev_line ! need to detect when there are more than just 2 different sums, e.g. 456
$ prev_prev_sum = f$element( 0, ",", f$edit( prev_prev_line, "collapse" ))
$ read sorted_sums_of_cubes prev_line
$ prev_sum = f$element( 0,",", f$edit( prev_line, "collapse" ))
$ loop3:
$ read /end_of_file = done sorted_sums_of_cubes line
$ sum = f$element( 0, ",", f$edit( line, "collapse" ))
$ if sum .eqs. prev_sum
$ then
$ if sum .nes. prev_prev_sum then $ count = count + 1
$ int_sum = f$integer( sum )
$ i1 = f$integer( f$element( 1, ",", prev_line ))
$ j1 = f$integer( f$element( 2, ",", prev_line ))
$ i2 = f$integer( f$element( 1, ",", line ))
$ j2 = f$integer( f$element( 2, ",", line ))
$ if count .le. 25 .or. ( count .ge. 2000 .and. count .le. 2006 ) then -
$ write sys$output f$fao( "!4SL:!11SL =!5SL^3 +!5SL^3 =!5SL^3 +!5SL^3", count, int_sum, i1, j1, i2, j2 )
$ endif
$ prev_prev_line = prev_line
$ prev_prev_sum = prev_sum
$ prev_line = line
$ prev_sum = sum
$ goto loop3
$ done:
$ close sorted_sums_of_cubes
$ exit
$
$ clean:
$ close /nolog sorted_sums_of_cubes
$ close /nolog sums_of_cubes |
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
| #Forth | Forth | : divisor_count ( n -- n )
1 >r
begin
dup 2 mod 0=
while
r> 1+ >r
2/
repeat
3
begin
2dup dup * >=
while
1 >r
begin
2dup mod 0=
while
r> 1+ >r
tuck / swap
repeat
2r> * >r
2 +
repeat
drop 1 > if r> 2* else r> then ;
: print_tau_numbers ( n -- )
." The first " dup . ." tau numbers are:" cr
0 >r
1
begin
over r@ >
while
dup dup divisor_count mod 0= if
dup 6 .r
r> 1+
dup 10 mod 0= if cr else space then
>r
then
1+
repeat
2drop rdrop ;
100 print_tau_numbers
bye |
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
| #FreeBASIC | FreeBASIC | function numdiv( n as uinteger ) as uinteger
dim as uinteger c = 2
for i as uinteger = 2 to (n+1)\2
if n mod i = 0 then c += 1
next i
return c
end function
function istau( n as uinteger ) as boolean
if n = 1 then return true
if n mod numdiv(n) = 0 then return true else return false
end function
dim as uinteger c = 0, i=1
while c < 100
if istau(i) then
print i,
c += 1
if c mod 10 = 0 then print
end if
i += 1
wend |
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.
| #Nim | Nim | import sequtils, strutils, tables
type
Node = ref object
val: int
index: int
lowLink: int
onStack: bool
Nodes = seq[Node]
DirectedGraph = object
nodes: seq[Node]
edges: Table[int, Nodes]
func initNode(n: int): Node =
Node(val: n, index: -1, lowLink: -1, onStack: false)
func `$`(node: Node): string = $node.val
func tarjan(g: DirectedGraph): seq[Nodes] =
var index = 0
var s: seq[Node]
var sccs: seq[Nodes]
func strongConnect(v: Node) =
# Set the depth index for "v" to the smallest unused index.
v.index = index
v.lowLink = index
inc index
s.add v
v.onStack = true
# Consider successors of "v".
for w in g.edges[v.val]:
if w.index < 0:
# Successor "w" has not yet been visited; recurse on it.
w.strongConnect()
v.lowLink = min(v.lowLink, w.lowLink)
elif w.onStack:
# Successor "w" is in stack "s" and hence in the current SCC.
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:
var scc: Nodes
while true:
let w = s.pop()
w.onStack = false
scc.add w
if w == v: break
sccs.add scc
for v in g.nodes:
if v.index < 0:
v.strongConnect()
result = move(sccs)
when isMainModule:
let vs = toSeq(0..7).map(initNode)
let es = {0: @[vs[1]],
1: @[vs[2]],
2: @[vs[0]],
3: @[vs[1], vs[2], vs[4]],
4: @[vs[5], vs[3]],
5: @[vs[2], vs[6]],
6: @[vs[5]],
7: @[vs[4], vs[7], vs[6]]}.toTable
var g = DirectedGraph(nodes: vs, edges: es)
let sccs = g.tarjan()
echo sccs.join("\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.
| #Perl | Perl | use strict;
use warnings;
use feature <say state current_sub>;
use List::Util qw(min);
sub tarjan {
my (%k) = @_;
my (%onstack, %index, %lowlink, @stack, @connected);
my sub strong_connect {
my ($vertex, $i) = @_;
$index{$vertex} = $i;
$lowlink{$vertex} = $i + 1;
$onstack{$vertex} = 1;
push @stack, $vertex;
for my $connection (@{$k{$vertex}}) {
if (not defined $index{$connection}) {
__SUB__->($connection, $i + 1);
$lowlink{$vertex} = min($lowlink{$connection}, $lowlink{$vertex});
}
elsif ($onstack{$connection}) {
$lowlink{$vertex} = min($index{$connection}, $lowlink{$vertex});
}
}
if ($lowlink{$vertex} eq $index{$vertex}) {
my @node;
do {
push @node, pop @stack;
$onstack{$node[-1]} = 0;
} while $node[-1] ne $vertex;
push @connected, [@node];
}
}
for (sort keys %k) {
strong_connect($_, 0) unless $index{$_};
}
@connected;
}
my %test1 = (
0 => [1],
1 => [2],
2 => [0],
3 => [1, 2, 4],
4 => [3, 5],
5 => [2, 6],
6 => [5],
7 => [4, 6, 7]
);
my %test2 = (
'Andy' => ['Bart'],
'Bart' => ['Carl'],
'Carl' => ['Andy'],
'Dave' => [qw<Bart Carl Earl>],
'Earl' => [qw<Dave Fred>],
'Fred' => [qw<Carl Gary>],
'Gary' => ['Fred'],
'Hank' => [qw<Earl Gary Hank>]
);
print "Strongly connected components:\n";
print join(', ', sort @$_) . "\n" for tarjan(%test1);
print "\nStrongly connected components:\n";
print join(', ', sort @$_) . "\n" for tarjan(%test2); |
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
| #Lychen | Lychen |
const wc = new CS.System.Net.WebClient();
const lines = wc.DownloadString("http://wiki.puzzlers.org/pub/wordlists/unixdict.txt");
const words = lines.split(/\n/g);
const collection = {};
words.filter(word => word.length > 2).forEach(word => {
let allok = true;
let newword = word;
for (let i = 0; i < word.length - 1; i++) {
newword = newword.substr(1) + newword.substr(0, 1);
if (!words.includes(newword)) {
allok = false;
break;
}
}
if (allok) {
const key = word.split("").sort().join("");
if (!collection[key]) {
collection[key] = [word];
} else {
if (!collection[key].includes(word)) {
collection[key].push(word);
}
}
}
});
Object.keys(collection)
.filter(key => collection[key].length > 1)
.forEach(key => console.log("%s", collection[key].join(", ")));
|
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
| #Amazing_Hopper | Amazing Hopper |
/* MISTRAL - a flavour of Hopper */
#include <mistral.h>
INICIAR:
TAMAÑO DE MEMORIA 20
temperatura=0
RECIBIR PARÁMETRO NUMÉRICO(2), GUARDAR EN (temperatura);
TOMAR("KELVIN : ",temperatura, NL)
CON( "CELSIUS : ", temperatura ), CALCULAR( Conversión Kelvin a Celsius ), NUEVA LÍNEA
CON( "FAHRENHEIT : ", temperatura ), CALCULAR( Conversión Kelvin a Fahrenheit ), NUEVA LÍNEA
CON( "RANKINE : ", temperatura ), CALCULAR( Conversión Kelvin a Rankine ), NUEVA LÍNEA
IMPRIMIR CON SALTO
FINALIZAR
SUBRUTINAS
FUNCIÓN(Conversión Kelvin a Celsius, k)
REDONDEAR(RESTAR(k, 273.15), 2)
RETORNAR
FUNCIÓN( Conversión Kelvin a Fahrenheit, k)
REDONDEAR( {k} MULTIPLICADO POR(1.8) MENOS( 459.67), 2)
RETORNAR
FUNCIÓN( Conversión Kelvin a Rankine, k)
RETORNAR ( {k} POR (1.8), REDONDEADO AL DECIMAL(2) )
|
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
| #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 << "Count of divisors for the first " << limit << " positive integers:\n";
for (unsigned int n = 1; n <= limit; ++n) {
std::cout << std::setw(3) << divisor_count(n);
if (n % 20 == 0)
std::cout << '\n';
}
} |
http://rosettacode.org/wiki/Terminal_control/Clear_the_screen | Terminal control/Clear the screen | Task
Clear the terminal window.
| #Elena | Elena | public program()
{
console.clear()
} |
http://rosettacode.org/wiki/Terminal_control/Clear_the_screen | Terminal control/Clear the screen | Task
Clear the terminal window.
| #Erlang | Erlang |
clear()->io:format(os:cmd("clear")).
|
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
| #Haskell | Haskell | import Prelude hiding (Bool(..), not, (&&), (||), (==))
main = mapM_ (putStrLn . unlines . map unwords)
[ table "not" $ unary not
, table "and" $ binary (&&)
, table "or" $ binary (||)
, table "implies" $ binary (=->)
, table "equals" $ binary (==)
]
data Trit = False | Maybe | True deriving (Show)
False `nand` _ = True
_ `nand` False = True
True `nand` True = False
_ `nand` _ = Maybe
not a = nand a a
a && b = not $ a `nand` b
a || b = not a `nand` not b
a =-> b = a `nand` not b
a == b = (a && b) || (not a && not b)
inputs1 = [True, Maybe, False]
inputs2 = [(a,b) | a <- inputs1, b <- inputs1]
unary f = map (\a -> [a, f a]) inputs1
binary f = map (\(a,b) -> [a, b, f a b]) inputs2
table name xs = map (map pad) . (header :) $ map (map show) xs
where header = map (:[]) (take ((length $ head xs) - 1) ['A'..]) ++ [name]
pad s = s ++ replicate (5 - length s) ' ' |
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.
| #Julia | Julia |
using DataFrames
function mungdata(filename)
lines = readlines(filename)
numlines = length(lines)
dates = Array{DateTime, 1}(numlines)
means = zeros(Float64, numlines)
numvalid = zeros(Int, numlines)
invalidlength = zeros(Int, numlines)
invalidpos = zeros(Int, numlines)
datamatrix = Array{Float64,2}(numlines, 24)
datamatrix .= NaN
totalsum = 0.0
totalgood = 0
for (linenum,line) in enumerate(lines)
data = split(line)
validcount = badlength = 0
validsum = 0.0
for i in 2:2:length(data)-1
if parse(Int, data[i+1]) >= 0
validsum += (datamatrix[linenum, Int(i/2)] = parse(Float64, data[i]))
validcount += 1
badlength = 0
else
badlength += 1
if badlength > invalidlength[linenum]
invalidlength[linenum] = badlength
invalidpos[linenum] = Int(i/2) - invalidlength[linenum] + 1
end
end
end
dates[linenum] = DateTime(data[1], "y-m-d")
means[linenum] = validsum / validcount
numvalid[linenum] = validcount
totalsum += validsum
totalgood += validcount
end
dt = DataFrame(Date = dates, Mean = means, ValidValues = numvalid,
MaximumGap = invalidlength, GapPosition = invalidpos)
for i in 1:size(datamatrix)[2]
dt[Symbol("$(i-1):00")] = datamatrix[:,i]
end
dt, totalsum/totalgood
end
datafilename = "data.txt" # this is taken from the example listed on the task, since the actual text file is not available
df, dmean = mungdata(datafilename)
println(df)
println("The overall mean is $dmean")
maxbadline = indmax(df[:MaximumGap])
maxbadval = df[:MaximumGap][maxbadline]
maxbadtime = df[:GapPosition][maxbadline] - 1
maxbaddate = replace("$(df[:Date][maxbadline])", r"T.+$", "")
println("The largest run of bad values is $(maxbadval), on $(maxbaddate) beginning at $(maxbadtime):00 hours.")
|
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).
| #zkl | zkl | nOut,maxOut,maxTimes:=0,-1,List();
foreach job in (File("mlijobs.txt")){
_,status,_,date:=job.split();
nOut+=( if(status.toUpper()=="OUT") 1 else -1 );
if(nOut>maxOut){ maxOut=nOut; maxTimes.clear(); }
if(nOut==maxOut) maxTimes.append(date);
}
println(("Maximum simultaneous license use is %d at"
" the following times:\n %s").fmt(maxOut,maxTimes.concat("\n"))); |
http://rosettacode.org/wiki/Test_a_function | Test a function |
Task
Using a well-known testing-specific library/module/suite for your language, write some tests for your language's entry in Palindrome.
If your language does not have a testing specific library well known to the language's community then state this or omit the language.
| #SQL_PL | SQL PL |
CREATE OR REPLACE PROCEDURE TEST_MY_TEST()
BEGIN
DECLARE EXPECTED INTEGER;
DECLARE ACTUAL INTEGER;
CALL DB2UNIT.REGISTER_MESSAGE('My first test');
SET EXPECTED = 2;
SET ACTUAL = 1+1;
CALL DB2UNIT.ASSERT_INT_EQUALS('Same value', EXPECTED, ACTUAL);
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.
| #Swift | Swift | import Cocoa
import XCTest
class PalindromTests: XCTestCase {
override func setUp() {
super.setUp()
}
override func tearDown() {
super.tearDown()
}
func testPalindrome() {
// This is an example of a functional test case.
XCTAssert(isPalindrome("abcba"), "Pass")
XCTAssert(isPalindrome("aa"), "Pass")
XCTAssert(isPalindrome("a"), "Pass")
XCTAssert(isPalindrome(""), "Pass")
XCTAssert(isPalindrome("ab"), "Pass") // Fail
XCTAssert(isPalindrome("aa"), "Pass")
XCTAssert(isPalindrome("abcdba"), "Pass") // Fail
}
func testPalindromePerformance() {
// This is an example of a performance test case.
self.measureBlock() {
var _is = isPalindrome("abcba")
}
}
} |
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
| #FreeBASIC | FreeBASIC | ' version 10-01-2017
' compile with: fbc -s console
Dim As ULong d, r
Dim As String days(1 To ...) = { "first", "second", "third", "fourth", _
"fifth", "sixth", "seventh", "eighth", _
"ninth", "tenth", "eleventh", "twelfth" }
Dim As String gifts(1 To ...) = { "", " 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 d = 1 To 12
Print " On the " + days(d) + " day of Christmas"
Print " My true love gave to me:"
For r = d To 3 Step -1
Print gifts(r)
Next
' print " Two turtle doves" for the twelfth day and add "and" for the other days
If d > 1 Then
Print gifts(2); iif(d = 12, "", " and")
End If
' print "A partridge...", on the twelfth day print "And a partrige..."
Print " A" & IIf(d = 12, "nd a", "" ) & " partridge in a pear tree"
Print
Next
' empty keyboard buffer
While Inkey <> "" : Wend
Print : 'Print "hit any key to end program"
Sleep
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)
| #Lasso | Lasso | #!/usr/bin/lasso9
define ec(code::string) => {
local(esc = decode_base64('Gw=='))
local(codes = map('esc' = #esc,
'normal' = #esc + '[0m',
'blink' = #esc + '[5;31;49m',
'red' = #esc + '[31;49m',
'blue' = #esc + '[34;49m',
'green' = #esc + '[32;49m',
'magenta' = #esc + '[35;49m',
'yellowred' = #esc + '[33;41m'
))
return #codes -> find(#code)
}
stdout( ec('red'))
stdoutnl('So this is the Rosetta Code!')
stdout( ec('blue'))
stdoutnl('So this is the Rosetta Code!')
stdout( ec('green'))
stdoutnl('So this is the Rosetta Code!')
stdout( ec('magenta'))
stdoutnl('So this is the Rosetta Code!')
stdout( ec('yellowred'))
stdout('So this is the Rosetta Code!')
stdoutnl( ec('blink'))
stdoutnl('So this is the Rosetta Code!')
stdout( ec('normal'))
|
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)
| #Locomotive_Basic | Locomotive Basic | 10 mode 1:defint a-z
20 print "Mode 1 (4 colors):"
30 for y=0 to 3
40 for x=0 to 3
50 pen x:paper y:print "Test";
60 next
70 print
80 next
90 pen 1:paper 0
100 locate 1,25:print "<Press any key>";:call &bb06
110 ink 1,8,26
120 ink 2,21,17
130 locate 1,25:print "Flashing inks --- <Press any key>";:call &bb06
140 speed ink 8,3
150 locate 1,25:print "Different flashing --- <Press any key>";:call &bb06
160 ink 1,24:ink 2,20 ' back to defaults -- see chapter 1, page 50 in CPC manual
170 pen 1:paper 0:mode 0:speed ink 50,50
180 print "Mode 0 (16 colors):"
190 for i=0 to 15
200 pen i
210 if i=0 then paper 1 else paper 0
220 print using "##";i;
230 for j=1 to 18
240 print chr$(143);
250 next
260 next
270 pen 1:paper 0
280 print "Paper/pen 14 and 15"
290 print "are set to";
300 pen 14:print " flashing":pen 1
310 print "by default."
320 print
330 print "*End of color demo*"
340 locate 1,25:print "<Press any key>";:call &bb06
350 mode 1 |
http://rosettacode.org/wiki/Synchronous_concurrency | Synchronous concurrency | The goal of this task is to create two concurrent activities ("Threads" or "Tasks", not processes.) that share data synchronously. Your language may provide syntax or libraries to perform concurrency. Different languages provide different implementations of concurrency, often with different names. Some languages use the term threads, others use the term tasks, while others use co-processes. This task should not be implemented using fork, spawn, or the Linux/UNIX/Win32 pipe command, as communication should be between threads, not processes.
One of the concurrent units will read from a file named "input.txt" and send the contents of that file, one line at a time, to the other concurrent unit, which will print the line it receives to standard output. The printing unit must count the number of lines it prints. After the concurrent unit reading the file sends its last line to the printing unit, the reading unit will request the number of lines printed by the printing unit. The reading unit will then print the number of lines printed by the printing unit.
This task requires two-way communication between the concurrent units. All concurrent units must cleanly terminate at the end of the program.
| #Ada | Ada | package Synchronous_Concurrent is
task Printer is
entry Put(Item : in String);
entry Get_Count(Count : out Natural);
end Printer;
end Synchronous_Concurrent; |
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.
| #EchoLisp | EchoLisp |
(lib 'struct)
(lib 'sql)
(define Postal (make-table
(struct postal (auto: id name street city state zip))))
Postal
→ #table:#struct:postal [id name street city state zip]:[0]
(table-insert Postal '(0 Gallubert "29 rue de l'Ermitage" Paris Seine 75020))
(table-insert Postal '(0 Brougnard "666 rue des Cascades " Paris Seine 75042))
(table-make-index Postal 'postal.id)
(table-print Postal)
[0] 15 Gallubert 29 rue de l'Ermitage Paris Seine 75020
[1] 16 Brougnard 666 rue des Cascades Paris Seine 75042
|
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.
| #Erlang | Erlang |
-module( table_creation ).
-export( [task/0] ).
-record( address, {id, street, city, zip} ).
task() ->
mnesia:start(),
mnesia:create_table( address, [{attributes, record_info(fields, address)}] ).
|
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.
| #AWK | AWK |
# syntax: GAWK -f TAKE_NOTES.AWK [notes ... ]
# examples:
# GAWK -f TAKE_NOTES.AWK Hello world
# GAWK -f TAKE_NOTES.AWK A "B C" D
# GAWK -f TAKE_NOTES.AWK
BEGIN {
log_name = "NOTES.TXT"
(ARGC == 1) ? show_log() : update_log()
exit(0)
}
function show_log( rec) {
while (getline rec <log_name > 0) {
printf("%s\n",rec)
}
}
function update_log( i,q) {
print(strftime("%Y-%m-%d %H:%M:%S")) >>log_name
printf("\t") >>log_name
for (i=1; i<=ARGC-1; i++) {
q = (ARGV[i] ~ / /) ? "\"" : ""
printf("%s%s%s ",q,ARGV[i],q) >>log_name
}
printf("\n") >>log_name
}
|
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).
| #Delphi | Delphi |
(require '(heap compile))
(define (scube a b) (+ (* a a a) (* b b b)))
(compile 'scube "-f") ; "-f" means : no bigint, no rational used
;; is n - a^3 a cube b^3?
;; if yes return b, else #f
(define (taxi? n a (b 0))
(set! b (cbrt (- n (* a a a)))) ;; cbrt is ∛
(when (and (< b a) (integer? b)) b))
(compile 'taxi? "-f")
#|-------------------
looking for taxis
--------------------|#
;; remove from heap until heap-top >= a
;; when twins are removed, it is a taxicab number : push it
;; at any time (top stack) = last removed
(define (clean-taxi H limit: a min-of-heap: htop)
(when (and htop (> a htop))
(when (!= (stack-top S) htop) (pop S))
(push S htop)
(heap-pop H)
(clean-taxi H a (heap-top H))))
(compile 'clean-taxi "-f")
;; loop on a and b, b <=a , until n taxicabs found
(define (taxicab (n 2100))
(for ((a (in-naturals)))
(clean-taxi H (* a a a) (heap-top H))
#:break (> (stack-length S) n)
(for ((b a))
(heap-push H (scube a b)))))
#|------------------
printing taxis
---------------------|#
;; string of all decompositions
(define (taxi->string i n)
(string-append (format "%d. %d " (1+ i) n)
(for/string ((a (cbrt n)))
#:when (taxi? n a)
(format " = %4d^3 + %4d^3" a (taxi? n a)))))
(define (taxi-print taxis (nfrom 0) (nto 26))
(for ((i (in-naturals nfrom)) (taxi (sublist taxis nfrom nto)))
(writeln (taxi->string i (first taxi)))))
|
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
| #Frink | Frink | tau = {|x| x mod length[allFactors[x]] == 0}
println[formatTable[columnize[first[select[count[1], tau], 100], 10], "right"]] |
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
| #Go | Go | package main
import "fmt"
func countDivisors(n int) int {
count := 0
i := 1
k := 2
if n%2 == 0 {
k = 1
}
for i*i <= n {
if n%i == 0 {
count++
j := n / i
if j != i {
count++
}
}
i += k
}
return count
}
func main() {
fmt.Println("The first 100 tau numbers are:")
count := 0
i := 1
for count < 100 {
tf := countDivisors(i)
if i%tf == 0 {
fmt.Printf("%4d ", i)
count++
if count%10 == 0 {
fmt.Println()
}
}
i++
}
} |
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.
| #Phix | Phix | with javascript_semantics
constant g = {{2}, {3}, {1}, {2,3,5}, {6,4}, {3,7}, {6}, {5,8,7}}
sequence index, lowlink, stacked, stack
integer x
function strong_connect(integer n, emit)
index[n] = x
lowlink[n] = x
stacked[n] = 1
stack &= n
x += 1
for b=1 to length(g[n]) do
integer nb = g[n][b]
if index[nb] == 0 then
if not strong_connect(nb,emit) then
return false
end if
if lowlink[nb] < lowlink[n] then
lowlink[n] = lowlink[nb]
end if
elsif stacked[nb] == 1 then
if index[nb] < lowlink[n] then
lowlink[n] = index[nb]
end if
end if
end for
if lowlink[n] == index[n] then
sequence c = {}
while true do
integer w := stack[$]
stack = stack[1..$-1]
stacked[w] = 0
c = prepend(c, w)
if w == n then
emit(c)
exit
end if
end while
end if
return true
end function
procedure tarjan(sequence g, integer emit)
index = repeat(0,length(g))
lowlink = repeat(0,length(g))
stacked = repeat(0,length(g))
stack = {}
x = 1
for n=1 to length(g) do
if index[n] == 0
and not strong_connect(n,emit) then
return
end if
end for
end procedure
procedure emit(object c)
-- called for each component identified.
-- each component is a list of nodes.
?c
end procedure
tarjan(g,emit)
|
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
| #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | ClearAll[Teacuppable]
TeacuppableHelper[set_List] := Module[{f, s},
f = First[set];
s = StringRotateLeft[f, #] & /@ Range[Length[set]];
Sort[s] == Sort[set]
]
Teacuppable[set_List] := Module[{ss, l},
l = StringLength[First[set]];
ss = Subsets[set, {l}];
Select[ss, TeacuppableHelper]
]
s = Import["http://wiki.puzzlers.org/pub/wordlists/unixdict.txt", "String"];
s //= StringSplit[#, "\n"] &;
s //= Select[StringLength /* GreaterThan[2]];
s //= Map[ToLowerCase];
s //= Map[{#, Sort[Characters[#]]} &];
s //= GatherBy[#, Last] &;
s //= Select[Length /* GreaterEqualThan[2]];
s = s[[All, All, 1]];
s //= Select[StringLength[First[#]] <= Length[#] &];
Flatten[Teacuppable /@ s, 1] |
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
| #Nim | Nim | import sequtils, sets, sugar
let words = collect(initHashSet, for word in "unixdict.txt".lines: {word})
proc rotate(s: var string) =
let first = s[0]
for i in 1..s.high: s[i - 1] = s[i]
s[^1] = first
var result: seq[string]
for word in "unixdict.txt".lines:
if word.len >= 3:
block checkWord:
var w = word
for _ in 1..w.len:
w.rotate()
if w notin words or w in result:
# Not present in dictionary or already encountered.
break checkWord
if word.anyIt(it != word[0]):
# More then one letter.
result.add word
for word in result:
var w = word
stdout.write w
for _ in 2..w.len:
w.rotate()
stdout.write " → ", w
echo() |
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
| #APL | APL | CONVERT←{⍵,(⍵-273.15),(R-459.67),(R←⍵×9÷5)} |
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
| #CLU | CLU | tau = proc (n: int) returns (int)
total: int := 1
while n//2 = 0 do
total := total + 1
n := n/2
end
p: int := 3
while p*p <= n do
count: int := 1
while n//p = 0 do
count := count + 1
n := n/p
end
total := total * count
p := p+2
end
if n>1 then
total := total * 2
end
return(total)
end tau
start_up = proc ()
po: stream := stream$primary_output()
for n: int in int$from_to(1, 100) do
stream$putright(po, int$unparse(tau(n)), 3)
if n//20=0 then stream$putl(po, "") end
end
end start_up |
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
| #COBOL | COBOL | IDENTIFICATION DIVISION.
PROGRAM-ID. TAU-FUNCTION.
DATA DIVISION.
WORKING-STORAGE SECTION.
01 TAU-VARS.
03 TOTAL PIC 999.
03 N PIC 999.
03 FILLER REDEFINES N.
05 FILLER PIC 99.
05 FILLER PIC 9.
88 N-EVEN VALUES 0, 2, 4, 6, 8.
03 P PIC 999.
03 P-SQUARED PIC 999.
03 N-DIV-P PIC 999V999.
03 FILLER REDEFINES N-DIV-P.
05 NEXT-N PIC 999.
05 FILLER PIC 999.
88 DIVISIBLE VALUE ZERO.
03 F-COUNT PIC 999.
01 CONTROL-VARS.
03 I PIC 999.
01 OUT-VARS.
03 OUT-ITM PIC ZZ9.
03 OUT-STR PIC X(80) VALUE SPACES.
03 OUT-PTR PIC 99 VALUE 1.
PROCEDURE DIVISION.
BEGIN.
PERFORM SHOW-TAU VARYING I FROM 1 BY 1
UNTIL I IS GREATER THAN 100.
STOP RUN.
SHOW-TAU.
MOVE I TO N.
PERFORM TAU.
MOVE TOTAL TO OUT-ITM.
STRING OUT-ITM DELIMITED BY SIZE INTO OUT-STR
WITH POINTER OUT-PTR.
IF OUT-PTR IS EQUAL TO 61,
DISPLAY OUT-STR,
MOVE 1 TO OUT-PTR.
TAU.
MOVE 1 TO TOTAL.
PERFORM POWER-OF-2 UNTIL NOT N-EVEN.
MOVE ZERO TO P-SQUARED.
PERFORM ODD-FACTOR THRU ODD-FACTOR-LOOP
VARYING P FROM 3 BY 2
UNTIL P-SQUARED IS GREATER THAN N.
IF N IS GREATER THAN 1,
MULTIPLY 2 BY TOTAL.
POWER-OF-2.
ADD 1 TO TOTAL.
DIVIDE 2 INTO N.
ODD-FACTOR.
MULTIPLY P BY P GIVING P-SQUARED.
MOVE 1 TO F-COUNT.
ODD-FACTOR-LOOP.
DIVIDE N BY P GIVING N-DIV-P.
IF DIVISIBLE,
MOVE NEXT-N TO N,
ADD 1 TO F-COUNT,
GO TO ODD-FACTOR-LOOP.
MULTIPLY F-COUNT BY TOTAL. |
http://rosettacode.org/wiki/Terminal_control/Clear_the_screen | Terminal control/Clear the screen | Task
Clear the terminal window.
| #Euphoria | Euphoria | clear_screen() |
http://rosettacode.org/wiki/Terminal_control/Clear_the_screen | Terminal control/Clear the screen | Task
Clear the terminal window.
| #F.23 | F# | open System
Console.Clear() |
http://rosettacode.org/wiki/Terminal_control/Clear_the_screen | Terminal control/Clear the screen | Task
Clear the terminal window.
| #Forth | Forth | page |
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
| #Icon_and_Unicon | Icon and Unicon | $define TRUE 1
$define FALSE -1
$define UNKNOWN 0
invocable all
link printf
procedure main() # demonstrate ternary logic
ufunc := ["not3"]
bfunc := ["and3", "or3", "xor3", "eq3", "ifthen3"]
every f := !ufunc do { # display unary functions
printf("\nunary function=%s:\n",f)
every t1 := (TRUE | FALSE | UNKNOWN) do
printf(" %s : %s\n",showtrit(t1),showtrit(not3(t1)))
}
every f := !bfunc do { # display binary functions
printf("\nbinary function=%s:\n ",f)
every t1 := (&null | TRUE | FALSE | UNKNOWN) do {
printf(" %s : ",showtrit(\t1))
every t2 := (TRUE | FALSE | UNKNOWN | &null) do {
if /t1 then printf(" %s",showtrit(\t2)|"\n")
else printf(" %s",showtrit(f(t1,\t2))|"\n")
}
}
}
end
procedure showtrit(a) #: return printable trit of error if invalid
return case a of {TRUE:"T";FALSE:"F";UNKNOWN:"?";default:runerr(205,a)}
end
procedure istrit(a) #: return value of trit or error if invalid
return (TRUE|FALSE|UNKNOWN|runerr(205,a)) = a
end
procedure not3(a) #: not of trit or error if invalid
return FALSE * istrit(a)
end
procedure and3(a,b) #: and of two trits or error if invalid
return min(istrit(a),istrit(b))
end
procedure or3(a,b) #: or of two trits or error if invalid
return max(istrit(a),istrit(b))
end
procedure eq3(a,b) #: equals of two trits or error if invalid
return istrit(a) * istrit(b)
end
procedure ifthen3(a,b) #: if trit then trit or error if invalid
return case istrit(a) of { TRUE: istrit(b) ; UNKNOWN: or3(a,b); FALSE: TRUE }
end
procedure xor3(a,b) #: xor of two trits or error if invalid
return not3(eq3(a,b))
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.
| #Kotlin | Kotlin | // version 1.2.31
import java.io.File
fun main(args: Array<String>) {
val rx = Regex("""\s+""")
val file = File("readings.txt")
val fmt = "Line: %s Reject: %2d Accept: %2d Line_tot: %7.3f Line_avg: %7.3f"
var grandTotal = 0.0
var readings = 0
var date = ""
var run = 0
var maxRun = -1
var finishLine = ""
file.forEachLine { line ->
val fields = line.split(rx)
date = fields[0]
if (fields.size == 49) {
var accept = 0
var total = 0.0
for (i in 1 until fields.size step 2) {
if (fields[i + 1].toInt() >= 1) {
accept++
total += fields[i].toDouble()
if (run > maxRun) {
maxRun = run
finishLine = date
}
run = 0
}
else run++
}
grandTotal += total
readings += accept
println(fmt.format(date, 24 - accept, accept, total, total / accept))
}
else println("Line: $date does not have 49 fields and has been ignored")
}
if (run > maxRun) {
maxRun = run
finishLine = date
}
val average = grandTotal / readings
println("\nFile = ${file.name}")
println("Total = ${"%7.3f".format(grandTotal)}")
println("Readings = $readings")
println("Average = ${"%-7.3f".format(average)}")
println("\nMaximum run of $maxRun consecutive false readings")
println("ends at line starting with date: $finishLine")
} |
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.
| #Tailspin | Tailspin |
templates palindrome
[$...] -> #
when <=$(last..first:-1)> do '$...;' !
end palindrome
test 'palindrome filter'
assert 'rotor' -> palindrome <='rotor'> 'rotor is a palindrome'
assert ['rosetta' -> palindrome] <=[]> 'rosetta is not a palindrome'
end 'palindrome filter'
|
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.
| #Tcl | Tcl | package require tcltest 2
source palindrome.tcl; # Assume that this is what loads the implementation of ‘palindrome’
tcltest::test palindrome-1 {check for palindromicity} -body {
palindrome abcdedcba
} -result 1
tcltest::test palindrome-2 {check for non-palindromicity} -body {
palindrome abcdef
} -result 0
tcltest::test palindrome-3 {check for palindrome error} -body {
palindrome
} -returnCodes error -result "wrong # args: should be \"palindrome s\""
tcltest::cleanupTests |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.