task_url
stringlengths
30
116
task_name
stringlengths
2
86
task_description
stringlengths
0
14.4k
language_url
stringlengths
2
53
language_name
stringlengths
1
52
code
stringlengths
0
61.9k
http://rosettacode.org/wiki/Taxicab_numbers
Taxicab numbers
A   taxicab number   (the definition that is being used here)   is a positive integer that can be expressed as the sum of two positive cubes in more than one way. The first taxicab number is   1729,   which is: 13   +   123       and also 93   +   103. Taxicab numbers are also known as:   taxi numbers   taxi-cab numbers   taxi cab numbers   Hardy-Ramanujan numbers Task Compute and display the lowest 25 taxicab numbers (in numeric order, and in a human-readable format). For each of the taxicab numbers, show the number as well as it's constituent cubes. Extra credit Show the 2,000th taxicab number, and a half dozen more See also A001235: taxicab numbers on The On-Line Encyclopedia of Integer Sequences. Hardy-Ramanujan Number on MathWorld. taxicab number on MathWorld. taxicab number on Wikipedia   (includes the story on how taxi-cab numbers came to be called).
#Julia
Julia
using Printf, DataStructures, IterTools   function findtaxinumbers(nmax::Integer) cube2n = Dict{Int,Int}(x ^ 3 => x for x in 0:nmax) sum2cubes = DefaultDict{Int,Set{NTuple{2,Int}}}(Set{NTuple{2,Int}}) for ((c1, _), (c2, _)) in product(cube2n, cube2n) if c1 ≥ c2 push!(sum2cubes[c1 + c2], (cube2n[c1], cube2n[c2])) end end   taxied = collect((k, v) for (k, v) in sum2cubes if length(v) ≥ 2) return sort!(taxied, by = first) end taxied = findtaxinumbers(1200)   for (ith, (cube, set)) in zip(1:25, taxied[1:25]) @printf "%2i: %7i = %s\n" ith cube join(set, ", ") # println(ith, ": ", cube, " = ", join(set, ", ")) end println("...") for (ith, (cube, set)) in zip(2000:2006, taxied[2000:2006]) @printf "%-4i: %i = %s\n" ith cube join(set, ", ") end   # version 2 function findtaxinumbers(nmax::Integer) cubes, crev = collect(x ^ 3 for x in 1:nmax), Dict{Int,Int}() for (x, x3) in enumerate(cubes) crev[x3] = x end sums = collect(x + y for x in cubes for y in cubes if y < x) sort!(sums)   idx = 0 for i in 2:(endof(sums) - 1) if sums[i-1] != sums[i] && sums[i] == sums[i+1] idx += 1 if 25 < idx < 2000 || idx > 2006 continue end n, p = sums[i], NTuple{2,Int}[] for x in cubes n < 2x && break if haskey(crev, n - x) push!(p, (crev[x], crev[n - x])) end end @printf "%4d: %10d" idx n for x in p @printf(" = %4d ^ 3 + %4d ^ 3", x...) end println() end end end   findtaxinumbers(1200)
http://rosettacode.org/wiki/Superpermutation_minimisation
Superpermutation minimisation
A superpermutation of N different characters is a string consisting of an arrangement of multiple copies of those N different characters in which every permutation of those characters can be found as a substring. For example, representing the characters as A..Z, using N=2 we choose to use the first two characters 'AB'. The permutations of 'AB' are the two, (i.e. two-factorial), strings: 'AB' and 'BA'. A too obvious method of generating a superpermutation is to just join all the permutations together forming 'ABBA'. A little thought will produce the shorter (in fact the shortest) superpermutation of 'ABA' - it contains 'AB' at the beginning and contains 'BA' from the middle to the end. The "too obvious" method of creation generates a string of length N!*N. Using this as a yardstick, the task is to investigate other methods of generating superpermutations of N from 1-to-7 characters, that never generate larger superpermutations. Show descriptions and comparisons of algorithms used here, and select the "Best" algorithm as being the one generating shorter superpermutations. The problem of generating the shortest superpermutation for each N might be NP complete, although the minimal strings for small values of N have been found by brute -force searches. 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 Reference The Minimal Superpermutation Problem. by Nathaniel Johnston. oeis A180632 gives 0-5 as 0, 1, 3, 9, 33, 153. 6 is thought to be 872. Superpermutations - Numberphile. A video Superpermutations: the maths problem solved by 4chan - Standupmaths. A video of recent (2018) mathematical progress. New Superpermutations Discovered! Standupmaths & Numberphile.
#J
J
approxmin=:3 :0 seqs=. y{~(A.&i.~ !)#y r=.{.seqs seqs=.}.seqs while.#seqs do. for_n. i.-#y do. tail=. (-n){. r b=. tail -:"1 n{."1 seqs if. 1 e.b do. j=. b i.1 r=. r, n}.j{seqs seqs=. (<<<j) { seqs break. end. end. end. r )
http://rosettacode.org/wiki/Superpermutation_minimisation
Superpermutation minimisation
A superpermutation of N different characters is a string consisting of an arrangement of multiple copies of those N different characters in which every permutation of those characters can be found as a substring. For example, representing the characters as A..Z, using N=2 we choose to use the first two characters 'AB'. The permutations of 'AB' are the two, (i.e. two-factorial), strings: 'AB' and 'BA'. A too obvious method of generating a superpermutation is to just join all the permutations together forming 'ABBA'. A little thought will produce the shorter (in fact the shortest) superpermutation of 'ABA' - it contains 'AB' at the beginning and contains 'BA' from the middle to the end. The "too obvious" method of creation generates a string of length N!*N. Using this as a yardstick, the task is to investigate other methods of generating superpermutations of N from 1-to-7 characters, that never generate larger superpermutations. Show descriptions and comparisons of algorithms used here, and select the "Best" algorithm as being the one generating shorter superpermutations. The problem of generating the shortest superpermutation for each N might be NP complete, although the minimal strings for small values of N have been found by brute -force searches. 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 Reference The Minimal Superpermutation Problem. by Nathaniel Johnston. oeis A180632 gives 0-5 as 0, 1, 3, 9, 33, 153. 6 is thought to be 872. Superpermutations - Numberphile. A video Superpermutations: the maths problem solved by 4chan - Standupmaths. A video of recent (2018) mathematical progress. New Superpermutations Discovered! Standupmaths & Numberphile.
#Java
Java
import static java.util.stream.IntStream.rangeClosed;   public class Test { final static int nMax = 12;   static char[] superperm; static int pos; static int[] count = new int[nMax];   static int factSum(int n) { return rangeClosed(1, n) .map(m -> rangeClosed(1, m).reduce(1, (a, b) -> a * b)).sum(); }   static boolean r(int n) { if (n == 0) return false;   char c = superperm[pos - n]; if (--count[n] == 0) { count[n] = n; if (!r(n - 1)) return false; } superperm[pos++] = c; return true; }   static void superPerm(int n) { String chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";   pos = n; superperm = new char[factSum(n)];   for (int i = 0; i < n + 1; i++) count[i] = i; for (int i = 1; i < n + 1; i++) superperm[i - 1] = chars.charAt(i);   while (r(n)) { } }   public static void main(String[] args) { for (int n = 0; n < nMax; n++) { superPerm(n); System.out.printf("superPerm(%2d) len = %d", n, superperm.length); System.out.println(); } } }
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
#REXX
REXX
/*REXX pgm displays N tau numbers, an integer divisible by the # of its divisors). */ parse arg n cols . /*obtain optional argument from the CL.*/ if n=='' | n=="," then n= 100 /*Not specified? Then use the default.*/ if cols=='' | cols=="," then cols= 10 /*Not specified? Then use the default.*/ w= max(8, length(n) ) /*W: used to align 1st output column. */ @tau= ' the first ' commas(n) " tau numbers " /*the title of the tau numbers table. */ say ' index │'center(@tau, 1 + cols*(w+1) ) /*display the title of the output table*/ say '───────┼'center("" , 1 + cols*(w+1), '─') /* " " header " " " " */ idx= 1; #= 0; $= /*idx: line; #: tau numbers; $: #s */ do j=1 until #==n /*search for N tau numbers */ if j//tau(j) \==0 then iterate /*Is this a tau number? No, then skip.*/ #= # + 1 /*bump the count of tau numbers found. */ $= $ right( commas(j), w) /*add a tau number to the output list. */ if #//cols\==0 then iterate /*Not a multiple of cols? Don't show. */ say center(idx, 7)'│' substr($, 2) /*display partial list to the terminal.*/ idx= idx + cols; $= /*bump idx by number of cols; nullify $*/ end /*j*/   if $\=='' then say center(idx, 7)"│" substr($, 2) /*possible display residual output.*/ say '───────┴'center("" , 1 + cols*(w+1), '─') exit 0 /*stick a fork in it, we're all done. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ commas: parse arg ?; do jc=length(?)-3 to 1 by -3; ?=insert(',', ?, jc); end; return ? /*──────────────────────────────────────────────────────────────────────────────────────*/ tau: procedure; parse arg x 1 y /*X and $ are both set from the arg.*/ if x<6 then return 2 + (x==4) - (x==1) /*some low #s should be handled special*/ odd= x // 2 /*check if X is odd (remainder of 1).*/ if odd then do; #= 2; end /*Odd? Assume divisor count of 2. */ else do; #= 4; y= x % 2; end /*Even? " " " " 4. */ /* [↑] start with known number of divs*/ do j=3 for x%2-3 by 1+odd while j<y /*for odd number, skip even numbers. */ if x//j==0 then do /*if no remainder, then found a divisor*/ #= # + 2; y= x % j /*bump # of divisors; calculate limit.*/ if j>=y then do; #= # - 1; leave; end /*reached limit?*/ end /* ___ */ else if j*j>x then leave /*only divide up to √ x */ end /*j*/ /* [↑] this form of DO loop is faster.*/ return #
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
#C
C
#include <stdio.h> #include <stdlib.h>   double kelvinToCelsius(double k){ return k - 273.15; }   double kelvinToFahrenheit(double k){ return k * 1.8 - 459.67; }   double kelvinToRankine(double k){ return k * 1.8; } void convertKelvin(double kelvin) { printf("K %.2f\n", kelvin); printf("C %.2f\n", kelvinToCelsius(kelvin)); printf("F %.2f\n", kelvinToFahrenheit(kelvin)); printf("R %.2f", kelvinToRankine(kelvin)); }   int main(int argc, const char * argv[]) { if (argc > 1) { double kelvin = atof(argv[1]); convertKelvin(kelvin); } return 0; }
http://rosettacode.org/wiki/Tau_function
Tau function
Given a positive integer, count the number of its positive divisors. Task Show the result for the first   100   positive integers. Related task  Tau number
#Nim
Nim
import math, strutils   func divcount(n: Natural): Natural = for i in 1..sqrt(n.toFloat).int: if n mod i == 0: inc result if n div i != i: inc result   echo "Count of divisors for the first 100 positive integers:" for i in 1..100: stdout.write ($divcount(i)).align(3) if i mod 20 == 0: echo()
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
#PARI.2FGP
PARI/GP
vector(100,X,numdiv(X))
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
#Pascal
Pascal
program tauFunction(output);   type { name starts with `integer…` to facilitate sorting in documentation } integerPositive = 1..maxInt value 1; { the `value …` will initialize all variables to this value }   { returns Boolean value of the expression divisor ∣ dividend ----------- } function divides( protected divisor: integerPositive; protected dividend: integer ): Boolean; begin { in Pascal, function result variable has the same name as function } divides := dividend mod divisor = 0 end;   { returns τ(i) --------------------------------------------------------- } function tau(protected i: integerPositive): integerPositive; var count, potentialDivisor: integerPositive; begin { count is initialized to 1 and every number is divisible by one } for potentialDivisor := 2 to i do begin count := count + ord(divides(potentialDivisor, i)) end;   { in Pascal, there must be exactly one assignment to result variable } tau := count end;   { === MAIN ============================================================= } var i: integerPositive; f: string(6); begin for i := 1 to 100 do begin writeStr(f, 'τ(', i:1); writeLn(f:8, ') = ', tau(i):5) end end.
http://rosettacode.org/wiki/Terminal_control/Clear_the_screen
Terminal control/Clear the screen
Task Clear the terminal window.
#Phix
Phix
clear_screen()
http://rosettacode.org/wiki/Terminal_control/Clear_the_screen
Terminal control/Clear the screen
Task Clear the terminal window.
#PicoLisp
PicoLisp
(call 'clear)
http://rosettacode.org/wiki/Terminal_control/Clear_the_screen
Terminal control/Clear the screen
Task Clear the terminal window.
#Pike
Pike
int main() { Process.system("clear"); return 0; }
http://rosettacode.org/wiki/Terminal_control/Clear_the_screen
Terminal control/Clear the screen
Task Clear the terminal window.
#PowerShell
PowerShell
Clear-Host
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
#Nim
Nim
type Trit* = enum ttrue, tmaybe, tfalse   proc `$`*(a: Trit): string = case a of ttrue: "T" of tmaybe: "?" of tfalse: "F"   proc `not`*(a: Trit): Trit = case a of ttrue: tfalse of tmaybe: tmaybe of tfalse: ttrue   proc `and`*(a, b: Trit): Trit = const t: array[Trit, array[Trit, Trit]] = [ [ttrue, tmaybe, tfalse] , [tmaybe, tmaybe, tfalse] , [tfalse, tfalse, tfalse] ] t[a][b]   proc `or`*(a, b: Trit): Trit = const t: array[Trit, array[Trit, Trit]] = [ [ttrue, ttrue, ttrue] , [ttrue, tmaybe, tmaybe] , [ttrue, tmaybe, tfalse] ] t[a][b]   proc then*(a, b: Trit): Trit = const t: array[Trit, array[Trit, Trit]] = [ [ttrue, tmaybe, tfalse] , [ttrue, tmaybe, tmaybe] , [ttrue, ttrue, ttrue] ] t[a][b]   proc equiv*(a, b: Trit): Trit = const t: array[Trit, array[Trit, Trit]] = [ [ttrue, tmaybe, tfalse] , [tmaybe, tmaybe, tmaybe] , [tfalse, tmaybe, ttrue] ] t[a][b]     when isMainModule:   import strutils   for t in Trit: echo "Not ", t , ": ", not t   for op1 in Trit: for op2 in Trit: echo "$# and $#: $#".format(op1, op2, op1 and op2) echo "$# or $#: $#".format(op1, op2, op1 or op2) echo "$# then $#: $#".format(op1, op2, op1.then op2) echo "$# equiv $#: $#".format(op1, op2, op1.equiv op2)
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
#OCaml
OCaml
type trit = True | False | Maybe   let t_not = function | True -> False | False -> True | Maybe -> Maybe   let t_and a b = match (a,b) with | (True,True) -> True | (False,_) | (_,False) -> False | _ -> Maybe   let t_or a b = t_not (t_and (t_not a) (t_not b))   let t_eq a b = match (a,b) with | (True,True) | (False,False) -> True | (False,True) | (True,False) -> False | _ -> Maybe   let t_imply a b = t_or (t_not a) b   let string_of_trit = function | True -> "True" | False -> "False" | Maybe -> "Maybe"   let () = let values = [| True; Maybe; False |] in let f = string_of_trit in Array.iter (fun v -> Printf.printf "Not %s: %s\n" (f v) (f (t_not v))) values; print_newline (); let print op str = Array.iter (fun a -> Array.iter (fun b -> Printf.printf "%s %s %s: %s\n" (f a) str (f b) (f (op a b)) ) values ) values; print_newline () in print t_and "And"; print t_or "Or"; print t_imply "Then"; print t_eq "Equiv"; ;;
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.
#PowerShell
PowerShell
$file = '.\readings.txt' $lines = Get-Content $file # $args[0] $valid = $true $startDate = $currStart = $endDate = '' $startHour = $endHour = $currHour = $max = $currMax = $total = $readings = 0 $task = @() foreach ($var in $lines) { $date, $rest = [regex]::Split($var,'\s+') $reject = $accept = $sum = $cnt = 0 while ($rest) { $cnt += 1 [Double]$val, [Double]$flag, $rest = $rest if (0 -lt $flag) { $currMax = 0 $sum += $val $accept += 1 } else { if (0 -eq $currMax) { $currStart = $date $currHour = $cnt } $currMax += 1 $reject += 1 if ($max -lt $currMax) { $startDate, $endDate = $currStart, $date $startHour, $endHour = $currHour, $cnt $max = $currMax } } } $readings += $accept $total += $sum $average = if (0 -lt $accept) {$sum/$accept} else {0} $task += [PSCustomObject]@{ 'Line' = $date 'Reject' = $reject 'Accept' = $accept 'Sum' = $sum.ToString("N") 'Average' = $average.ToString("N3") } $valid = 0 -eq $reject } $task | Select -Last 3 $average = $total/$readings "File(s) = $file" "Total = {0}" -f $total.ToString("N") "Readings = $readings" "Average = {0}" -f $average.ToString("N3") "" "Maximum run(s) of $max consecutive false readings." if (0 -lt $max) { "Consecutive false readings starts at line starting with date $startDate at hour {0:0#}:00." -f $startHour "Consecutive false readings ends at line starting with date $endDate at hour {0:0#}:00." -f $endHour }
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
#Lua
Lua
  local days = { 'first', 'second', 'third', 'fourth', 'fifth', 'sixth', 'seventh', 'eighth', 'ninth', 'tenth', 'eleventh', 'twelfth', }   local gifts = { "A partridge in a pear tree", "Two turtle doves", "Three french hens", "Four calling birds", "Five golden rings", "Six geese a-laying", "Seven swans a-swimming", "Eight maids a-milking", "Nine ladies dancing", "Ten lords a-leaping", "Eleven pipers piping", "Twelve drummers drumming", }   local verses = {}   for i = 1, 12 do local lines = {} lines[1] = "On the " .. days[i] .. " day of Christmas, my true love gave to me"   local j = i local k = 2 repeat lines[k] = gifts[j] k = k + 1 j = j - 1 until j == 0   verses[i] = table.concat(lines, '\n') end   print(table.concat(verses, '\n\n'))  
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)
#Sidef
Sidef
var a = frequire('Term::ANSIColor');   say a.colored('RED ON WHITE', 'bold red on_white'); say a.colored('GREEN', 'bold green'); say a.colored('BLUE ON YELLOW', 'bold blue on_yellow'); say a.colored('MAGENTA', 'bold magenta'); say a.colored('CYAN ON RED', 'bold cyan on_red'); say a.colored('YELLOW', 'bold yellow');
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)
#Tcl
Tcl
# Utility interfaces to the low-level command proc capability cap {expr {![catch {exec tput -S << $cap}]}} proc colorterm {} {expr {[capability setaf] && [capability setab]}} proc tput args {exec tput -S << $args >/dev/tty} array set color {black 0 red 1 green 2 yellow 3 blue 4 magenta 5 cyan 6 white 7} proc foreground x {exec tput -S << "setaf $::color($x)" > /dev/tty} proc background x {exec tput -S << "setab $::color($x)" > /dev/tty} proc reset {} {exec tput sgr0 > /dev/tty}   # Demonstration of use if {[colorterm]} { foreground blue background yellow puts "Color output" reset } else { puts "Monochrome only" }   if {[capability blink]} { tput blink puts "Blinking output" reset } else { puts "Steady only" }
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.
#F.23
F#
  open System.IO   type Msg = | PrintLine of string | GetCount of AsyncReplyChannel<int>   let printer = MailboxProcessor.Start(fun inbox -> let rec loop count = async { let! msg = inbox.Receive() match msg with | PrintLine(s) -> printfn "%s" s return! loop (count + 1) | GetCount(reply) -> reply.Reply(count) return! loop count } loop 0 )   let reader (printAgent:MailboxProcessor<Msg>) file = File.ReadLines(file) |> Seq.iter (fun line -> PrintLine line |> printAgent.Post) printAgent.PostAndReply(fun reply -> GetCount(reply)) |> printfn "Lines written: %i"   reader printer @"c:\temp\input.txt"  
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.
#Run_BASIC
Run BASIC
sqliteconnect #mem, ":memory:" ' make handle #mem mem$ = " CREATE TABLE address ( addrID INTEGER PRIMARY KEY AUTOINCREMENT, addrStreet TEXT NOT NULL, addrCity TEXT NOT NULL, addrState TEXT NOT NULL, addrZIP TEXT NOT NULL )" #mem execute(mem$)
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.
#SAS
SAS
    PROC SQL; CREATE TABLE ADDRESS ( ADDRID CHAR(8) ,STREET CHAR(50) ,CITY CHAR(25) ,STATE CHAR(2) ,ZIP CHAR(20) ) ;QUIT;  
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.
#Scheme
Scheme
  (use sql-de-lite)   (define *db* (open-database "addresses"))   (exec ; create and run the SQL statement (sql *db* "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-database *db*) ; finally, close database  
http://rosettacode.org/wiki/System_time
System time
Task Output the system time   (any units will do as long as they are noted) either by a system command or one built into the language. The system time can be used for debugging, network information, random number seeds, or something as simple as program performance. Related task   Date format See also   Retrieving system time (wiki)
#Ada
Ada
with Ada.Calendar; use Ada.Calendar; with Ada.Calendar.Formatting; use Ada.Calendar.Formatting; with Ada.Calendar.Time_Zones; use Ada.Calendar.Time_Zones; with Ada.Text_Io; use Ada.Text_Io;   procedure System_Time is Now : Time := Clock; begin Put_line(Image(Date => Now, Time_Zone => -7*60)); end System_Time;
http://rosettacode.org/wiki/System_time
System time
Task Output the system time   (any units will do as long as they are noted) either by a system command or one built into the language. The system time can be used for debugging, network information, random number seeds, or something as simple as program performance. Related task   Date format See also   Retrieving system time (wiki)
#Aime
Aime
date d;   d_now(d);   o_form("~-/f2/-/f2/ /f2/:/f2/:/f2/\n", d_year(d), d_y_month(d), d_m_day(d), d_d_hour(d), d_h_minute(d), d_m_second(d));
http://rosettacode.org/wiki/Summarize_and_say_sequence
Summarize and say sequence
There are several ways to generate a self-referential sequence. One very common one (the Look-and-say sequence) is to start with a positive integer, then generate the next term by concatenating enumerated groups of adjacent alike digits: 0, 10, 1110, 3110, 132110, 1113122110, 311311222110 ... The terms generated grow in length geometrically and never converge. Another way to generate a self-referential sequence is to summarize the previous term. Count how many of each alike digit there is, then concatenate the sum and digit for each of the sorted enumerated digits. Note that the first five terms are the same as for the previous sequence. 0, 10, 1110, 3110, 132110, 13123110, 23124110 ... Sort the digits largest to smallest. Do not include counts of digits that do not appear in the previous term. Depending on the seed value, series generated this way always either converge to a stable value or to a short cyclical pattern. (For our purposes, I'll use converge to mean an element matches a previously seen element.) The sequence shown, with a seed value of 0, converges to a stable value of 1433223110 after 11 iterations. The seed value that converges most quickly is 22. It goes stable after the first element. (The next element is 22, which has been seen before.) Task Find all the positive integer seed values under 1000000, for the above convergent self-referential sequence, that takes the largest number of iterations before converging. Then print out the number of iterations and the sequence they return. Note that different permutations of the digits of the seed will yield the same sequence. For this task, assume leading zeros are not permitted. Seed Value(s): 9009 9090 9900 Iterations: 21 Sequence: (same for all three seeds except for first element) 9009 2920 192210 19222110 19323110 1923123110 1923224110 191413323110 191433125110 19151423125110 19251413226110 1916151413325110 1916251423127110 191716151413326110 191726151423128110 19181716151413327110 19182716151423129110 29181716151413328110 19281716151423228110 19281716151413427110 19182716152413228110 Related tasks   Fours is the number of letters in the ...   Look-and-say sequence   Number names   Self-describing numbers   Spelling of ordinal numbers Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet Also see   The On-Line Encyclopedia of Integer Sequences.
#Aime
Aime
text next(text s) { integer c, e, l; index v; data d;   l = ~s; while (l) { v[-s[l -= 1]] += 1; }   for (c, e in v) { b_form(d, "%d%c", e, -c); }   return d; }   integer depth(text s, integer i, record r) { integer d;   d = 0; r_j_integer(d, r, s); if (d <= 0) { i += 1; d += d ? i : -i; r[s] = d; i = depth(next(s), i, r); d = r[s]; if (d <= 0) { r[s] = d = i + 1; } }   return d; }   integer main(void) { integer d, e, i; record r; list l;   d = 0; i = 1000000; while (i) { i -= 1; e = depth(itoa(i), 0, r); if (e == d) { lb_p_integer(l, i); } elif (d < e) { d = e; l_clear(l); lb_p_integer(l, i); } }   o_("longest length is ", d, "\n"); while (l_o_integer(i, l, 0)) { text s;   o_("\n", i, "\n"); e = d - 1; s = itoa(i); while (e) { o_(s = next(s), "\n"); e -= 1; } }   return 0; }
http://rosettacode.org/wiki/Summarize_primes
Summarize primes
Task Considering in order of length, n, all sequences of consecutive primes, p, from 2 onwards, where p < 1000 and n>0, select those sequences whose sum is prime, and for these display the length of the sequence, the last item in the sequence, and the sum.
#Arturo
Arturo
print (pad "index" 6) ++ " | " ++ (pad "prime" 6) ++ " | " ++ (pad "prime sum" 11) print "------------------------------"   s: 0 idx: 0 loop 2..999 'n [ if prime? n [ idx: idx + 1 s: s + n if prime? s -> print (pad to :string idx 6) ++ " | " ++ (pad to :string n 6) ++ " | " ++ (pad to :string s 11) ] ]
http://rosettacode.org/wiki/Summarize_primes
Summarize primes
Task Considering in order of length, n, all sequences of consecutive primes, p, from 2 onwards, where p < 1000 and n>0, select those sequences whose sum is prime, and for these display the length of the sequence, the last item in the sequence, and the sum.
#AWK
AWK
  # syntax: GAWK -f SUMMARIZE_PRIMES.AWK BEGIN { start = 1 stop = 999 for (i=start; i<=stop; i++) { if (is_prime(i)) { count1++ sum += i if (is_prime(sum)) { printf("the sum of %3d primes from primes 2-%-3s is %5d which is also prime\n",count1,i,sum) count2++ } } } printf("Summarized primes %d-%d: %d\n",start,stop,count2) exit(0) } function is_prime(x, i) { if (x <= 1) { return(0) } for (i=2; i<=int(sqrt(x)); i++) { if (x % i == 0) { return(0) } } return(1) }  
http://rosettacode.org/wiki/Sutherland-Hodgman_polygon_clipping
Sutherland-Hodgman polygon clipping
The   Sutherland-Hodgman clipping algorithm   finds the polygon that is the intersection between an arbitrary polygon (the “subject polygon”) and a convex polygon (the “clip polygon”). It is used in computer graphics (especially 2D graphics) to reduce the complexity of a scene being displayed by eliminating parts of a polygon that do not need to be displayed. Task Take the closed polygon defined by the points: [ ( 50 , 150 ) , ( 200 , 50 ) , ( 350 , 150 ) , ( 350 , 300 ) , ( 250 , 300 ) , ( 200 , 250 ) , ( 150 , 350 ) , ( 100 , 250 ) , ( 100 , 200 ) ] {\displaystyle [(50,150),(200,50),(350,150),(350,300),(250,300),(200,250),(150,350),(100,250),(100,200)]} and clip it by the rectangle defined by the points: [ ( 100 , 100 ) , ( 300 , 100 ) , ( 300 , 300 ) , ( 100 , 300 ) ] {\displaystyle [(100,100),(300,100),(300,300),(100,300)]} Print the sequence of points that define the resulting clipped polygon. Extra credit Display all three polygons on a graphical surface, using a different color for each polygon and filling the resulting polygon. (When displaying you may use either a north-west or a south-west origin, whichever is more convenient for your display mechanism.)
#Elixir
Elixir
defmodule SutherlandHodgman do defp inside(cp1, cp2, p), do: (cp2.x-cp1.x)*(p.y-cp1.y) > (cp2.y-cp1.y)*(p.x-cp1.x)   defp intersection(cp1, cp2, s, e) do {dcx, dcy} = {cp1.x-cp2.x, cp1.y-cp2.y} {dpx, dpy} = {s.x-e.x, s.y-e.y} n1 = cp1.x*cp2.y - cp1.y*cp2.x n2 = s.x*e.y - s.y*e.x n3 = 1.0 / (dcx*dpy - dcy*dpx)  %{x: (n1*dpx - n2*dcx) * n3, y: (n1*dpy - n2*dcy) * n3} end   def polygon_clipping(subjectPolygon, clipPolygon) do Enum.chunk([List.last(clipPolygon) | clipPolygon], 2, 1) |> Enum.reduce(subjectPolygon, fn [cp1,cp2],acc -> Enum.chunk([List.last(acc) | acc], 2, 1) |> Enum.reduce([], fn [s,e],outputList -> case {inside(cp1, cp2, e), inside(cp1, cp2, s)} do {true, true} -> [e | outputList] {true, false} -> [e, intersection(cp1,cp2,s,e) | outputList] {false, true} -> [intersection(cp1,cp2,s,e) | outputList] _ -> outputList end end) |> Enum.reverse end) end end   subjectPolygon = [[50, 150], [200, 50], [350, 150], [350, 300], [250, 300], [200, 250], [150, 350], [100, 250], [100, 200]] |> Enum.map(fn [x,y] -> %{x: x, y: y} end)   clipPolygon = [[100, 100], [300, 100], [300, 300], [100, 300]] |> Enum.map(fn [x,y] -> %{x: x, y: y} end)   SutherlandHodgman.polygon_clipping(subjectPolygon, clipPolygon) |> Enum.each(&IO.inspect/1)
http://rosettacode.org/wiki/Sutherland-Hodgman_polygon_clipping
Sutherland-Hodgman polygon clipping
The   Sutherland-Hodgman clipping algorithm   finds the polygon that is the intersection between an arbitrary polygon (the “subject polygon”) and a convex polygon (the “clip polygon”). It is used in computer graphics (especially 2D graphics) to reduce the complexity of a scene being displayed by eliminating parts of a polygon that do not need to be displayed. Task Take the closed polygon defined by the points: [ ( 50 , 150 ) , ( 200 , 50 ) , ( 350 , 150 ) , ( 350 , 300 ) , ( 250 , 300 ) , ( 200 , 250 ) , ( 150 , 350 ) , ( 100 , 250 ) , ( 100 , 200 ) ] {\displaystyle [(50,150),(200,50),(350,150),(350,300),(250,300),(200,250),(150,350),(100,250),(100,200)]} and clip it by the rectangle defined by the points: [ ( 100 , 100 ) , ( 300 , 100 ) , ( 300 , 300 ) , ( 100 , 300 ) ] {\displaystyle [(100,100),(300,100),(300,300),(100,300)]} Print the sequence of points that define the resulting clipped polygon. Extra credit Display all three polygons on a graphical surface, using a different color for each polygon and filling the resulting polygon. (When displaying you may use either a north-west or a south-west origin, whichever is more convenient for your display mechanism.)
#Fortran
Fortran
    module SutherlandHodgmanUtil ! functions and type needed for Sutherland-Hodgman algorithm   ! -------------------------------------------------------- ! type polygon !type for polygons ! when you define a polygon, the first and the last vertices have to be the same integer :: n double precision, dimension(:,:), allocatable :: vertex end type polygon   contains   ! -------------------------------------------------------- ! subroutine sutherlandHodgman( ref, clip, outputPolygon ) ! Sutherland Hodgman algorithm for 2d polygons   ! -- parameters of the subroutine -- type(polygon) :: ref, clip, outputPolygon   ! -- variables used is the subroutine type(polygon) :: workPolygon ! polygon clipped step by step double precision, dimension(2) :: y1,y2 ! vertices of edge to clip workPolygon integer :: i   ! allocate workPolygon with the maximal possible size ! the sum of the size of polygon ref and clip allocate(workPolygon%vertex( ref%n+clip%n , 2 ))   ! initialise the work polygon with clip workPolygon%n = clip%n workPolygon%vertex(1:workPolygon%n,:) = clip%vertex(1:workPolygon%n,:)   do i=1,ref%n-1 ! for each edge i of the polygon ref y1(:) = ref%vertex(i,:) ! vertex 1 of edge i y2(:) = ref%vertex(i+1,:) ! vertex 2 of edge i   ! clip the work polygon by edge i call edgeClipping( workPolygon, y1, y2, outputPolygon) ! workPolygon <= outputPolygon workPolygon%n = outputPolygon%n workPolygon%vertex(1:workPolygon%n,:) = outputPolygon%vertex(1:workPolygon%n,:)   end do deallocate(workPolygon%vertex) end subroutine sutherlandHodgman   ! -------------------------------------------------------- ! subroutine edgeClipping( poly, y1, y2, outputPoly ) ! make the clipping of the polygon by the line (x1x2)   type(polygon) :: poly, outputPoly double precision, dimension(2) :: y1, y2, x1, x2, intersecPoint integer :: i, c   c = 0 ! counter for the output polygon   do i=1,poly%n-1 ! for each edge i of poly x1(:) = poly%vertex(i,:) ! vertex 1 of edge i x2(:) = poly%vertex(i+1,:) ! vertex 2 of edge i   if ( inside(x1, y1, y2) ) then ! if vertex 1 in inside clipping region if ( inside(x2, y1, y2) ) then ! if vertex 2 in inside clipping region ! add the vertex 2 to the output polygon c = c+1 outputPoly%vertex(c,:) = x2(:)   else ! vertex i+1 is outside intersecPoint = intersection(x1, x2, y1,y2) c = c+1 outputPoly%vertex(c,:) = intersecPoint(:) end if else ! vertex i is outside if ( inside(x2, y1, y2) ) then intersecPoint = intersection(x1, x2, y1,y2) c = c+1 outputPoly%vertex(c,:) = intersecPoint(:)   c = c+1 outputPoly%vertex(c,:) = x2(:) end if end if end do   if (c .gt. 0) then ! if the last vertice is not equal to the first one if ( (outputPoly%vertex(1,1) .ne. outputPoly%vertex(c,1)) .or. & (outputPoly%vertex(1,2) .ne. outputPoly%vertex(c,2))) then c=c+1 outputPoly%vertex(c,:) = outputPoly%vertex(1,:) end if end if ! set the size of the outputPolygon outputPoly%n = c end subroutine edgeClipping   ! -------------------------------------------------------- ! function intersection( x1, x2, y1, y2) ! computes the intersection between segment [x1x2] ! and line the line (y1y2)   ! -- parameters of the function -- double precision, dimension(2) :: x1, x2, & ! points of the segment y1, y2 ! points of the line   double precision, dimension(2) :: intersection, vx, vy, x1y1 double precision :: a   vx(:) = x2(:) - x1(:) vy(:) = y2(:) - y1(:)   ! if the vectors are colinear if ( crossProduct(vx,vy) .eq. 0.d0) then x1y1(:) = y1(:) - x1(:) ! if the the segment [x1x2] is included in the line (y1y2) if ( crossProduct(x1y1,vx) .eq. 0.d0) then ! the intersection is the last point of the segment intersection(:) = x2(:) end if else ! the vectors are not colinear ! we want to find the inersection between [x1x2] ! and (y1,y2). ! mathematically, we want to find a in [0;1] such ! that : ! x1 + a vx = y1 + b vy ! <=> a vx = x1y1 + b vy ! <=> a vx^vy = x1y1^vy , ^ is cross product ! <=> a = x1y1^vy / vx^vy   x1y1(:) = y1(:) - x1(:) ! we compute a a = crossProduct(x1y1,vy)/crossProduct(vx,vy) ! if a is not in [0;1] if ( (a .gt. 1.d0) .or. (a .lt. 0)) then ! no intersection else intersection(:) = x1(:) + a*vx(:) end if end if   end function intersection     ! -------------------------------------------------------- ! function inside( p, y1, y2) ! function that tells is the point p is at left of the line (y1y2)   double precision, dimension(2) :: p, y1, y2, v1, v2 logical :: inside v1(:) = y2(:) - y1(:) v2(:) = p(:) - y1(:) if ( crossProduct(v1,v2) .ge. 0.d0) then inside = .true. else inside = .false. end if   contains end function inside   ! -------------------------------------------------------- ! function dotProduct( v1, v2) ! compute the dot product of vectors v1 and v2 double precision, dimension(2) :: v1 double precision, dimension(2) :: v2 double precision :: dotProduct dotProduct = v1(1)*v2(1) + v1(2)*v2(2) end function dotProduct   ! -------------------------------------------------------- ! function crossProduct( v1, v2) ! compute the crossproduct of vectors v1 and v2 double precision, dimension(2) :: v1 double precision, dimension(2) :: v2 double precision :: crossProduct crossProduct = v1(1)*v2(2) - v1(2)*v2(1) end function crossProduct   end module SutherlandHodgmanUtil   program main   ! load the module for S-H algorithm use SutherlandHodgmanUtil, only : polygon, & sutherlandHodgman, & edgeClipping   type(polygon) :: p1, p2, res integer :: c, n double precision, dimension(2) :: y1, y2   ! when you define a polygon, the first and the last vertices have to be the same   ! first polygon p1%n = 10 allocate(p1%vertex(p1%n,2)) p1%vertex(1,1)=50.d0 p1%vertex(1,2)=150.d0   p1%vertex(2,1)=200.d0 p1%vertex(2,2)=50.d0   p1%vertex(3,1)= 350.d0 p1%vertex(3,2)= 150.d0   p1%vertex(4,1)= 350.d0 p1%vertex(4,2)= 300.d0   p1%vertex(5,1)= 250.d0 p1%vertex(5,2)= 300.d0   p1%vertex(6,1)= 200.d0 p1%vertex(6,2)= 250.d0   p1%vertex(7,1)= 150.d0 p1%vertex(7,2)= 350.d0   p1%vertex(8,1)= 100.d0 p1%vertex(8,2)= 250.d0   p1%vertex(9,1)= 100.d0 p1%vertex(9,2)= 200.d0   p1%vertex(10,1)= 50.d0 p1%vertex(10,2)= 150.d0   y1 = (/ 100.d0, 300.d0 /) y2 = (/ 300.d0, 300.d0 /)   ! second polygon p2%n = 5 allocate(p2%vertex(p2%n,2))   p2%vertex(1,1)= 100.d0 p2%vertex(1,2)= 100.d0   p2%vertex(2,1)= 300.d0 p2%vertex(2,2)= 100.d0   p2%vertex(3,1)= 300.d0 p2%vertex(3,2)= 300.d0   p2%vertex(4,1)= 100.d0 p2%vertex(4,2)= 300.d0   p2%vertex(5,1)= 100.d0 p2%vertex(5,2)= 100.d0   allocate(res%vertex(p1%n+p2%n,2)) call sutherlandHodgman( p2, p1, res) write(*,*) "Suterland-Hodgman" do c=1, res%n write(*,*) res%vertex(c,1), res%vertex(c,2) end do deallocate(res%vertex)   end program main    
http://rosettacode.org/wiki/Symmetric_difference
Symmetric difference
Task Given two sets A and B, compute ( A ∖ B ) ∪ ( B ∖ A ) . {\displaystyle (A\setminus B)\cup (B\setminus A).} That is, enumerate the items that are in A or B but not both. This set is called the symmetric difference of A and B. In other words: ( A ∪ B ) ∖ ( A ∩ B ) {\displaystyle (A\cup B)\setminus (A\cap B)} (the set of items that are in at least one of A or B minus the set of items that are in both A and B). Optionally, give the individual differences ( A ∖ B {\displaystyle A\setminus B} and B ∖ A {\displaystyle B\setminus A} ) as well. Test cases A = {John, Bob, Mary, Serena} B = {Jim, Mary, John, Bob} Notes If your code uses lists of items to represent sets then ensure duplicate items in lists are correctly handled. For example two lists representing sets of a = ["John", "Serena", "Bob", "Mary", "Serena"] and b = ["Jim", "Mary", "John", "Jim", "Bob"] should produce the result of just two strings: ["Serena", "Jim"], in any order. In the mathematical notation above A \ B gives the set of items in A that are not in B; A ∪ B gives the set of items in both A and B, (their union); and A ∩ B gives the set of items that are in both A and B (their intersection).
#AWK
AWK
  # syntax: GAWK -f SYMMETRIC_DIFFERENCE.AWK BEGIN { load("John,Bob,Mary,Serena",A) load("Jim,Mary,John,Bob",B) show("A \\ B",A,B) show("B \\ A",B,A) printf("symmetric difference: ") for (i in C) { if (!(i in A && i in B)) { printf("%s ",i) } } printf("\n") exit(0) } function load(str,arr, i,n,temp) { n = split(str,temp,",") for (i=1; i<=n; i++) { arr[temp[i]] C[temp[i]] } } function show(str,a,b, i) { printf("%s: ",str) for (i in a) { if (!(i in b)) { printf("%s ",i) } } printf("\n") }  
http://rosettacode.org/wiki/Super-d_numbers
Super-d numbers
A super-d number is a positive, decimal (base ten) integer   n   such that   d × nd   has at least   d   consecutive digits   d   where 2 ≤ d ≤ 9 For instance, 753 is a super-3 number because 3 × 7533 = 1280873331. Super-d   numbers are also shown on   MathWorld™   as   super-d   or   super-d. Task Write a function/procedure/routine to find super-d numbers. For   d=2   through   d=6,   use the routine to show the first   10   super-d numbers. Extra credit Show the first   10   super-7, super-8, and/or super-9 numbers   (optional). See also   Wolfram MathWorld - Super-d Number.   OEIS: A014569 - Super-3 Numbers.
#J
J
superD=: 1 e. #~@[ E. 10 #.inv ([ * ^~)&x: assert 3 superD 753 assert -. 2 superD 753 2 3 4 5 6 ,. _ 10 {. I. 2 3 4 5 6 superD&>/i.1e6 2 19 31 69 81 105 106 107 119 127 131 3 261 462 471 481 558 753 1036 1046 1471 1645 4 1168 4972 7423 7752 8431 10267 11317 11487 11549 11680 5 4602 5517 7539 12955 14555 20137 20379 26629 32767 35689 6 27257 272570 302693 323576 364509 502785 513675 537771 676657 678146
http://rosettacode.org/wiki/Super-d_numbers
Super-d numbers
A super-d number is a positive, decimal (base ten) integer   n   such that   d × nd   has at least   d   consecutive digits   d   where 2 ≤ d ≤ 9 For instance, 753 is a super-3 number because 3 × 7533 = 1280873331. Super-d   numbers are also shown on   MathWorld™   as   super-d   or   super-d. Task Write a function/procedure/routine to find super-d numbers. For   d=2   through   d=6,   use the routine to show the first   10   super-d numbers. Extra credit Show the first   10   super-7, super-8, and/or super-9 numbers   (optional). See also   Wolfram MathWorld - Super-d Number.   OEIS: A014569 - Super-3 Numbers.
#Java
Java
  import java.math.BigInteger;   public class SuperDNumbers {   public static void main(String[] args) { for ( int i = 2 ; i <= 9 ; i++ ) { superD(i, 10); } }   private static final void superD(int d, int max) { long start = System.currentTimeMillis(); String test = ""; for ( int i = 0 ; i < d ; i++ ) { test += (""+d); }   int n = 0; int i = 0; System.out.printf("First %d super-%d numbers: %n", max, d); while ( n < max ) { i++; BigInteger val = BigInteger.valueOf(d).multiply(BigInteger.valueOf(i).pow(d)); if ( val.toString().contains(test) ) { n++; System.out.printf("%d ", i); } } long end = System.currentTimeMillis(); System.out.printf("%nRun time %d ms%n%n", end-start);   }   }  
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.
#Factor
Factor
#! /usr/bin/env factor USING: kernel calendar calendar.format io io.encodings.utf8 io.files sequences command-line namespaces ;   command-line get [ "notes.txt" utf8 file-contents print ] [ " " join "\t" prepend "notes.txt" utf8 [ now timestamp>ymdhms print print flush ] with-file-appender ] if-empty
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.
#Fantom
Fantom
  class Notes { public static Void main (Str[] args) { notesFile := File(`notes.txt`) // the backticks make a URI if (args.isEmpty) { if (notesFile.exists) { notesFile.eachLine |line| { echo (line) } } } else { // notice the following uses a block so the 'printLine/close' // operations are all applied to the same output stream for notesFile notesFile.out(true) // 'true' to append to file { printLine ( DateTime.now.toLocale("DD-MM-YY hh:mm:ss").toStr ) printLine ( "\t" + args.join(" ") ) close } } } }  
http://rosettacode.org/wiki/Superellipse
Superellipse
A superellipse is a geometric figure defined as the set of all points (x, y) with | x a | n + | y b | n = 1 , {\displaystyle \left|{\frac {x}{a}}\right|^{n}\!+\left|{\frac {y}{b}}\right|^{n}\!=1,} where n, a, and b are positive numbers. Task Draw a superellipse with n = 2.5, and a = b = 200
#Go
Go
package main   import ( "github.com/fogleman/gg" "math" )   /* assumes a and b are always equal */ func superEllipse(dc *gg.Context, n float64, a int) { hw := float64(dc.Width() / 2) hh := float64(dc.Height() / 2)   // calculate y for each x y := make([]float64, a+1) for x := 0; x <= a; x++ { aa := math.Pow(float64(a), n) xx := math.Pow(float64(x), n) y[x] = math.Pow(aa-xx, 1.0/n) }   // draw quadrants for x := a; x >= 0; x-- { dc.LineTo(hw+float64(x), hh-y[x]) } for x := 0; x <= a; x++ { dc.LineTo(hw+float64(x), hh+y[x]) } for x := a; x >= 0; x-- { dc.LineTo(hw-float64(x), hh+y[x]) } for x := 0; x <= a; x++ { dc.LineTo(hw-float64(x), hh-y[x]) }   dc.SetRGB(1, 1, 1) // white ellipse dc.Fill() }   func main() { dc := gg.NewContext(500, 500) dc.SetRGB(0, 0, 0) // black background dc.Clear() superEllipse(dc, 2.5, 200) dc.SavePNG("superellipse.png") }
http://rosettacode.org/wiki/Sylvester%27s_sequence
Sylvester's sequence
This page uses content from Wikipedia. The original article was at Sylvester's sequence. 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 number theory, Sylvester's sequence is an integer sequence in which each term of the sequence is the product of the previous terms, plus one. Its values grow doubly exponentially, and the sum of its reciprocals forms a series of unit fractions that converges to 1 more rapidly than any other series of unit fractions with the same number of terms. Further, the sum of the first k terms of the infinite series of reciprocals provides the closest possible underestimate of 1 by any k-term Egyptian fraction. Task Write a routine (function, procedure, generator, whatever) to calculate Sylvester's sequence. Use that routine to show the values of the first 10 elements in the sequence. Show the sum of the reciprocals of the first 10 elements on the sequence, ideally as an exact fraction. Related tasks Egyptian fractions Harmonic series See also OEIS A000058 - Sylvester's sequence
#Quackery
Quackery
[ $ "bigrat.qky" loadfile ] now!   ' [ 2 ] 9 times [ dup -1 peek dup 2 ** swap - 1+ join ]   dup witheach [ echo cr ] cr   0 n->v rot witheach [ n->v 1/v v+ ] 222 point$ echo$
http://rosettacode.org/wiki/Sylvester%27s_sequence
Sylvester's sequence
This page uses content from Wikipedia. The original article was at Sylvester's sequence. 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 number theory, Sylvester's sequence is an integer sequence in which each term of the sequence is the product of the previous terms, plus one. Its values grow doubly exponentially, and the sum of its reciprocals forms a series of unit fractions that converges to 1 more rapidly than any other series of unit fractions with the same number of terms. Further, the sum of the first k terms of the infinite series of reciprocals provides the closest possible underestimate of 1 by any k-term Egyptian fraction. Task Write a routine (function, procedure, generator, whatever) to calculate Sylvester's sequence. Use that routine to show the values of the first 10 elements in the sequence. Show the sum of the reciprocals of the first 10 elements on the sequence, ideally as an exact fraction. Related tasks Egyptian fractions Harmonic series See also OEIS A000058 - Sylvester's sequence
#Raku
Raku
my @S = {1 + [*] @S[^($++)]} … *;   put 'First 10 elements of Sylvester\'s sequence: ', @S[^10];   say "\nSum of the reciprocals of first 10 elements: ", sum @S[^10].map: { FatRat.new: 1, $_ };
http://rosettacode.org/wiki/Sylvester%27s_sequence
Sylvester's sequence
This page uses content from Wikipedia. The original article was at Sylvester's sequence. 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 number theory, Sylvester's sequence is an integer sequence in which each term of the sequence is the product of the previous terms, plus one. Its values grow doubly exponentially, and the sum of its reciprocals forms a series of unit fractions that converges to 1 more rapidly than any other series of unit fractions with the same number of terms. Further, the sum of the first k terms of the infinite series of reciprocals provides the closest possible underestimate of 1 by any k-term Egyptian fraction. Task Write a routine (function, procedure, generator, whatever) to calculate Sylvester's sequence. Use that routine to show the values of the first 10 elements in the sequence. Show the sum of the reciprocals of the first 10 elements on the sequence, ideally as an exact fraction. Related tasks Egyptian fractions Harmonic series See also OEIS A000058 - Sylvester's sequence
#REXX
REXX
/*REXX pgm finds N terms of the Sylvester's sequence & the sum of the their reciprocals.*/ parse arg n . /*obtain optional argument from the CL.*/ if n=='' | n=="," then n= 10 /*Not specified? Then use the default.*/ numeric digits max(9, 2**(n-7) * 13 + 1) /*calculate how many dec. digs we need.*/ @.0= 2 /*the value of the 1st Sylvester number*/ $= 0 do j=0 for n; jm= j - 1 /*calculate the Sylvester sequence. */ if j>0 then @.j= @.jm**2 - @.jm + 1 /*calculate a Sylvester sequence num.*/ say 'Sylvester('j") ──► " @.j /*display the Sylvester index & number.*/ $= $ + 1 / @.j /*add its reciprocal to the recip. sum.*/ end /*j*/ say /*stick a fork in it, we're all done. */ numeric digits digits() - 1 say 'sum of the first ' n " reciprocals using" digits() 'decimal digits: ' $ / 1
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).
#Kotlin
Kotlin
// version 1.0.6   import java.util.PriorityQueue   class CubeSum(val x: Long, val y: Long) : Comparable<CubeSum> { val value: Long = x * x * x + y * y * y   override fun toString() = String.format("%4d^3 + %3d^3", x, y)   override fun compareTo(other: CubeSum) = value.compareTo(other.value) }   class SumIterator : Iterator<CubeSum> { private val pq = PriorityQueue<CubeSum>() private var n = 0L   override fun hasNext() = true   override fun next(): CubeSum { while (pq.size == 0 || pq.peek().value >= n * n * n) pq.add(CubeSum(++n, 1)) val s: CubeSum = pq.remove() if (s.x > s.y + 1) pq.add(CubeSum(s.x, s.y + 1)) return s } }   class TaxiIterator : Iterator<MutableList<CubeSum>> { private val sumIterator = SumIterator() private var last: CubeSum = sumIterator.next()   override fun hasNext() = true   override fun next(): MutableList<CubeSum> { var s: CubeSum = sumIterator.next() val train = mutableListOf<CubeSum>() while (s.value != last.value) { last = s s = sumIterator.next() } train.add(last) do { train.add(s) s = sumIterator.next() } while (s.value == last.value) last = s return train } }   fun main(args: Array<String>) { val taxi = TaxiIterator() for (i in 1..2006) { val t = taxi.next() if (i in 26 until 2000) continue print(String.format("%4d: %10d", i, t[0].value)) for (s in t) print(" = $s") println() } }
http://rosettacode.org/wiki/Superpermutation_minimisation
Superpermutation minimisation
A superpermutation of N different characters is a string consisting of an arrangement of multiple copies of those N different characters in which every permutation of those characters can be found as a substring. For example, representing the characters as A..Z, using N=2 we choose to use the first two characters 'AB'. The permutations of 'AB' are the two, (i.e. two-factorial), strings: 'AB' and 'BA'. A too obvious method of generating a superpermutation is to just join all the permutations together forming 'ABBA'. A little thought will produce the shorter (in fact the shortest) superpermutation of 'ABA' - it contains 'AB' at the beginning and contains 'BA' from the middle to the end. The "too obvious" method of creation generates a string of length N!*N. Using this as a yardstick, the task is to investigate other methods of generating superpermutations of N from 1-to-7 characters, that never generate larger superpermutations. Show descriptions and comparisons of algorithms used here, and select the "Best" algorithm as being the one generating shorter superpermutations. The problem of generating the shortest superpermutation for each N might be NP complete, although the minimal strings for small values of N have been found by brute -force searches. 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 Reference The Minimal Superpermutation Problem. by Nathaniel Johnston. oeis A180632 gives 0-5 as 0, 1, 3, 9, 33, 153. 6 is thought to be 872. Superpermutations - Numberphile. A video Superpermutations: the maths problem solved by 4chan - Standupmaths. A video of recent (2018) mathematical progress. New Superpermutations Discovered! Standupmaths & Numberphile.
#Julia
Julia
const nmax = 12   function r!(n, s, pos, count) if n == 0 return false end c = s[pos + 1 - n] count[n + 1] -= 1 if count[n + 1] == 0 count[n + 1] = n if r!(n - 1, s, pos, count) == 0 return false end end s[pos + 1] = c pos += 1 true end   function superpermutation(n) count = zeros(nmax) pos = n superperm = zeros(UInt8, n < 2 ? n : mapreduce(factorial, +, 1:n)) for i in 0:n-1 count[i + 1] = i superperm[i + 1] = Char(i + '0') end count[n + 1] = n while r!(n, superperm, pos, count) ; end superperm end   function testsuper(N, verbose=false) for i in 0:N-1 s = superpermutation(i) println("Superperm($i) has length $(length(s)) ", (verbose ? String(s) : "")) end end   testsuper(nmax)  
http://rosettacode.org/wiki/Superpermutation_minimisation
Superpermutation minimisation
A superpermutation of N different characters is a string consisting of an arrangement of multiple copies of those N different characters in which every permutation of those characters can be found as a substring. For example, representing the characters as A..Z, using N=2 we choose to use the first two characters 'AB'. The permutations of 'AB' are the two, (i.e. two-factorial), strings: 'AB' and 'BA'. A too obvious method of generating a superpermutation is to just join all the permutations together forming 'ABBA'. A little thought will produce the shorter (in fact the shortest) superpermutation of 'ABA' - it contains 'AB' at the beginning and contains 'BA' from the middle to the end. The "too obvious" method of creation generates a string of length N!*N. Using this as a yardstick, the task is to investigate other methods of generating superpermutations of N from 1-to-7 characters, that never generate larger superpermutations. Show descriptions and comparisons of algorithms used here, and select the "Best" algorithm as being the one generating shorter superpermutations. The problem of generating the shortest superpermutation for each N might be NP complete, although the minimal strings for small values of N have been found by brute -force searches. 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 Reference The Minimal Superpermutation Problem. by Nathaniel Johnston. oeis A180632 gives 0-5 as 0, 1, 3, 9, 33, 153. 6 is thought to be 872. Superpermutations - Numberphile. A video Superpermutations: the maths problem solved by 4chan - Standupmaths. A video of recent (2018) mathematical progress. New Superpermutations Discovered! Standupmaths & Numberphile.
#Kotlin
Kotlin
// version 1.1.2   const val MAX = 12   var sp = CharArray(0) val count = IntArray(MAX) var pos = 0   fun factSum(n: Int): Int { var s = 0 var x = 0 var f = 1 while (x < n) { f *= ++x s += f } return s }   fun r(n: Int): Boolean { if (n == 0) return false val c = sp[pos - n] if (--count[n] == 0) { count[n] = n if (!r(n - 1)) return false } sp[pos++] = c return true }   fun superPerm(n: Int) { pos = n val len = factSum(n) if (len > 0) sp = CharArray(len) for (i in 0..n) count[i] = i for (i in 1..n) sp[i - 1] = '0' + i while (r(n)) {} }   fun main(args: Array<String>) { for (n in 0 until MAX) { superPerm(n) println("superPerm(${"%2d".format(n)}) len = ${sp.size}") } }
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
#Ring
Ring
  see "The first 100 tau numbers are:" + nl + nl   n = 1 num = 0 limit = 100 while num < limit n = n + 1 tau = 0 for m = 1 to n if n%m = 0 tau = tau + 1 ok next if n%tau = 0 num = num + 1 if num%10 = 1 see nl ok see "" + n + " " ok 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
#Ruby
Ruby
require 'prime'   taus = Enumerator.new do |y| (1..).each do |n| num_divisors = n.prime_division.inject(1){|prod, n| prod *= n[1] + 1 } y << n if n % num_divisors == 0 end end   p taus.take(100)  
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
#C.23
C#
using System;   namespace TemperatureConversion { class Program { static Func<double, double> ConvertKelvinToFahrenheit = x => (x * 1.8) - 459.67; static Func<double, double> ConvertKelvinToRankine = x => x * 1.8; static Func<double, double> ConvertKelvinToCelsius = x => x = 273.13;   static void Main(string[] args) { Console.Write("Enter a Kelvin Temperature: "); string inputVal = Console.ReadLine(); double kelvinTemp = 0f;   if (double.TryParse(inputVal, out kelvinTemp)) { Console.WriteLine(string.Format("Kelvin: {0}", kelvinTemp)); Console.WriteLine(string.Format("Fahrenheit: {0}", ConvertKelvinToFahrenheit(kelvinTemp))); Console.WriteLine(string.Format("Rankine: {0}", ConvertKelvinToRankine(kelvinTemp))); Console.WriteLine(string.Format("Celsius: {0}", ConvertKelvinToCelsius(kelvinTemp))); Console.ReadKey(); } else { Console.WriteLine("Invalid input value: " + inputVal); } } } }
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
#Perl
Perl
use strict; use warnings; use feature 'say'; use ntheory 'divisors';   my @x; push @x, scalar divisors($_) for 1..100;   say "Tau function - first 100:\n" . ((sprintf "@{['%4d' x 100]}", @x[0..100-1]) =~ s/(.{80})/$1\n/gr);
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
#Phix
Phix
for i=1 to 100 do printf(1,"%3d",{length(factors(i,1))}) if remainder(i,20)=0 then puts(1,"\n") end if end for
http://rosettacode.org/wiki/Terminal_control/Clear_the_screen
Terminal control/Clear the screen
Task Clear the terminal window.
#ProDOS
ProDOS
clearscurrentscreentext
http://rosettacode.org/wiki/Terminal_control/Clear_the_screen
Terminal control/Clear the screen
Task Clear the terminal window.
#Python
Python
import os os.system("clear")
http://rosettacode.org/wiki/Terminal_control/Clear_the_screen
Terminal control/Clear the screen
Task Clear the terminal window.
#Quackery
Quackery
[ $ &print("\33[2J",end='')& python ] is clearscreen
http://rosettacode.org/wiki/Terminal_control/Clear_the_screen
Terminal control/Clear the screen
Task Clear the terminal window.
#R
R
cat("\33[2J")
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
#ooRexx
ooRexx
  tritValues = .array~of(.trit~true, .trit~false, .trit~maybe) tab = '09'x   say "not operation (\)" loop a over tritValues say "\"a":" (\a) end   say say "and operation (&)" loop aa over tritValues loop bb over tritValues say (aa" & "bb":" (aa&bb)) end end   say say "or operation (|)" loop aa over tritValues loop bb over tritValues say (aa" | "bb":" (aa|bb)) end end   say say "implies operation (&&)" loop aa over tritValues loop bb over tritValues say (aa" && "bb":" (aa&&bb)) end end   say say "equals operation (=)" loop aa over tritValues loop bb over tritValues say (aa" = "bb":" (aa=bb)) end end   ::class trit -- making this a private method so we can control the creation -- of these. We only allow 3 instances to exist ::method new class private forward class(super)   ::method init class expose true false maybe -- delayed creation true = .nil false = .nil maybe = .nil   -- read only attribute access to the instances. -- these methods create the appropriate singleton on the first call ::attribute true class get expose true if true == .nil then true = self~new("True") return true   ::attribute false class get expose false if false == .nil then false = self~new("False") return false   ::attribute maybe class get expose maybe if maybe == .nil then maybe = self~new("Maybe") return maybe   -- create an instance ::method init expose value use arg value   -- string method to return the value of the instance ::method string expose value return value   -- "and" method using the operator overload ::method "&" use strict arg other if self == .trit~true then return other else if self == .trit~maybe then do if other == .trit~false then return .trit~false else return .trit~maybe end else return .trit~false   -- "or" method using the operator overload ::method "|" use strict arg other if self == .trit~true then return .trit~true else if self == .trit~maybe then do if other == .trit~true then return .trit~true else return .trit~maybe end else return other   -- implies method...using the XOR operator for this ::method "&&" use strict arg other if self == .trit~true then return other else if self == .trit~maybe then do if other == .trit~true then return .trit~true else return .trit~maybe end else return .trit~true   -- "not" method using the operator overload ::method "\" if self == .trit~true then return .trit~false else if self == .trit~maybe then return .trit~maybe else return .trit~true   -- "equals" using the "=" override. This makes a distinction between -- the "==" operator, which is real equality and the "=" operator, which -- is trinary equality. ::method "=" use strict arg other if self == .trit~true then return other else if self == .trit~maybe then return .trit~maybe else return \other  
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.
#PureBasic
PureBasic
#TASK="Text processing/1" Define File$, InLine$, Part$, i, Out$, ErrEnds$, Errcnt, ErrMax Define lsum.d, tsum.d, rejects, val.d, readings   File$=OpenFileRequester(#TASK,"readings.txt","",0) If OpenConsole() And ReadFile(0,File$) While Not Eof(0) InLine$=ReadString(0) For i=1 To 1+2*24 Part$=StringField(InLine$,i,#TAB$) If i=1 ; Date Out$=Part$: lsum=0: rejects=0 ElseIf i%2=0 ; Recorded value val=ValD(Part$) Else ; Status part If Val(Part$)>0 Errcnt=0 : readings+1 lsum+val : tsum+val Else rejects+1: Errcnt+1 If Errcnt>ErrMax ErrMax=Errcnt ErrEnds$=Out$ EndIf EndIf EndIf Next i Out$+" Rejects: " + Str(rejects) Out$+" Accepts: " + Str(24-rejects) Out$+" Line_tot: "+ StrD(lsum,3) If rejects<24 Out$+" Line_avg: "+StrD(lsum/(24-rejects),3) Else Out$+" Line_avg: N/A" EndIf PrintN("Line: "+Out$) Wend PrintN(#CRLF$+"File = "+GetFilePart(File$)) PrintN("Total = "+ StrD(tsum,3)) PrintN("Readings = "+ Str(readings)) PrintN("Average = "+ StrD(tsum/readings,3)) Print(#CRLF$+"Maximum of "+Str(ErrMax)) PrintN(" consecutive false readings, ends at "+ErrEnds$) CloseFile(0) ; Print("Press ENTER to exit"): Input() EndIf
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
#MAD
MAD
NORMAL MODE IS INTEGER   THROUGH VERSE, FOR I=1, 1, I.G.12 PRINT FORMAT XMS,ORD(I) PRINT FORMAT TLV TRANSFER TO GIFT(13-I) GIFT(1) PRINT FORMAT G12 GIFT(2) PRINT FORMAT G11 GIFT(3) PRINT FORMAT G10 GIFT(4) PRINT FORMAT G9 GIFT(5) PRINT FORMAT G8 GIFT(6) PRINT FORMAT G7 GIFT(7) PRINT FORMAT G6 GIFT(8) PRINT FORMAT G5 GIFT(9) PRINT FORMAT G4 GIFT(10) PRINT FORMAT G3 GIFT(11) PRINT FORMAT G2 GIFT(12) PRINT FORMAT G1 VERSE PRINT FORMAT MT   VECTOR VALUES XMS = 0 $7HON THE ,C,S1,16HDAY OF CHRISTMAS*$ VECTOR VALUES ORD = $*$, $FIRST$, $SECOND$, $THIRD$ 0 , $FOURTH$, $FIFTH$, $SIXTH$, $SEVENTH$, $EIGHTH$ 1 , $NINTH$, $TENTH$, $ELEVENTH$, $TWELFTH$ VECTOR VALUES TLV = $23HMY TRUE LOVE GAVE TO ME*$ VECTOR VALUES G12 = $24HTWELVE DRUMMERS DRUMMING*$ VECTOR VALUES G11 = $20HELEVEN PIPERS PIPING*$ VECTOR VALUES G10 = $19HTEN LORDS A-LEAPING*$ VECTOR VALUES G9 = $19HNINE LADIES DANCING*$ VECTOR VALUES G8 = $21HEIGHT MAIDS A-MILKING*$ VECTOR VALUES G7 = $22HSEVEN SWANS A-SWIMMING*$ VECTOR VALUES G6 = $18HSIX GEESE A-LAYING*$ VECTOR VALUES G5 = $17HFIVE GOLDEN RINGS*$ VECTOR VALUES G4 = $18HFOUR CALLING BIRDS*$ VECTOR VALUES G3 = $17HTHREE FRENCH HENS*$ VECTOR VALUES G2 = $20HTWO TURTLE DOVES AND*$ VECTOR VALUES G1 = $26HA PARTRIDGE IN A PEAR TREE*$ VECTOR VALUES MT = $*$ END OF PROGRAM  
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
#Maple
Maple
gifts := ["Twelve drummers drumming", "Eleven pipers piping", "Ten lords a-leaping", "Nine ladies dancing", "Eight maids a-milking", "Seven swans a-swimming", "Six geese a-laying", "Five golden rings", "Four calling birds", "Three french hens", "Two turtle doves and", "A partridge in a pear tree"]: days := ["first", "second", "third", "fourth", "fifth", "sixth", "seventh", "eighth", "ninth", "tenth", "eleventh", "twelfth"]: for i to 12 do printf("On the %s day of Christmas\nMy true love gave to me:\n", days[i]); for j from 13-i to 12 do printf("%s\n", gifts[j]); end do; printf("\n"); end do;
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)
#TPP
TPP
--color red This is red --color green This is green --color blue This is blue --color cyan This is cyan --color magenta This is magenta --color yellow This is yellow
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)
#True_BASIC
True BASIC
FOR n = 1 TO 15 SET COLOR n PRINT "Rosetta Code" NEXT n 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)
#UNIX_Shell
UNIX Shell
#!/bin/sh # Check if the terminal supports colour   # We should know from the TERM evironment variable whether the system # is comfigured for a colour terminal or not, but we can also check the # tput utility to check the terminal capability records.   COLORS=8 # Assume initially that the system supports eight colours case $TERM in linux)  ;; # We know this is a colour terminal rxvt)  ;; # We know this is a colour terminal *) COLORS=`tput colors 2> /dev/null` # Get the number of colours from the termcap file esac if [ -z $COLORS ] ; then COLORS=1 # Watch out for an empty returned value fi   if [ $COLORS -le 2 ] ; then # The terminal is not colour echo "HW65000 This application requires a colour terminal" >&2 exit 252 #ERLHW incompatible hardware fi   # We know at this point that the terminal is colour   # Coloured text tput setaf 1 #red echo "Red" tput setaf 4 #blue echo "Blue" tput setaf 3 # yellow echo "Yellow"   # Blinking tput setab 1 # red background tput setaf 3 # yellow foreground #tput blink # enable blinking (but does not work on some terminals) echo "Flashing text"   tput sgr0 # reset everything before exiting
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)
#Wren
Wren
import "timer" for Timer   var colors = ["Black", "Red", "Green", "Yellow", "Blue", "Magenta", "Cyan", "White"]   // display words using 'bright' colors for (i in 1..7) System.print("\e[%(30+i);1m%(colors[i])") // red to white Timer.sleep(3000) // wait for 3 seconds System.write("\e[47m") // set background color to white System.write("\e[2J") // clear screen to background color System.write("\e[H") // home the cursor   // display words again using 'blinking' colors System.write("\e[5m") // blink on for (i in 0..6) System.print("\e[%(30+i);1m%(colors[i])") // black to cyan Timer.sleep(3000) // wait for 3 more seconds System.write("\e[0m") // reset all attributes System.write("\e[2J") // clear screen to background color System.write("\e[H") // home the cursor
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.
#Forth
Forth
\ \ co.fs Coroutines by continuations. \ \ * Circular Queue. Capacity is power of 2. \ VARIABLE HEAD VARIABLE TAIL 128 CELLS CONSTANT CQ# \ * align by queue capacity HERE DUP CQ# 1- INVERT AND CQ# + SWAP - ALLOT \ HERE CQ# ALLOT CONSTANT START \ : ADJUST ( -- ) [ CQ# 1- ]L AND START + ; : PUT ( n-- ) TAIL @ TUCK ! CELL+ ADJUST TAIL ! ; : TAKE ( --n ) HEAD @ DUP @ SWAP CELL+ ADJUST HEAD ! ; : 0CQ ( -- ) START DUP HEAD ! TAIL ! ; 0CQ : NOEMPTY? ( --f ) HEAD @ TAIL @ <> ; : ;CO ( -- ) TAKE >R ; \ \ * COROUTINES LEXEME \ : CO: ( -- ) R> PUT ; \ Register continuation as coroutine. Exit. : CO ( -- ) R> PUT TAKE >R ; \ Co-route. : GO ( -- ) BEGIN NOEMPTY? WHILE ;CO REPEAT ; \ :-) \ \ * CHANNELS LEXEME \ : CHAN? ( a--f ) 2@ XOR ;  
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.
#Go
Go
package main   import ( "bufio" "fmt" "log" "os" )   func main() { lines := make(chan string) count := make(chan int) go func() { c := 0 for l := range lines { fmt.Println(l) c++ } count <- c }()   f, err := os.Open("input.txt") if err != nil { log.Fatal(err) } for s := bufio.NewScanner(f); s.Scan(); { lines <- s.Text() } f.Close() close(lines) fmt.Println("Number of lines:", <-count) }
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.
#Sidef
Sidef
require('DBI');   var db = %s'DBI'.connect('DBI:mysql:database:server','login','password');   var statment = <<'EOF'; CREATE TABLE `Address` ( `addrID` int(11) NOT NULL auto_increment, `addrStreet` varchar(50) NOT NULL default '', `addrCity` varchar(25) NOT NULL default '', `addrState` char(2) NOT NULL default '', `addrZIP` char(10) NOT NULL default '', PRIMARY KEY (`addrID`) ); EOF   var exec = db.prepare(statment); exec.execute;
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.
#SQL_PL
SQL PL
  CREATE TABLE Address ( addrID INTEGER generated BY DEFAULT AS IDENTITY, addrStreet VARCHAR(50) NOT NULL, addrCity VARCHAR(25) 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.
#SQLite
SQLite
  CREATE TABLE address_USA ( address_ID INTEGER PRIMARY KEY, address_Street TEXT, address_City TEXT, address_State TEXT, address_Zip INTEGER );  
http://rosettacode.org/wiki/System_time
System time
Task Output the system time   (any units will do as long as they are noted) either by a system command or one built into the language. The system time can be used for debugging, network information, random number seeds, or something as simple as program performance. Related task   Date format See also   Retrieving system time (wiki)
#ALGOL_68
ALGOL 68
FORMAT time repr = $"year="4d,", month="2d,", day="2d,", hours="2d,", \ minutes="2d,", seconds="2d,", day of week="d,", \ daylight-saving-time flag="dl$; printf((time repr, local time)); printf((time repr, utc time))
http://rosettacode.org/wiki/Summarize_and_say_sequence
Summarize and say sequence
There are several ways to generate a self-referential sequence. One very common one (the Look-and-say sequence) is to start with a positive integer, then generate the next term by concatenating enumerated groups of adjacent alike digits: 0, 10, 1110, 3110, 132110, 1113122110, 311311222110 ... The terms generated grow in length geometrically and never converge. Another way to generate a self-referential sequence is to summarize the previous term. Count how many of each alike digit there is, then concatenate the sum and digit for each of the sorted enumerated digits. Note that the first five terms are the same as for the previous sequence. 0, 10, 1110, 3110, 132110, 13123110, 23124110 ... Sort the digits largest to smallest. Do not include counts of digits that do not appear in the previous term. Depending on the seed value, series generated this way always either converge to a stable value or to a short cyclical pattern. (For our purposes, I'll use converge to mean an element matches a previously seen element.) The sequence shown, with a seed value of 0, converges to a stable value of 1433223110 after 11 iterations. The seed value that converges most quickly is 22. It goes stable after the first element. (The next element is 22, which has been seen before.) Task Find all the positive integer seed values under 1000000, for the above convergent self-referential sequence, that takes the largest number of iterations before converging. Then print out the number of iterations and the sequence they return. Note that different permutations of the digits of the seed will yield the same sequence. For this task, assume leading zeros are not permitted. Seed Value(s): 9009 9090 9900 Iterations: 21 Sequence: (same for all three seeds except for first element) 9009 2920 192210 19222110 19323110 1923123110 1923224110 191413323110 191433125110 19151423125110 19251413226110 1916151413325110 1916251423127110 191716151413326110 191726151423128110 19181716151413327110 19182716151423129110 29181716151413328110 19281716151423228110 19281716151413427110 19182716152413228110 Related tasks   Fours is the number of letters in the ...   Look-and-say sequence   Number names   Self-describing numbers   Spelling of ordinal numbers Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet Also see   The On-Line Encyclopedia of Integer Sequences.
#AutoHotkey
AutoHotkey
  ; The following directives and commands speed up execution: #NoEnv SetBatchlines -1 ListLines Off Process, Priority,, high   iterations := 0, seed := "Seeds: "   Loop 1000000 If (newIterations := CountSubString(list := ListSequence(A_Index), "`n")) > iterations iterations := newiterations ,final := "`nIterations: " iterations+1 "`nSequence:`n`n" A_Index "`n" list ,seed := A_Index " " else if (newIterations = iterations) seed .= A_Index " " MsgBox % "Seeds: " . seed . final ListSequence(seed){ While !InStr("`n" . out, "`n" (d:=Describe(seed)) "`n") out .= d "`n", seed := d return out }   Describe(n){ Loop 10 If (t:=CountSubString(n, 10-A_Index)) out .= t . (10-A_Index) return out }   CountSubstring(fullstring, substring){ StringReplace, junk, fullstring, %substring%, , UseErrorLevel return errorlevel }  
http://rosettacode.org/wiki/Summarize_primes
Summarize primes
Task Considering in order of length, n, all sequences of consecutive primes, p, from 2 onwards, where p < 1000 and n>0, select those sequences whose sum is prime, and for these display the length of the sequence, the last item in the sequence, and the sum.
#C
C
#include <stdbool.h> #include <stdio.h>   bool is_prime(int n) { int i = 5;   if (n < 2) { return false; }   if (n % 2 == 0) { return n == 2; } if (n % 3 == 0) { return n == 3; }   while (i * i <= n) { if (n % i == 0) { return false; } i += 2;   if (n % i == 0) { return false; } i += 4; }   return true; }   int main() { const int start = 1; const int stop = 1000;   int sum = 0; int count = 0; int sc = 0; int p;   for (p = start; p < stop; p++) { if (is_prime(p)) { count++; sum += p; if (is_prime(sum)) { printf("The sum of %3d primes in [2, %3d] is %5d which is also prime\n", count, p, sum); sc++; } } } printf("There are %d summerized primes in [%d, %d)\n", sc, start, stop);   return 0; }
http://rosettacode.org/wiki/Sutherland-Hodgman_polygon_clipping
Sutherland-Hodgman polygon clipping
The   Sutherland-Hodgman clipping algorithm   finds the polygon that is the intersection between an arbitrary polygon (the “subject polygon”) and a convex polygon (the “clip polygon”). It is used in computer graphics (especially 2D graphics) to reduce the complexity of a scene being displayed by eliminating parts of a polygon that do not need to be displayed. Task Take the closed polygon defined by the points: [ ( 50 , 150 ) , ( 200 , 50 ) , ( 350 , 150 ) , ( 350 , 300 ) , ( 250 , 300 ) , ( 200 , 250 ) , ( 150 , 350 ) , ( 100 , 250 ) , ( 100 , 200 ) ] {\displaystyle [(50,150),(200,50),(350,150),(350,300),(250,300),(200,250),(150,350),(100,250),(100,200)]} and clip it by the rectangle defined by the points: [ ( 100 , 100 ) , ( 300 , 100 ) , ( 300 , 300 ) , ( 100 , 300 ) ] {\displaystyle [(100,100),(300,100),(300,300),(100,300)]} Print the sequence of points that define the resulting clipped polygon. Extra credit Display all three polygons on a graphical surface, using a different color for each polygon and filling the resulting polygon. (When displaying you may use either a north-west or a south-west origin, whichever is more convenient for your display mechanism.)
#FreeBASIC
FreeBASIC
  Type Point As Double x,y End Type   Type Line As Point s,f'start/finish End Type   Function isleft(L As Line,p As Point) As Long Return -Sgn((L.s.x-L.f.x)*(p.y-L.f.y)-(p.x-L.f.x)*(L.s.y-L.f.y)) End Function   Function segmentintersections(L1 As Line,L2 As Line) As Long If isleft(L2,L1.s) = isleft(L2,L1.f) Then Return 0 If isleft(L1,L2.s) = isleft(L1,L2.f) Then Return 0 Return 1 End Function   Function allintersections(l1 As Line,l2 As Line,_out As Point) As Long Const tolerance=.01 Var p1=l1.s, p2=l1.f, p3=l2.s, p4=l2.f Var x12=p1.x-p2.x, x34=p3.x-p4.x, y12=p1.y-p2.y, y34=p3.y-p4.y Var c=x12*y34-y12*x34 If Abs(c)<tolerance Then Return 0 Var a=p1.x*p2.y-p1.y*p2.x, b=p3.x*p4.y-p3.y*p4.x _out.x = (a*x34-b*x12)/c _out.y = (a*y34-b*y12)/c Return 1 End Function   Dim As Point p1(...)={(50,150),(200,50),(350,150),(350,300),(250,300),(200,250), _ (150,350),(100,250),(100,200)}   Dim As Point p2(...)={(100,100),(300,100),(300,300),(100,300)} 'get the line segments around the polygons Dim As Line L1(...)={(p1(0),p1(1)),(p1(1),p1(2)),(p1(2),p1(3)),(p1(3),p1(4)),(p1(4),p1(5)),_ (p1(5),p1(6)),(p1(6),p1(7)),(p1(7),p1(8)),(p1(8),p1(0))}   Dim As Line L2(...)={(p2(0),p2(1)),(p2(1),p2(2)),(p2(2),p2(3)),(p2(3),p2(0))}   'would normally draw these lines now, but not here. Dim As Point x For n1 As Long=Lbound(L1) To Ubound(L1) For n2 As Long=Lbound(L2) To Ubound(L2) If allintersections(L1(n1),L2(n2),x) And segmentintersections(L1(n1),L2(n2)) Then Print x.x,x.y End If Next Next   Sleep  
http://rosettacode.org/wiki/Symmetric_difference
Symmetric difference
Task Given two sets A and B, compute ( A ∖ B ) ∪ ( B ∖ A ) . {\displaystyle (A\setminus B)\cup (B\setminus A).} That is, enumerate the items that are in A or B but not both. This set is called the symmetric difference of A and B. In other words: ( A ∪ B ) ∖ ( A ∩ B ) {\displaystyle (A\cup B)\setminus (A\cap B)} (the set of items that are in at least one of A or B minus the set of items that are in both A and B). Optionally, give the individual differences ( A ∖ B {\displaystyle A\setminus B} and B ∖ A {\displaystyle B\setminus A} ) as well. Test cases A = {John, Bob, Mary, Serena} B = {Jim, Mary, John, Bob} Notes If your code uses lists of items to represent sets then ensure duplicate items in lists are correctly handled. For example two lists representing sets of a = ["John", "Serena", "Bob", "Mary", "Serena"] and b = ["Jim", "Mary", "John", "Jim", "Bob"] should produce the result of just two strings: ["Serena", "Jim"], in any order. In the mathematical notation above A \ B gives the set of items in A that are not in B; A ∪ B gives the set of items in both A and B, (their union); and A ∩ B gives the set of items that are in both A and B (their intersection).
#BBC_BASIC
BBC BASIC
DIM list$(4) list$() = "Bob", "Jim", "John", "Mary", "Serena"   setA% = %11101 PRINT "Set A: " FNlistset(list$(), setA%) setB% = %01111 PRINT "Set B: " FNlistset(list$(), setB%)   REM Compute symmetric difference: setC% = setA% EOR setB% PRINT '"Symmetric difference: " FNlistset(list$(), setC%)   REM Optional: PRINT "Set A \ Set B: " FNlistset(list$(), setA% AND NOT setB%) PRINT "Set B \ Set A: " FNlistset(list$(), setB% AND NOT setA%) END   DEF FNlistset(list$(), set%) LOCAL i%, o$ FOR i% = 0 TO 31 IF set% AND 1 << i% o$ += list$(i%) + ", " NEXT = LEFT$(LEFT$(o$))
http://rosettacode.org/wiki/Symmetric_difference
Symmetric difference
Task Given two sets A and B, compute ( A ∖ B ) ∪ ( B ∖ A ) . {\displaystyle (A\setminus B)\cup (B\setminus A).} That is, enumerate the items that are in A or B but not both. This set is called the symmetric difference of A and B. In other words: ( A ∪ B ) ∖ ( A ∩ B ) {\displaystyle (A\cup B)\setminus (A\cap B)} (the set of items that are in at least one of A or B minus the set of items that are in both A and B). Optionally, give the individual differences ( A ∖ B {\displaystyle A\setminus B} and B ∖ A {\displaystyle B\setminus A} ) as well. Test cases A = {John, Bob, Mary, Serena} B = {Jim, Mary, John, Bob} Notes If your code uses lists of items to represent sets then ensure duplicate items in lists are correctly handled. For example two lists representing sets of a = ["John", "Serena", "Bob", "Mary", "Serena"] and b = ["Jim", "Mary", "John", "Jim", "Bob"] should produce the result of just two strings: ["Serena", "Jim"], in any order. In the mathematical notation above A \ B gives the set of items in A that are not in B; A ∪ B gives the set of items in both A and B, (their union); and A ∩ B gives the set of items that are in both A and B (their intersection).
#Bracmat
Bracmat
(SymmetricDifference= A B x symdiff .  !arg:(?A.?B) & :?symdiff & (  !A !B  :  ? ( %@?x & ( !A:? !x ?&!B:? !x ? | !symdiff:? !x ? | !symdiff !x:?symdiff ) & ~ )  ? | !symdiff ));
http://rosettacode.org/wiki/Super-d_numbers
Super-d numbers
A super-d number is a positive, decimal (base ten) integer   n   such that   d × nd   has at least   d   consecutive digits   d   where 2 ≤ d ≤ 9 For instance, 753 is a super-3 number because 3 × 7533 = 1280873331. Super-d   numbers are also shown on   MathWorld™   as   super-d   or   super-d. Task Write a function/procedure/routine to find super-d numbers. For   d=2   through   d=6,   use the routine to show the first   10   super-d numbers. Extra credit Show the first   10   super-7, super-8, and/or super-9 numbers   (optional). See also   Wolfram MathWorld - Super-d Number.   OEIS: A014569 - Super-3 Numbers.
#jq
jq
# To take advantage of gojq's arbitrary-precision integer arithmetic: def power($b): . as $in | reduce range(0;$b) as $i (1; . * $in);   # Input is $d, the number of consecutive digits, 2 <= $d <= 9 # $max is the number of superd numbers to be emitted. def superd($number): . as $d | tostring as $s | ($s * $d) as $target | {count:0, j: 3 } | while ( .count <= $number; .emit = null | if ((.j|power($d) * $d) | tostring) | index($target) then .count += 1 | .emit = .j else . end | .j += 1 ) | select(.emit).emit ;   # super-d for 2 <=d < 8 range(2; 8) | "First 10 super-\(.) numbers:", superd(10)
http://rosettacode.org/wiki/Super-d_numbers
Super-d numbers
A super-d number is a positive, decimal (base ten) integer   n   such that   d × nd   has at least   d   consecutive digits   d   where 2 ≤ d ≤ 9 For instance, 753 is a super-3 number because 3 × 7533 = 1280873331. Super-d   numbers are also shown on   MathWorld™   as   super-d   or   super-d. Task Write a function/procedure/routine to find super-d numbers. For   d=2   through   d=6,   use the routine to show the first   10   super-d numbers. Extra credit Show the first   10   super-7, super-8, and/or super-9 numbers   (optional). See also   Wolfram MathWorld - Super-d Number.   OEIS: A014569 - Super-3 Numbers.
#Julia
Julia
function superd(N) println("First 10 super-$N numbers:") count, j = 0, BigInt(3) target = Char('0' + N)^N while count < 10 if occursin(target, string(j^N * N)) count += 1 print("$j ") end j += 1 end println() end   for n in 2:9 @time superd(n) end  
http://rosettacode.org/wiki/Super-d_numbers
Super-d numbers
A super-d number is a positive, decimal (base ten) integer   n   such that   d × nd   has at least   d   consecutive digits   d   where 2 ≤ d ≤ 9 For instance, 753 is a super-3 number because 3 × 7533 = 1280873331. Super-d   numbers are also shown on   MathWorld™   as   super-d   or   super-d. Task Write a function/procedure/routine to find super-d numbers. For   d=2   through   d=6,   use the routine to show the first   10   super-d numbers. Extra credit Show the first   10   super-7, super-8, and/or super-9 numbers   (optional). See also   Wolfram MathWorld - Super-d Number.   OEIS: A014569 - Super-3 Numbers.
#Kotlin
Kotlin
import java.math.BigInteger   fun superD(d: Int, max: Int) { val start = System.currentTimeMillis() var test = "" for (i in 0 until d) { test += d }   var n = 0 var i = 0 println("First $max super-$d numbers:") while (n < max) { i++ val value: Any = BigInteger.valueOf(d.toLong()) * BigInteger.valueOf(i.toLong()).pow(d) if (value.toString().contains(test)) { n++ print("$i ") } } val end = System.currentTimeMillis() println("\nRun time ${end - start} ms\n") }   fun main() { for (i in 2..9) { superD(i, 10) } }
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.
#Forth
Forth
vocabulary note-words get-current also note-words definitions   \ -- notes.txt variable file : open s" notes.txt" r/w open-file if s" notes.txt" r/w create-file throw then file ! ; : appending file @ file-size throw file @ reposition-file throw ; : write file @ write-file throw ; : close file @ close-file throw ;   \ -- SwiftForth console workaround 9 constant TAB : type ( c-addr u -- ) bounds ?do i c@ dup TAB = if drop 8 spaces else emit then loop ;   \ -- dump notes.txt create buf 4096 allot : dump ( -- ) cr begin buf 4096 file @ read-file throw dup while buf swap type repeat drop ;   \ -- time and date : time @time (time) ; : date @date (date) ;   \ -- add note : cr s\" \n" write ; : tab s\" \t" write ; : space s" " write ; : add-note ( c-addr u -- ) appending date write space time write cr tab ( note ) write cr ;   set-current   \ -- note : note ( "note" -- ) open 0 parse dup if add-note else 2drop dump then close ; previous
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.
#Fortran
Fortran
  program notes implicit none integer :: i, length, iargs, lun, ios integer,dimension(8) :: values character(len=:),allocatable :: arg character(len=256)  :: line character(len=1),parameter  :: tab=char(9) iargs = command_argument_count() open(file='notes.txt',newunit=lun,action='readwrite',position='append',status='unknown') if(iargs.eq.0)then rewind(lun) do read(lun,'(a)',iostat=ios)line if(ios.ne.0)exit write(*,'(a)')trim(line) enddo else call date_and_time(VALUES=values) write(lun,'(*(g0))')values(1),"-",values(2),"-",values(3),"T",values(5),":",values(6),":",values(7) write(lun,'(a)',advance='no')tab do i=1,iargs call get_command_argument(number=i,length=length) arg=repeat(' ',length) call get_command_argument(i, arg) write(lun,'(a,1x)',advance='no')arg enddo write(lun,*) endif end program notes  
http://rosettacode.org/wiki/Superellipse
Superellipse
A superellipse is a geometric figure defined as the set of all points (x, y) with | x a | n + | y b | n = 1 , {\displaystyle \left|{\frac {x}{a}}\right|^{n}\!+\left|{\frac {y}{b}}\right|^{n}\!=1,} where n, a, and b are positive numbers. Task Draw a superellipse with n = 2.5, and a = b = 200
#Haskell
Haskell
{-# LANGUAGE OverloadedStrings, RankNTypes #-} import Reflex import Reflex.Dom import Data.Text (Text, pack, unpack) import Data.Map (Map, fromList, empty) import Text.Read (readMaybe)   width = 600 height = 500   type Point = (Float,Float) type Segment = (Point,Point)   data Ellipse = Ellipse {a :: Float, b :: Float, n :: Float}   toFloat :: Text -> Maybe Float toFloat = readMaybe.unpack   toEllipse :: Maybe Float -> Maybe Float -> Maybe Float -> Maybe Ellipse toEllipse (Just a) (Just b) (Just n) = if a < 1.0 || b <= 1.0 || n <= 0.0 -- not all floats are valid then Nothing else Just $ Ellipse a b n   toEllipse _ _ _ = Nothing   showError :: Maybe a -> String showError Nothing = "invalid input" showError _ = ""   reflect45 pts = pts ++ fmap (\(x,y) -> ( y, x)) (reverse pts) rotate90 pts = pts ++ fmap (\(x,y) -> ( y, -x)) pts rotate180 pts = pts ++ fmap (\(x,y) -> (-x, -y)) pts scale a b = fmap (\(x,y) -> ( a*x, b*y )) segments pts = zip pts $ tail pts   toLineMap :: Maybe Ellipse -> Map Int ((Float,Float),(Float,Float)) toLineMap (Just (Ellipse a b n)) = let f p = (1 - p**n)**(1/n) dp = iterate (*0.9) 1.0 ip = map (\p -> 1.0 -p) dp points s = if n > 1.0 then (\p -> zip p (map f p)) ip else (\p -> zip (map f p) p) dp   in fromList $ -- changes list to map (for listWithKey) zip [0..] $ -- annotates segments with index segments $ -- changes points to line segments scale a b $ rotate180 $ -- doubles the point count rotate90 $ -- doubles the point count reflect45 $ -- doubles the point count takeWhile (\(x,y) -> x < y ) $ -- stop at 45 degree line points 0.9   toLineMap Nothing = empty   lineAttrs :: Segment -> Map Text Text lineAttrs ((x1,y1), (x2,y2)) = fromList [ ( "x1", pack $ show (width/2+x1)) , ( "y1", pack $ show (height/2+y1)) , ( "x2", pack $ show (width/2+x2)) , ( "y2", pack $ show (height/2+y2)) , ( "style", "stroke:brown;stroke-width:2") ]   showLine :: MonadWidget t m => Int -> Dynamic t Segment -> m () showLine _ dSegment = do elSvgns "line" (lineAttrs <$> dSegment) $ return () return ()   main = mainWidget $ do elAttr "h1" ("style" =: "color:brown") $ text "Superellipse" ta <- el "div" $ do text "a: " textInput def { _textInputConfig_initialValue = "200"}   tb <- el "div" $ do text "b: " textInput def { _textInputConfig_initialValue = "200"}   tn <- el "div" $ do text "n: " textInput def { _textInputConfig_initialValue = "2.5"} let ab = zipDynWith toEllipse (toFloat <$> value ta) (toFloat <$> value tb) dEllipse = zipDynWith ($) ab (toFloat <$> value tn) dLines = fmap toLineMap dEllipse   dAttrs = constDyn $ fromList [ ("width" , pack $ show width) , ("height", pack $ show height) ] elAttr "div" ("style" =: "color:red") $ dynText $ fmap (pack.showError) dEllipse el "div" $ elSvgns "svg" dAttrs $ listWithKey dLines showLine return ()   -- At end to avoid Rosetta Code unmatched quotes problem. elSvgns :: forall t m a. MonadWidget t m => Text -> Dynamic t (Map Text Text) -> m a -> m (El t, a) elSvgns = elDynAttrNS' (Just "http://www.w3.org/2000/svg")
http://rosettacode.org/wiki/Sylvester%27s_sequence
Sylvester's sequence
This page uses content from Wikipedia. The original article was at Sylvester's sequence. 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 number theory, Sylvester's sequence is an integer sequence in which each term of the sequence is the product of the previous terms, plus one. Its values grow doubly exponentially, and the sum of its reciprocals forms a series of unit fractions that converges to 1 more rapidly than any other series of unit fractions with the same number of terms. Further, the sum of the first k terms of the infinite series of reciprocals provides the closest possible underestimate of 1 by any k-term Egyptian fraction. Task Write a routine (function, procedure, generator, whatever) to calculate Sylvester's sequence. Use that routine to show the values of the first 10 elements in the sequence. Show the sum of the reciprocals of the first 10 elements on the sequence, ideally as an exact fraction. Related tasks Egyptian fractions Harmonic series See also OEIS A000058 - Sylvester's sequence
#Ruby
Ruby
def sylvester(n) = (1..n).reduce(2){|a| a*a - a + 1 }   (0..9).each {|n| puts "#{n}: #{sylvester n}" } puts " Sum of reciprocals of first 10 terms: #{(0..9).sum{|n| 1.0r / sylvester(n)}.to_f }"  
http://rosettacode.org/wiki/Sylvester%27s_sequence
Sylvester's sequence
This page uses content from Wikipedia. The original article was at Sylvester's sequence. 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 number theory, Sylvester's sequence is an integer sequence in which each term of the sequence is the product of the previous terms, plus one. Its values grow doubly exponentially, and the sum of its reciprocals forms a series of unit fractions that converges to 1 more rapidly than any other series of unit fractions with the same number of terms. Further, the sum of the first k terms of the infinite series of reciprocals provides the closest possible underestimate of 1 by any k-term Egyptian fraction. Task Write a routine (function, procedure, generator, whatever) to calculate Sylvester's sequence. Use that routine to show the values of the first 10 elements in the sequence. Show the sum of the reciprocals of the first 10 elements on the sequence, ideally as an exact fraction. Related tasks Egyptian fractions Harmonic series See also OEIS A000058 - Sylvester's sequence
#Scheme
Scheme
(define sylvester (lambda (x) (if (= x 1) 2 (let ((n (sylvester (- x 1)))) (- (* n n) n -1))))) (define list (map sylvester '(1 2 3 4 5 6 7 8 9 10))) (print list) (newline) (print (apply + (map / list)))
http://rosettacode.org/wiki/Sylvester%27s_sequence
Sylvester's sequence
This page uses content from Wikipedia. The original article was at Sylvester's sequence. 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 number theory, Sylvester's sequence is an integer sequence in which each term of the sequence is the product of the previous terms, plus one. Its values grow doubly exponentially, and the sum of its reciprocals forms a series of unit fractions that converges to 1 more rapidly than any other series of unit fractions with the same number of terms. Further, the sum of the first k terms of the infinite series of reciprocals provides the closest possible underestimate of 1 by any k-term Egyptian fraction. Task Write a routine (function, procedure, generator, whatever) to calculate Sylvester's sequence. Use that routine to show the values of the first 10 elements in the sequence. Show the sum of the reciprocals of the first 10 elements on the sequence, ideally as an exact fraction. Related tasks Egyptian fractions Harmonic series See also OEIS A000058 - Sylvester's sequence
#Seed7
Seed7
$ include "seed7_05.s7i"; include "bigint.s7i"; include "bigrat.s7i";   const func bigInteger: nextSylvester (in bigInteger: prev) is return prev * prev - prev + 1_;   const proc: main is func local var bigInteger: number is 2_; var bigRational: reciprocalSum is 0_ / 1_; var integer: n is 0; begin writeln("First 10 elements of Sylvester's sequence:"); for n range 1 to 10 do writeln(number); reciprocalSum +:= 1_ / number; number := nextSylvester(number); end for; writeln("\nSum of the reciprocals of the first 10 elements:"); writeln(reciprocalSum digits 210); end func;
http://rosettacode.org/wiki/Sylvester%27s_sequence
Sylvester's sequence
This page uses content from Wikipedia. The original article was at Sylvester's sequence. 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 number theory, Sylvester's sequence is an integer sequence in which each term of the sequence is the product of the previous terms, plus one. Its values grow doubly exponentially, and the sum of its reciprocals forms a series of unit fractions that converges to 1 more rapidly than any other series of unit fractions with the same number of terms. Further, the sum of the first k terms of the infinite series of reciprocals provides the closest possible underestimate of 1 by any k-term Egyptian fraction. Task Write a routine (function, procedure, generator, whatever) to calculate Sylvester's sequence. Use that routine to show the values of the first 10 elements in the sequence. Show the sum of the reciprocals of the first 10 elements on the sequence, ideally as an exact fraction. Related tasks Egyptian fractions Harmonic series See also OEIS A000058 - Sylvester's sequence
#Sidef
Sidef
func sylvester_sequence(n) { 1..n -> reduce({|a| a*(a-1) + 1 }, 2) }   say "First 10 terms in Sylvester's sequence:" 10.of(sylvester_sequence).each_kv{|k,v| '%2s: %s' % (k,v) -> say }   say "\nSum of reciprocals of first 10 terms: " say 10.of(sylvester_sequence).sum {|n| 1/n }.as_dec(230)
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).
#Lua
Lua
sums, taxis, limit = {}, {}, 1200 for i = 1, limit do for j = 1, i-1 do sum = i^3 + j^3 sums[sum] = sums[sum] or {} table.insert(sums[sum], i.."^3 + "..j.."^3") end end for k,v in pairs(sums) do if #v > 1 then table.insert(taxis, { sum=k, num=#v, terms=table.concat(v," = ") }) end end table.sort(taxis, function(a,b) return a.sum<b.sum end) for i=1,2006 do if i<=25 or i>=2000 or taxis[i].num==3 then print(string.format("%4d%s: %10d = %s", i, taxis[i].num==3 and "*" or " ", taxis[i].sum, taxis[i].terms)) end end print("* n=3")
http://rosettacode.org/wiki/Superpermutation_minimisation
Superpermutation minimisation
A superpermutation of N different characters is a string consisting of an arrangement of multiple copies of those N different characters in which every permutation of those characters can be found as a substring. For example, representing the characters as A..Z, using N=2 we choose to use the first two characters 'AB'. The permutations of 'AB' are the two, (i.e. two-factorial), strings: 'AB' and 'BA'. A too obvious method of generating a superpermutation is to just join all the permutations together forming 'ABBA'. A little thought will produce the shorter (in fact the shortest) superpermutation of 'ABA' - it contains 'AB' at the beginning and contains 'BA' from the middle to the end. The "too obvious" method of creation generates a string of length N!*N. Using this as a yardstick, the task is to investigate other methods of generating superpermutations of N from 1-to-7 characters, that never generate larger superpermutations. Show descriptions and comparisons of algorithms used here, and select the "Best" algorithm as being the one generating shorter superpermutations. The problem of generating the shortest superpermutation for each N might be NP complete, although the minimal strings for small values of N have been found by brute -force searches. 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 Reference The Minimal Superpermutation Problem. by Nathaniel Johnston. oeis A180632 gives 0-5 as 0, 1, 3, 9, 33, 153. 6 is thought to be 872. Superpermutations - Numberphile. A video Superpermutations: the maths problem solved by 4chan - Standupmaths. A video of recent (2018) mathematical progress. New Superpermutations Discovered! Standupmaths & Numberphile.
#Mathematica_.2F_Wolfram_Language
Mathematica / Wolfram Language
ClearAll[OverlapDistance, ConstructDistances] OverlapDistance[{s1_List, s2_List}] := OverlapDistance[s1, s2] OverlapDistance[s1_List, s2_List] := Module[{overlaprange, overlap, l}, overlaprange = {Min[Length[s1], Length[s2]], 0}; l = LengthWhile[Range[Sequence @@ overlaprange, -1], Take[s1, -#] =!= Take[s2, #] &]; overlap = overlaprange[[1]] - l; <|"Overlap" -> overlap, "Distance" -> Length[s2] - overlap|> ] ConstructDistances[perms_List] := Module[{sel, OD, fullseq}, OD = BlockMap[OverlapDistance, perms, 2, 1]; fullseq = Fold[Join[#1, Drop[#2[[2]], #2[[1]]["Overlap"]]] &, First[perms], {OD, Rest[perms]} // Transpose]; fullseq ] Dynamic[Length[perms]] Do[ n = i; perms = Permutations[Range[n]]; {start, perms} = TakeDrop[perms, 1]; While[Length[perms] > 0, last = Last[start]; dists = Table[<|"Index" -> i, OverlapDistance[last, perms[[i]]]|>, {i, Length[perms]}]; sel = First[TakeSmallestBy[dists, #["Distance"] &, 1]]; AppendTo[start, perms[[sel["Index"]]]]; perms = Delete[perms, sel["Index"]]; ]; Print[{n, Length@ConstructDistances[start]}] , {i, 1, 7} ]
http://rosettacode.org/wiki/Superpermutation_minimisation
Superpermutation minimisation
A superpermutation of N different characters is a string consisting of an arrangement of multiple copies of those N different characters in which every permutation of those characters can be found as a substring. For example, representing the characters as A..Z, using N=2 we choose to use the first two characters 'AB'. The permutations of 'AB' are the two, (i.e. two-factorial), strings: 'AB' and 'BA'. A too obvious method of generating a superpermutation is to just join all the permutations together forming 'ABBA'. A little thought will produce the shorter (in fact the shortest) superpermutation of 'ABA' - it contains 'AB' at the beginning and contains 'BA' from the middle to the end. The "too obvious" method of creation generates a string of length N!*N. Using this as a yardstick, the task is to investigate other methods of generating superpermutations of N from 1-to-7 characters, that never generate larger superpermutations. Show descriptions and comparisons of algorithms used here, and select the "Best" algorithm as being the one generating shorter superpermutations. The problem of generating the shortest superpermutation for each N might be NP complete, although the minimal strings for small values of N have been found by brute -force searches. 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 Reference The Minimal Superpermutation Problem. by Nathaniel Johnston. oeis A180632 gives 0-5 as 0, 1, 3, 9, 33, 153. 6 is thought to be 872. Superpermutations - Numberphile. A video Superpermutations: the maths problem solved by 4chan - Standupmaths. A video of recent (2018) mathematical progress. New Superpermutations Discovered! Standupmaths & Numberphile.
#Nim
Nim
import strformat   const MAX = 12   var super: seq[char] = @[] var pos: int var cnt: array[MAX, int]   proc factSum(n: int): int = var s, x = 0 var f = 1 while x < n: inc x f *= x inc s, f s   proc r(n: int): bool = if n == 0: return false var c = super[pos - n] dec cnt[n] if cnt[n] == 0: cnt[n] = n if not r(n - 1): return false super[pos] = c inc pos true   proc superperm(n: int) = pos = n var le = factSum(n) super.setLen(le) for i in 0..n: cnt[i] = i for i in 1..n: super[i-1] = char(i + ord('0')) while r(n): discard for n in 0..<MAX: write(stdout, fmt"superperm({n:2})") superperm(n) writeLine(stdout, fmt" len = {len(super)}")
http://rosettacode.org/wiki/Superpermutation_minimisation
Superpermutation minimisation
A superpermutation of N different characters is a string consisting of an arrangement of multiple copies of those N different characters in which every permutation of those characters can be found as a substring. For example, representing the characters as A..Z, using N=2 we choose to use the first two characters 'AB'. The permutations of 'AB' are the two, (i.e. two-factorial), strings: 'AB' and 'BA'. A too obvious method of generating a superpermutation is to just join all the permutations together forming 'ABBA'. A little thought will produce the shorter (in fact the shortest) superpermutation of 'ABA' - it contains 'AB' at the beginning and contains 'BA' from the middle to the end. The "too obvious" method of creation generates a string of length N!*N. Using this as a yardstick, the task is to investigate other methods of generating superpermutations of N from 1-to-7 characters, that never generate larger superpermutations. Show descriptions and comparisons of algorithms used here, and select the "Best" algorithm as being the one generating shorter superpermutations. The problem of generating the shortest superpermutation for each N might be NP complete, although the minimal strings for small values of N have been found by brute -force searches. 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 Reference The Minimal Superpermutation Problem. by Nathaniel Johnston. oeis A180632 gives 0-5 as 0, 1, 3, 9, 33, 153. 6 is thought to be 872. Superpermutations - Numberphile. A video Superpermutations: the maths problem solved by 4chan - Standupmaths. A video of recent (2018) mathematical progress. New Superpermutations Discovered! Standupmaths & Numberphile.
#Objeck
Objeck
class SuperPermutation { @super : static : Char[]; @pos : static : Int; @cnt : static : Int[];   function : Main(args : String[]) ~ Nil { max := 12; @cnt := Int->New[max]; @super := Char->New[0];   for(n := 0; n < max; n += 1;) { "superperm({$n}) "->Print(); SuperPerm(n); len := @super->Size() - 1; "len = {$len}"->PrintLine(); }; }   function : native : FactSum(n : Int) ~ Int { s := 0; x := 0; f := 1; while(x < n) { f *= ++x; s += f; }; return s; }   function : native : R(n : Int) ~ Bool { if(n = 0) { return false; };   c := @super[@pos - n]; if(--@cnt[n] = 0) { @cnt[n] := n; if(<>R(n - 1)) { return false; }; }; @super[@pos++] := c;   return true; }   function : SuperPerm(n : Int) ~ Nil { @pos := n; len := FactSum(n);   tmp := Char->New[len + 1]; Runtime->Copy(tmp, 0, @super, 0, @super->Size()); @super := tmp;   for(i := 0; i <= n; i += 1;) { @cnt[i] := i; };   for(i := 1; i <= n; i += 1;) { @super[i - 1] := i + '0'; };   do { r := R(n); } while(r); } }  
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
#Rust
Rust
  /// Gets all divisors of a number, including itself fn get_divisors(n: u32) -> Vec<u32> { let mut results = Vec::new();   for i in 1..(n / 2 + 1) { if n % i == 0 { results.push(i); } } results.push(n); results }   fn is_tau_number(i: u32) -> bool { 0 == i % get_divisors(i).len() as u32 }   fn main() { println!("\nFirst 100 Tau numbers:"); let mut counter: u32 = 0; let mut i: u32 = 1; while counter < 100 { if is_tau_number(i) { print!("{:>4}", i); counter += 1; print!("{}", if counter % 20 == 0 { "\n" } else { "," }); } i += 1; } }    
http://rosettacode.org/wiki/Tau_number
Tau number
A Tau number is a positive integer divisible by the count of its positive divisors. Task Show the first   100   Tau numbers. The numbers shall be generated during run-time (i.e. the code may not contain string literals, sets/arrays of integers, or alike). Related task  Tau function
#Sidef
Sidef
func is_tau_number(n) { n % n.sigma0 == 0 }   say is_tau_number.first(100).join(' ')
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
#Swift
Swift
import Foundation   // See https://en.wikipedia.org/wiki/Divisor_function func divisorCount(number: Int) -> Int { var n = number var total = 1 // Deal with powers of 2 first while (n & 1) == 0 { total += 1 n >>= 1 } // Odd prime factors up to the square root var p = 3 while p * p <= n { var count = 1 while n % p == 0 { count += 1 n /= p } total *= count p += 2 } // If n > 1 then it's prime if n > 1 { total *= 2 } return total }   let limit = 100 print("The first \(limit) tau numbers are:") var count = 0 var n = 1 while count < limit { if n % divisorCount(number: n) == 0 { print(String(format: "%5d", n), terminator: "") count += 1 if count % 10 == 0 { print() } } n += 1 }
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
#C.2B.2B
C++
  #include <iostream> #include <iomanip>   //-------------------------------------------------------------------------------------------------- using namespace std;   //-------------------------------------------------------------------------------------------------- class converter { public: converter() : KTC( 273.15f ), KTDel( 3.0f / 2.0f ), KTF( 9.0f / 5.0f ), KTNew( 33.0f / 100.0f ), KTRank( 9.0f / 5.0f ), KTRe( 4.0f / 5.0f ), KTRom( 21.0f / 40.0f ) {}   void convert( float kelvin ) { float cel = kelvin - KTC, del = ( 373.15f - kelvin ) * KTDel, fah = kelvin * KTF - 459.67f, net = cel * KTNew, rnk = kelvin * KTRank, rea = cel * KTRe, rom = cel * KTRom + 7.5f;   cout << endl << left << "TEMPERATURES:" << endl << "===============" << endl << setw( 13 ) << "CELSIUS:" << cel << endl << setw( 13 ) << "DELISLE:" << del << endl << setw( 13 ) << "FAHRENHEIT:" << fah << endl << setw( 13 ) << "KELVIN:" << kelvin << endl << setw( 13 ) << "NEWTON:" << net << endl << setw( 13 ) << "RANKINE:" << rnk << endl << setw( 13 ) << "REAUMUR:" << rea << endl << setw( 13 ) << "ROMER:" << rom << endl << endl << endl; } private: const float KTRank, KTC, KTF, KTRe, KTDel, KTNew, KTRom; }; //-------------------------------------------------------------------------------------------------- int main( int argc, char* argv[] ) { converter con; float k; while( true ) { cout << "Enter the temperature in Kelvin to convert: "; cin >> k; con.convert( k ); system( "pause" ); system( "cls" ); } return 0; } //--------------------------------------------------------------------------------------------------  
http://rosettacode.org/wiki/Tau_function
Tau function
Given a positive integer, count the number of its positive divisors. Task Show the result for the first   100   positive integers. Related task  Tau number
#PL.2FI
PL/I
taufunc: procedure options(main); tau: procedure(nn) returns(fixed); declare (n, nn, tot, pf, cnt) fixed; tot = 1; do n=nn repeat(n/2) while(mod(n,2)=0); tot = tot + 1; end; do pf=3 repeat(pf+2) while(pf*pf<=n); do cnt=1 repeat(cnt+1) while(mod(n,pf)=0); n = n/pf; end; tot = tot * cnt; end; if n>1 then tot = tot * 2; return(tot); end tau;   declare n fixed; do n=1 to 100; put edit(tau(n)) (F(3)); if mod(n,20)=0 then put skip; end; end taufunc;
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
#PL.2FM
PL/M
100H:   /* CP/M BDOS FUNCTIONS */ BDOS: PROCEDURE(F,A); DECLARE F BYTE, A ADDRESS; GO TO 5; END BDOS; EXIT: PROCEDURE; GO TO 0; END EXIT; PR$CHAR: PROCEDURE(C); DECLARE C BYTE; CALL BDOS(2,C); END PR$CHAR; PR$STR: PROCEDURE(S); DECLARE S ADDRESS; CALL BDOS(9,S); END PR$STR;   /* PRINT BYTE IN A 3-CHAR COLUMN */ PRINT3: PROCEDURE(N); DECLARE (N, M) BYTE; M = 100; DO WHILE M>0; IF N>=M THEN CALL PR$CHAR('0' + (N/M) MOD 10); ELSE CALL PR$CHAR(' '); M = M/10; END; END PRINT3;   /* TAU FUNCTION */ TAU: PROCEDURE(N) BYTE; DECLARE (N, TOTAL, COUNT, P) BYTE; TOTAL = 1; DO WHILE NOT N; N = SHR(N,1); TOTAL = TOTAL + 1; END; P = 3; DO WHILE P*P <= N; COUNT = 1; DO WHILE N MOD P = 0; COUNT = COUNT + 1; N = N / P; END; TOTAL = TOTAL * COUNT; P = P + 2; END; IF N>1 THEN TOTAL = SHL(TOTAL, 1); RETURN TOTAL; END TAU;   /* PRINT TAU 1..100 */ DECLARE N BYTE; DO N=1 TO 100; CALL PRINT3(TAU(N)); IF N MOD 20=0 THEN CALL PR$STR(.(13,10,'$')); END; CALL EXIT; EOF
http://rosettacode.org/wiki/Terminal_control/Clear_the_screen
Terminal control/Clear the screen
Task Clear the terminal window.
#Racket
Racket
  #lang racket (require (planet neil/charterm:3:0)) (with-charterm (void (charterm-clear-screen)))  
http://rosettacode.org/wiki/Terminal_control/Clear_the_screen
Terminal control/Clear the screen
Task Clear the terminal window.
#Raku
Raku
sub clear { print qx[clear] } clear;
http://rosettacode.org/wiki/Terminal_control/Clear_the_screen
Terminal control/Clear the screen
Task Clear the terminal window.
#Retro
Retro
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
#Pascal
Pascal
Program TernaryLogic (output);   type trit = (terTrue, terMayBe, terFalse);   function terNot (a: trit): trit; begin case a of terTrue: terNot := terFalse; terMayBe: terNot := terMayBe; terFalse: terNot := terTrue; end; end;   function terAnd (a, b: trit): trit; begin terAnd := terMayBe; if (a = terFalse) or (b = terFalse) then terAnd := terFalse else if (a = terTrue) and (b = terTrue) then terAnd := terTrue; end;   function terOr (a, b: trit): trit; begin terOr := terMayBe; if (a = terTrue) or (b = terTrue) then terOr := terTrue else if (a = terFalse) and (b = terFalse) then terOr := terFalse; end;   function terEquals (a, b: trit): trit; begin if a = b then terEquals := terTrue else if a <> b then terEquals := terFalse; if (a = terMayBe) or (b = terMayBe) then terEquals := terMayBe; end;   function terIfThen (a, b: trit): trit; begin terIfThen := terMayBe; if (a = terTrue) or (b = terFalse) then terIfThen := terTrue else if (a = terFalse) and (b = terTrue) then terIfThen := terFalse; end;   function terToStr(a: trit): string; begin case a of terTrue: terToStr := 'True '; terMayBe: terToStr := 'Maybe'; terFalse: terToStr := 'False'; end; end;   begin writeln('Ternary logic test:'); writeln; writeln('NOT ', ' True ', ' Maybe', ' False'); writeln(' ', terToStr(terNot(terTrue)), ' ', terToStr(terNot(terMayBe)), ' ', terToStr(terNot(terFalse))); writeln; writeln('AND ', ' True ', ' Maybe', ' False'); writeln('True ', terToStr(terAnd(terTrue,terTrue)), ' ', terToStr(terAnd(terMayBe,terTrue)), ' ', terToStr(terAnd(terFalse,terTrue))); writeln('Maybe ', terToStr(terAnd(terTrue,terMayBe)), ' ', terToStr(terAnd(terMayBe,terMayBe)), ' ', terToStr(terAnd(terFalse,terMayBe))); writeln('False ', terToStr(terAnd(terTrue,terFalse)), ' ', terToStr(terAnd(terMayBe,terFalse)), ' ', terToStr(terAnd(terFalse,terFalse))); writeln; writeln('OR ', ' True ', ' Maybe', ' False'); writeln('True ', terToStr(terOR(terTrue,terTrue)), ' ', terToStr(terOR(terMayBe,terTrue)), ' ', terToStr(terOR(terFalse,terTrue))); writeln('Maybe ', terToStr(terOR(terTrue,terMayBe)), ' ', terToStr(terOR(terMayBe,terMayBe)), ' ', terToStr(terOR(terFalse,terMayBe))); writeln('False ', terToStr(terOR(terTrue,terFalse)), ' ', terToStr(terOR(terMayBe,terFalse)), ' ', terToStr(terOR(terFalse,terFalse))); writeln; writeln('IFTHEN', ' True ', ' Maybe', ' False'); writeln('True ', terToStr(terIfThen(terTrue,terTrue)), ' ', terToStr(terIfThen(terMayBe,terTrue)), ' ', terToStr(terIfThen(terFalse,terTrue))); writeln('Maybe ', terToStr(terIfThen(terTrue,terMayBe)), ' ', terToStr(terIfThen(terMayBe,terMayBe)), ' ', terToStr(terIfThen(terFalse,terMayBe))); writeln('False ', terToStr(terIfThen(terTrue,terFalse)), ' ', terToStr(terIfThen(terMayBe,terFalse)), ' ', terToStr(terIfThen(terFalse,terFalse))); writeln; writeln('EQUAL ', ' True ', ' Maybe', ' False'); writeln('True ', terToStr(terEquals(terTrue,terTrue)), ' ', terToStr(terEquals(terMayBe,terTrue)), ' ', terToStr(terEquals(terFalse,terTrue))); writeln('Maybe ', terToStr(terEquals(terTrue,terMayBe)), ' ', terToStr(terEquals(terMayBe,terMayBe)), ' ', terToStr(terEquals(terFalse,terMayBe))); writeln('False ', terToStr(terEquals(terTrue,terFalse)), ' ', terToStr(terEquals(terMayBe,terFalse)), ' ', terToStr(terEquals(terFalse,terFalse))); writeln; 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.
#Python
Python
import fileinput import sys   nodata = 0; # Current run of consecutive flags<0 in lines of file nodata_max=-1; # Max consecutive flags<0 in lines of file nodata_maxline=[]; # ... and line number(s) where it occurs   tot_file = 0 # Sum of file data num_file = 0 # Number of file data items with flag>0   infiles = sys.argv[1:]   for line in fileinput.input(): tot_line=0; # sum of line data num_line=0; # number of line data items with flag>0   # extract field info field = line.split() date = field[0] data = [float(f) for f in field[1::2]] flags = [int(f) for f in field[2::2]]   for datum, flag in zip(data, flags): if flag<1: nodata += 1 else: # check run of data-absent fields if nodata_max==nodata and nodata>0: nodata_maxline.append(date) if nodata_max<nodata and nodata>0: nodata_max=nodata nodata_maxline=[date] # re-initialise run of nodata counter nodata=0; # gather values for averaging tot_line += datum num_line += 1   # totals for the file so far tot_file += tot_line num_file += num_line   print "Line: %11s Reject: %2i Accept: %2i Line_tot: %10.3f Line_avg: %10.3f" % ( date, len(data) -num_line, num_line, tot_line, tot_line/num_line if (num_line>0) else 0)   print "" print "File(s) = %s" % (", ".join(infiles),) print "Total = %10.3f" % (tot_file,) print "Readings = %6i" % (num_file,) print "Average = %10.3f" % (tot_file / num_file,)   print "\nMaximum run(s) of %i consecutive false readings ends at line starting with date(s): %s" % ( nodata_max, ", ".join(nodata_maxline))
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
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
daysarray = {"first", "second", "third", "fourth", "fifth", "sixth", "seventh", "eighth", "ninth", "tenth", "eleventh", "twelfth"}; giftsarray = {"And a partridge in a pear tree.", "Two turtle doves", "Three french hens", "Four calling birds", "FIVE GOLDEN RINGS", "Six geese a-laying", "Seven swans a-swimming,", "Eight maids a-milking", "Nine ladies dancing", "Ten lords a-leaping", "Eleven pipers piping", "Twelve drummers drumming"}; Do[Print[StringForm[ "On the `1` day of Christmas, my true love gave to me: `2`", daysarray[[i]], If[i == 1, "A partridge in a pear tree.", Row[Reverse[Take[giftsarray, i]], ","]]]], {i, 1, 12}]
http://rosettacode.org/wiki/Terminal_control/Coloured_text
Terminal control/Coloured text
Task Display a word in various colours on the terminal. The system palette, or colours such as Red, Green, Blue, Magenta, Cyan, and Yellow can be used. Optionally demonstrate: How the system should determine if the terminal supports colour Setting of the background colour How to cause blinking or flashing (if supported by the terminal)
#XPL0
XPL0
code ChOut=8, Attrib=69; def Black, Blue, Green, Cyan, Red, Magenta, Brown, White, \attribute colors Gray, LBlue, LGreen, LCyan, LRed, LMagenta, Yellow, BWhite; \EGA palette [ChOut(6,^C); \default white on black background Attrib(Red<<4+White); \white on red ChOut(6,^o); Attrib(Green<<4+Red); \red on green ChOut(6,^l); Attrib(Blue<<4+LGreen); \light green on blue ChOut(6,^o); Attrib(LRed<<4+White); \flashing white on (standard/dim) red ChOut(6,^u); Attrib(Cyan<<4+Black); \black on cyan ChOut(6,^r); ]
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)
#zkl
zkl
fcn table(title,mode){ println("\n\e[1m%s\e[m\n bg\t fg".fmt(title)); foreach b in ([40..48].chain([100..107])){ print("%3d\t\e[%s%dm".fmt(b,mode,b)); foreach f in ([30..38].chain([90..97])){ print("\e[%dm%3d ".fmt(f,f)) } println("\e[m"); } }   table("normal ( ESC[22m or ESC[m )", "22;"); table("bold ( ESC[1m )", "1;"); table("faint ( ESC[2m ), not well supported", "2;"); table("italic ( ESC[3m ), not well supported", "3;"); table("underline ( ESC[4m ), support varies", "4;"); table("blink ( ESC[5m )", "5;"); table("inverted ( ESC[7m )", "7;");
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)
#ZX_Spectrum_Basic
ZX Spectrum Basic
10 FOR l=0 TO 7 20 READ c$: REM get our text for display 30 INK l: REM set the text colour 40 PRINT c$ 50 NEXT l 60 PAPER 2: REM red background 70 INK 6: REM yellow forground 80 FLASH 1: REM activate flashing 90 PRINT "Flashing!": REM this will flash red and yellow (alternating inverse) 100 PAPER 7: INK 0: FLASH 0: REM normalize colours before exit 110 STOP   900 DATA "Black","Blue","Red","Magenta","Green","Cyan","Yellow","White"
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.
#Haskell
Haskell
import Control.Concurrent import Control.Concurrent.MVar   main = do lineVar <- newEmptyMVar countVar <- newEmptyMVar   let takeLine = takeMVar lineVar putLine = putMVar lineVar . Just putEOF = putMVar lineVar Nothing takeCount = takeMVar countVar putCount = putMVar countVar   forkIO $ writer takeLine putCount reader putLine putEOF takeCount
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.
#Icon_and_Unicon
Icon and Unicon
procedure main(A) fName := A[1]|"index.txt" p := thread produce(fName) c := thread consume(p) every wait(p | c) end   procedure produce(fName) every !open(fName)@>> # drop messages in p's outbox (blocking whenever box is full) @>> # Signal consumer that p is done write("count is ",<<@) # block until message in p's inbox end   procedure consume(p) i := 0 while write(\<<@p) do (i+:=1) # loop until empty message in p's outbox # (blocking until each message arrives) i@>>p # put row count into p's inbox end