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/Achilles_numbers
Achilles numbers
This page uses content from Wikipedia. The original article was at Achilles number. 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) An Achilles number is a number that is powerful but imperfect. Named after Achilles, a hero of the Trojan war, who was also powerful but imperfect. A positive integer n is a powerful number if, for every prime factor p of n, p2 is also a divisor. In other words, every prime factor appears at least squared in the factorization. All Achilles numbers are powerful. However, not all powerful numbers are Achilles numbers: only those that cannot be represented as mk, where m and k are positive integers greater than 1. A strong Achilles number is an Achilles number whose Euler totient (𝜑) is also an Achilles number. E.G. 108 is a powerful number. Its prime factorization is 22 × 33, and thus its prime factors are 2 and 3. Both 22 = 4 and 32 = 9 are divisors of 108. However, 108 cannot be represented as mk, where m and k are positive integers greater than 1, so 108 is an Achilles number. 360 is not an Achilles number because it is not powerful. One of its prime factors is 5 but 360 is not divisible by 52 = 25. Finally, 784 is not an Achilles number. It is a powerful number, because not only are 2 and 7 its only prime factors, but also 22 = 4 and 72 = 49 are divisors of it. Nonetheless, it is a perfect power; its square root is an even integer, so it is not an Achilles number. 500 = 22 × 53 is a strong Achilles number as its Euler totient, 𝜑(500), is 200 = 23 × 52 which is also an Achilles number. Task Find and show the first 50 Achilles numbers. Find and show at least the first 20 strong Achilles numbers. For at least 2 through 5, show the count of Achilles numbers with that many digits. See also Wikipedia: Achilles number OEIS:A052486 - Achilles numbers - powerful but imperfect numbers OEIS:A194085 - Strong Achilles numbers: Achilles numbers m such that phi(m) is also an Achilles number Related task: Powerful numbers Related task: Totient function
#XPL0
XPL0
func GCD(N, D); \Return the greatest common divisor of N and D int N, D; \numerator and denominator int R; [if D > N then [R:= D; D:= N; N:= R]; \swap D and N while D > 0 do [R:= rem(N/D); N:= D; D:= R; ]; return N; ]; \GCD   func Totient(N); \Return the totient of N int N, Phi, M; [Phi:= 0; for M:= 1 to N do if GCD(M, N) = 1 then Phi:= Phi+1; return Phi; ];   func Powerful(N0); \Return 'true' if N0 is a powerful number int N0, N, F, Q, L; [if N0 <= 1 then return false; N:= N0; F:= 2; L:= sqrt(N0); loop [Q:= N/F; if rem(0) = 0 then \found a factor [if rem(N0/(F*F)) then return false; N:= Q; if F>N then quit; ] else [F:= F+1; if F > L then [if rem(N0/(N*N)) then return false; quit; ]; ]; ]; return true; ];   func Achilles(N); \Return 'true' if N is an Achilles number int N, M, A; [if not Powerful(N) then return false; M:= 2; A:= M*M; repeat loop [if A = N then return false; if A > N then quit; A:= A*M; ]; M:= M+1; A:= M*M; until A > N; return true; ];   int Cnt, N, Pwr, Start; [Cnt:= 0; N:= 1; loop [if Achilles(N) then [IntOut(0, N); Cnt:= Cnt+1; if Cnt >= 50 then quit; if rem(Cnt/10) then ChOut(0, 9) else CrLf(0); ]; N:= N+1; ]; CrLf(0); CrLf(0); Cnt:= 0; N:= 1; loop [if Achilles(N) then if Achilles(Totient(N)) then [IntOut(0, N); Cnt:= Cnt+1; if Cnt >= 20 then quit; if rem(Cnt/10) then ChOut(0, 9) else CrLf(0); ]; N:= N+1; ]; CrLf(0); CrLf(0); for Pwr:= 1 to 6 do [IntOut(0, Pwr); Text(0, ": "); Start:= fix(Pow(10.0, float(Pwr-1))); Cnt:= 0; for N:= Start to Start*10-1 do if Achilles(N) then Cnt:= Cnt+1; IntOut(0, Cnt); CrLf(0); ]; ]
http://rosettacode.org/wiki/Aliquot_sequence_classifications
Aliquot sequence classifications
An aliquot sequence of a positive integer K is defined recursively as the first member being K and subsequent members being the sum of the Proper divisors of the previous term. If the terms eventually reach 0 then the series for K is said to terminate. There are several classifications for non termination: If the second term is K then all future terms are also K and so the sequence repeats from the first term with period 1 and K is called perfect. If the third term would be repeating K then the sequence repeats with period 2 and K is called amicable. If the Nth term would be repeating K for the first time, with N > 3 then the sequence repeats with period N - 1 and K is called sociable. Perfect, amicable and sociable numbers eventually repeat the original number K; there are other repetitions... Some K have a sequence that eventually forms a periodic repetition of period 1 but of a number other than K, for example 95 which forms the sequence 95, 25, 6, 6, 6, ... such K are called aspiring. K that have a sequence that eventually forms a periodic repetition of period >= 2 but of a number other than K, for example 562 which forms the sequence 562, 284, 220, 284, 220, ... such K are called cyclic. And finally: Some K form aliquot sequences that are not known to be either terminating or periodic; these K are to be called non-terminating. For the purposes of this task, K is to be classed as non-terminating if it has not been otherwise classed after generating 16 terms or if any term of the sequence is greater than 2**47 = 140,737,488,355,328. Task Create routine(s) to generate the aliquot sequence of a positive integer enough to classify it according to the classifications given above. Use it to display the classification and sequences of the numbers one to ten inclusive. Use it to show the classification and sequences of the following integers, in order: 11, 12, 28, 496, 220, 1184, 12496, 1264460, 790, 909, 562, 1064, 1488, and optionally 15355717786080. Show all output on this page. Related tasks   Abundant, deficient and perfect number classifications. (Classifications from only the first two members of the whole sequence).   Proper divisors   Amicable pairs
#jq
jq
# "until" is available in more recent versions of jq # than jq 1.4 def until(cond; next): def _until: if cond then . else (next|_until) end; _until;   # unordered def proper_divisors: . as $n | if $n > 1 then 1, ( range(2; 1 + (sqrt|floor)) as $i | if ($n % $i) == 0 then $i, (($n / $i) | if . == $i then empty else . end) else empty end) else empty end;   # sum of proper divisors, or 0 def pdsum: [proper_divisors] | add // 0;   # input is n # maxlen defaults to 16; # maxterm defaults to 2^47 def aliquot(maxlen; maxterm): (maxlen // 15) as $maxlen | (maxterm // 40737488355328) as $maxterm | if . == 0 then "terminating at 0" else # [s, slen, new] = [[n], 1, n] [ [.], 1, .] | until( type == "string" or .[1] > $maxlen or .[2] > $maxterm; .[0] as $s | .[1] as $slen | ($s | .[length-1] | pdsum) as $new | if ($s|index($new)) then if $s[0] == $new then if $slen == 1 then "perfect \($s)" elif $slen == 2 then "amicable: \($s)" else "sociable of length \($slen): \($s)" end elif ($s | .[length-1]) == $new then "aspiring: \($s)" else "cyclic back to \($new): \($s)" end elif $new == 0 then "terminating: \($s + [0])" else [ ($s + [$new]), ($slen + 1), $new ] end ) | if type == "string" then . else "non-terminating: \(.[0])" end end;   def task: def pp: "\(.): \(aliquot(null;null))"; (range(1; 11) | pp), "", ((11, 12, 28, 496, 220, 1184, 12496, 1264460, 790, 909, 562, 1064, 1488, 15355717786080) | pp);   task
http://rosettacode.org/wiki/Add_a_variable_to_a_class_instance_at_runtime
Add a variable to a class instance at runtime
Demonstrate how to dynamically add variables to an object (a class instance) at runtime. This is useful when the methods/variables of an instance are based on a data file that isn't available until runtime. Hal Fulton gives an example of creating an OO CSV parser at An Exercise in Metaprogramming with Ruby. This is referred to as "monkeypatching" by Pythonistas and some others.
#REBOL
REBOL
  rebol [ Title: "Add Variables to Class at Runtime" URL: http://rosettacode.org/wiki/Adding_variables_to_a_class_instance_at_runtime ]   ; As I understand it, a REBOL object can only ever have whatever ; properties it was born with. However, this is somewhat offset by the ; fact that every instance can serve as a prototype for a new object ; that also has the new parameter you want to add.   ; Here I create an empty instance of the base object (x), then add the ; new instance variable while creating a new object prototyped from ; x. I assign the new object to x, et voila', a dynamically added ; variable.   x: make object! [] ; Empty object.   x: make x [ newvar: "forty-two" ; New property. ]   print "Empty object modifed with 'newvar' property:" probe x   ; A slightly more interesting example:   starfighter: make object! [ model: "unknown" pilot: none ] x-wing: make starfighter [ model: "Incom T-65 X-wing" ]   squadron: reduce [ make x-wing [pilot: "Luke Skywalker"] make x-wing [pilot: "Wedge Antilles"] make starfighter [ model: "Slayn & Korpil B-wing" pilot: "General Salm" ] ]   ; Adding new property here. squadron/1: make squadron/1 [deathstar-removal-expert: yes]   print [crlf "Fighter squadron:"] foreach pilot squadron [probe pilot]  
http://rosettacode.org/wiki/Add_a_variable_to_a_class_instance_at_runtime
Add a variable to a class instance at runtime
Demonstrate how to dynamically add variables to an object (a class instance) at runtime. This is useful when the methods/variables of an instance are based on a data file that isn't available until runtime. Hal Fulton gives an example of creating an OO CSV parser at An Exercise in Metaprogramming with Ruby. This is referred to as "monkeypatching" by Pythonistas and some others.
#Red
Red
person: make object! [ name: none age: none ]   people: reduce [make person [name: "fred" age: 20] make person [name: "paul" age: 21]] people/1: make people/1 [skill: "fishing"]   foreach person people [ print reduce [person/age "year old" person/name "is good at" any [select person 'skill "nothing"]] ]
http://rosettacode.org/wiki/Add_a_variable_to_a_class_instance_at_runtime
Add a variable to a class instance at runtime
Demonstrate how to dynamically add variables to an object (a class instance) at runtime. This is useful when the methods/variables of an instance are based on a data file that isn't available until runtime. Hal Fulton gives an example of creating an OO CSV parser at An Exercise in Metaprogramming with Ruby. This is referred to as "monkeypatching" by Pythonistas and some others.
#Ring
Ring
o1 = new point addattribute(o1,"x") addattribute(o1,"y") addattribute(o1,"z") see o1 {x=10 y=20 z=30} class point
http://rosettacode.org/wiki/Address_of_a_variable
Address of a variable
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation | Comparison | Matching Memory Operations Pointers & references | Addresses Task Demonstrate how to get the address of a variable and how to set the address of a variable.
#R
R
  x <- 5 y <- x pryr::address(x) pryr::address(y)   y <- y + 1   pryr::address(x) pryr::address(y)  
http://rosettacode.org/wiki/Address_of_a_variable
Address of a variable
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation | Comparison | Matching Memory Operations Pointers & references | Addresses Task Demonstrate how to get the address of a variable and how to set the address of a variable.
#Racket
Racket
#lang racket   (require ffi/unsafe)   (define (madness v) ; i'm so sorry (cast v _racket _gcpointer))
http://rosettacode.org/wiki/Address_of_a_variable
Address of a variable
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation | Comparison | Matching Memory Operations Pointers & references | Addresses Task Demonstrate how to get the address of a variable and how to set the address of a variable.
#Raku
Raku
my $x; say $x.WHERE;   my $y := $x; # alias say $y.WHERE; # same address as $x   say "Same variable" if $y =:= $x; $x = 42; say $y; # 42  
http://rosettacode.org/wiki/AKS_test_for_primes
AKS test for primes
The AKS algorithm for testing whether a number is prime is a polynomial-time algorithm based on an elementary theorem about Pascal triangles. The theorem on which the test is based can be stated as follows:   a number   p {\displaystyle p}   is prime   if and only if   all the coefficients of the polynomial expansion of ( x − 1 ) p − ( x p − 1 ) {\displaystyle (x-1)^{p}-(x^{p}-1)} are divisible by   p {\displaystyle p} . Example Using   p = 3 {\displaystyle p=3} : (x-1)^3 - (x^3 - 1) = (x^3 - 3x^2 + 3x - 1) - (x^3 - 1) = -3x^2 + 3x And all the coefficients are divisible by 3,   so 3 is prime. Note: This task is not the AKS primality test.   It is an inefficient exponential time algorithm discovered in the late 1600s and used as an introductory lemma in the AKS derivation. Task Create a function/subroutine/method that given   p {\displaystyle p}   generates the coefficients of the expanded polynomial representation of   ( x − 1 ) p {\displaystyle (x-1)^{p}} . Use the function to show here the polynomial expansions of   ( x − 1 ) p {\displaystyle (x-1)^{p}}   for   p {\displaystyle p}   in the range   0   to at least   7,   inclusive. Use the previous function in creating another function that when given   p {\displaystyle p}   returns whether   p {\displaystyle p}   is prime using the theorem. Use your test to generate a list of all primes under   35. As a stretch goal,   generate all primes under   50   (needs integers larger than 31-bit). References Agrawal-Kayal-Saxena (AKS) primality test (Wikipedia) Fool-Proof Test for Primes - Numberphile (Video). The accuracy of this video is disputed -- at best it is an oversimplification.
#Erlang
Erlang
#! /usr/bin/escript   -import(lists, [all/2, seq/2, zip/2]).   iterate(F, X) -> fun() -> [X | iterate(F, F(X))] end.   take(0, _lazy) -> []; take(N, Lazy) -> [Value | Next] = Lazy(), [Value | take(N-1, Next)].     pascal() -> iterate(fun (Row) -> [1 | sum_adj(Row)] end, [1]).   sum_adj([_] = L) -> L; sum_adj([A, B | _] = Row) -> [A+B | sum_adj(tl(Row))].     show_binomial(Row) -> Degree = length(Row) - 1, ["(x - 1)^", integer_to_list(Degree), " =", binomial_rhs(Row, 1, Degree)].   show_x(0) -> ""; show_x(1) -> "x"; show_x(N) -> [$x, $^ | integer_to_list(N)].   binomial_rhs([], _, _) -> []; binomial_rhs([Coef | Coefs], Sgn, Exp) -> SignChar = if Sgn > 0 -> $+; true -> $- end, [$ , SignChar, $ , integer_to_list(Coef), show_x(Exp) | binomial_rhs(Coefs, -Sgn, Exp-1)].     primerow(Row, N) -> all(fun (Coef) -> (Coef =:= 1) or (Coef rem N =:= 0) end, Row).   main(_) -> [io:format("~s~n", [show_binomial(Row)]) || Row <- take(8, pascal())], io:format("~nThe primes upto 50: ~p~n", [[N || {Row, N} <- zip(tl(tl(take(51, pascal()))), seq(2, 50)), primerow(Row, N)]]).  
http://rosettacode.org/wiki/Additive_primes
Additive primes
Definitions In mathematics, additive primes are prime numbers for which the sum of their decimal digits are also primes. Task Write a program to determine (and show here) all additive primes less than 500. Optionally, show the number of additive primes. Also see   the OEIS entry:   A046704 additive primes.   the prime-numbers entry:   additive primes.   the geeks for geeks entry: additive prime number.   the prime-numbers fandom: additive primes.
#Julia
Julia
using Primes   let p = primesmask(500) println("Additive primes under 500:") pcount = 0 for i in 2:499 if p[i] && p[sum(digits(i))] pcount += 1 print(lpad(i, 4), pcount % 20 == 0 ? "\n" : "") end end println("\n\n$pcount additive primes found.") end  
http://rosettacode.org/wiki/Additive_primes
Additive primes
Definitions In mathematics, additive primes are prime numbers for which the sum of their decimal digits are also primes. Task Write a program to determine (and show here) all additive primes less than 500. Optionally, show the number of additive primes. Also see   the OEIS entry:   A046704 additive primes.   the prime-numbers entry:   additive primes.   the geeks for geeks entry: additive prime number.   the prime-numbers fandom: additive primes.
#Kotlin
Kotlin
fun isPrime(n: Int): Boolean { if (n <= 3) return n > 1 if (n % 2 == 0 || n % 3 == 0) return false var i = 5 while (i * i <= n) { if (n % i == 0 || n % (i + 2) == 0) return false i += 6 } return true }   fun digitSum(n: Int): Int { var sum = 0 var num = n while (num > 0) { sum += num % 10 num /= 10 } return sum }   fun main() { var additivePrimes = 0 for (i in 2 until 500) { if (isPrime(i) and isPrime(digitSum(i))) { additivePrimes++ print("$i ") } } println("\nFound $additivePrimes additive primes less than 500") }
http://rosettacode.org/wiki/Additive_primes
Additive primes
Definitions In mathematics, additive primes are prime numbers for which the sum of their decimal digits are also primes. Task Write a program to determine (and show here) all additive primes less than 500. Optionally, show the number of additive primes. Also see   the OEIS entry:   A046704 additive primes.   the prime-numbers entry:   additive primes.   the geeks for geeks entry: additive prime number.   the prime-numbers fandom: additive primes.
#Ksh
Ksh
#!/bin/ksh   # Prime numbers for which the sum of their decimal digits are also primes   # # Variables: # integer MAX_n=500   # # Functions: # # # Function _isprime(n) return 1 for prime, 0 for not prime # function _isprime { typeset _n ; integer _n=$1 typeset _i ; integer _i   (( _n < 2 )) && return 0 for (( _i=2 ; _i*_i<=_n ; _i++ )); do (( ! ( _n % _i ) )) && return 0 done return 1 }   # # Function _sumdigits(n) return sum of n's digits # function _sumdigits { typeset _n ; _n=$1 typeset _i _sum ; integer _i _sum=0   for ((_i=0; _i<${#_n}; _i++)); do (( _sum+=${_n:${_i}:1} )) done echo ${_sum} }   ###### # main # ######   integer i digsum for ((i=2; i<MAX_n; i++)); do _isprime ${i} && (( ! $? )) && continue   digsum=$(_sumdigits ${i}) _isprime ${digsum} ; (( $? )) && printf "%4d " ${i} done print
http://rosettacode.org/wiki/Almost_prime
Almost prime
A   k-Almost-prime   is a natural number   n {\displaystyle n}   that is the product of   k {\displaystyle k}   (possibly identical) primes. Example 1-almost-primes,   where   k = 1 {\displaystyle k=1} ,   are the prime numbers themselves. 2-almost-primes,   where   k = 2 {\displaystyle k=2} ,   are the   semiprimes. Task Write a function/method/subroutine/... that generates k-almost primes and use it to create a table here of the first ten members of k-Almost primes for   1 <= K <= 5 {\displaystyle 1<=K<=5} . Related tasks   Semiprime   Category:Prime Numbers
#jq
jq
# Recent versions of jq (version > 1.4) have the following definition of "until": def until(cond; next): def _until: if cond then . else (next|_until) end; _until;   # relatively_prime(previous) tests whether the input integer is prime # relative to the primes in the array "previous": def relatively_prime(previous): . as $in | (previous|length) as $plen # state: [found, ix] | [false, 0] | until( .[0] or .[1] >= $plen; [ ($in % previous[.[1]]) == 0, .[1] + 1] ) | .[0] | not ;   # Emit a stream in increasing order of all primes (from 2 onwards) # that are less than or equal to mx: def primes(mx):   # The helper function, next, has arity 0 for tail recursion optimization; # it expects its input to be the array of previously found primes: def next: . as $previous | ($previous | .[length-1]) as $last | if ($last >= mx) then empty else ((2 + $last) | until( relatively_prime($previous) ; . + 2)) as $nextp | if $nextp <= mx then $nextp, (( $previous + [$nextp] ) | next) else empty end end; if mx <= 1 then empty elif mx == 2 then 2 else (2, 3, ( [2,3] | next)) end ;   # Return an array of the distinct prime factors of . in increasing order def prime_factors:   # Return an array of prime factors of . given that "primes" # is an array of relevant primes: def pf(primes): if . <= 1 then [] else . as $in | if ($in | relatively_prime(primes)) then [$in] else reduce primes[] as $p ([]; if ($in % $p) != 0 then . else . + [$p] + (($in / $p) | pf(primes)) end) end | unique end;   if . <= 1 then [] else . as $in | pf( [ primes( (1+$in) | sqrt | floor) ] ) end;   # Return an array of prime factors of . repeated according to their multiplicities: def prime_factors_with_multiplicities: # Emit p according to the multiplicity of p # in the input integer assuming p > 1 def multiplicity(p): if . < p then empty elif . == p then p elif (. % p) == 0 then ((./p) | recurse( if (. % p) == 0 then (. / p) else empty end) | p) else empty end;   if . <= 1 then [] else . as $in | prime_factors as $primes | if ($in|relatively_prime($primes)) then [$in] else reduce $primes[] as $p ([]; if ($in % $p) == 0 then . + [$in|multiplicity($p)] else . end ) end end;
http://rosettacode.org/wiki/Almost_prime
Almost prime
A   k-Almost-prime   is a natural number   n {\displaystyle n}   that is the product of   k {\displaystyle k}   (possibly identical) primes. Example 1-almost-primes,   where   k = 1 {\displaystyle k=1} ,   are the prime numbers themselves. 2-almost-primes,   where   k = 2 {\displaystyle k=2} ,   are the   semiprimes. Task Write a function/method/subroutine/... that generates k-almost primes and use it to create a table here of the first ten members of k-Almost primes for   1 <= K <= 5 {\displaystyle 1<=K<=5} . Related tasks   Semiprime   Category:Prime Numbers
#Julia
Julia
using Primes   isalmostprime(n::Integer, k::Integer) = sum(values(factor(n))) == k   function almostprimes(N::Integer, k::Integer) # return first N almost-k primes P = Vector{typeof(k)}(undef,N) i = 0; n = 2 while i < N if isalmostprime(n, k) P[i += 1] = n end n += 1 end return P end   for k in 1:5 println("$k-Almost-primes: ", join(almostprimes(10, k), ", "), "...") end
http://rosettacode.org/wiki/Anagrams
Anagrams
When two or more words are composed of the same characters, but in a different order, they are called anagrams. Task[edit] Using the word list at   http://wiki.puzzlers.org/pub/wordlists/unixdict.txt, find the sets of words that share the same characters that contain the most words in them. Related tasks Word plays Ordered words Palindrome detection Semordnilap Anagrams Anagrams/Deranged anagrams Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#EchoLisp
EchoLisp
  (require 'struct) (require 'hash) (require 'sql) (require 'words) (require 'dico.fr.no-accent)     (define mots-français (words-select #:any null 999999)) (string-delimiter "")   (define (string-sort str) (list->string (list-sort string<? (string->list str))))   (define (ana-sort H words) ;; bump counter for each word (for ((w words)) #:continue (< (string-length w) 4) (let [(key (string-sort w))] (hash-set H key (1+ (hash-ref! H key 0))))))   ;; input w word ;; output : list of matching words (define (anagrams w words) (set! w (string-sort w)) (make-set (for/list (( ana words)) #:when (string=? w (string-sort ana)) ana)))   (define (task words) (define H (make-hash)) (ana-sort H words) ;; build counters key= sorted-string, value = count (hash-get-keys H ;; extract max count values (for/fold (hmax 0) ((h H) ) #:when (>= (cdr h) hmax) (cdr h)) ))  
http://rosettacode.org/wiki/Angle_difference_between_two_bearings
Angle difference between two bearings
Finding the angle between two bearings is often confusing.[1] Task Find the angle which is the result of the subtraction b2 - b1, where b1 and b2 are the bearings. Input bearings are expressed in the range   -180   to   +180   degrees. The  result  is also expressed in the range   -180   to   +180   degrees. Compute the angle for the following pairs: 20 degrees (b1) and 45 degrees (b2) -45 and 45 -85 and 90 -95 and 90 -45 and 125 -45 and 145 29.4803 and -88.6381 -78.3251 and -159.036 Optional extra Allow the input bearings to be any (finite) value. Test cases -70099.74233810938 and 29840.67437876723 -165313.6666297357 and 33693.9894517456 1174.8380510598456 and -154146.66490124757 60175.77306795546 and 42213.07192354373
#Raku
Raku
sub infix:<∠> (Real $b1, Real $b2) { (my $b = ($b2 - $b1 + 720) % 360) > 180 ?? $b - 360 !! $b; }   for 20, 45, -45, 45, -85, 90, -95, 90, -45, 125, -45, 145, 29.4803, -88.6381, -78.3251, -159.036, -70099.74233810938, 29840.67437876723, -165313.6666297357, 33693.9894517456, 1174.8380510598456, -154146.66490124757, 60175.77306795546, 42213.07192354373   -> $b1, $b2 { printf "%10.2f %10.2f = %8.2f\n", $b1, $b2, $b1 ∠ $b2 }
http://rosettacode.org/wiki/Anagrams/Deranged_anagrams
Anagrams/Deranged anagrams
Two or more words are said to be anagrams if they have the same characters, but in a different order. By analogy with derangements we define a deranged anagram as two words with the same characters, but in which the same character does not appear in the same position in both words. Task[edit] Use the word list at unixdict to find and display the longest deranged anagram. Related tasks Permutations/Derangements Best shuffle Word plays Ordered words Palindrome detection Semordnilap Anagrams Anagrams/Deranged anagrams Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#Ruby
Ruby
def deranged?(a, b) a.chars.zip(b.chars).all? {|char_a, char_b| char_a != char_b} end   def find_derangements(list) list.combination(2) {|a,b| return a,b if deranged?(a,b)} nil end   require 'open-uri' anagram = open('http://www.puzzlers.org/pub/wordlists/unixdict.txt') do |f| f.read.split.group_by {|s| s.each_char.sort} end   anagram = anagram.select{|k,list| list.size>1}.sort_by{|k,list| -k.size}   anagram.each do |k,list| if derangements = find_derangements(list) puts "Longest derangement anagram: #{derangements}" break end end
http://rosettacode.org/wiki/Anonymous_recursion
Anonymous recursion
While implementing a recursive function, it often happens that we must resort to a separate   helper function   to handle the actual recursion. This is usually the case when directly calling the current function would waste too many resources (stack space, execution time), causing unwanted side-effects,   and/or the function doesn't have the right arguments and/or return values. So we end up inventing some silly name like   foo2   or   foo_helper.   I have always found it painful to come up with a proper name, and see some disadvantages:   You have to think up a name, which then pollutes the namespace   Function is created which is called from nowhere else   The program flow in the source code is interrupted Some languages allow you to embed recursion directly in-place.   This might work via a label, a local gosub instruction, or some special keyword. Anonymous recursion can also be accomplished using the   Y combinator. Task If possible, demonstrate this by writing the recursive version of the fibonacci function   (see Fibonacci sequence)   which checks for a negative argument before doing the actual recursion.
#Perl
Perl
sub recur (&@) { my $f = shift; local *recurse = $f; $f->(@_); }   sub fibo { my $n = shift; $n < 0 and die 'Negative argument'; recur { my $m = shift; $m < 3 ? 1 : recurse($m - 1) + recurse($m - 2); } $n; }
http://rosettacode.org/wiki/Amicable_pairs
Amicable pairs
Two integers N {\displaystyle N} and M {\displaystyle M} are said to be amicable pairs if N ≠ M {\displaystyle N\neq M} and the sum of the proper divisors of N {\displaystyle N} ( s u m ( p r o p D i v s ( N ) ) {\displaystyle \mathrm {sum} (\mathrm {propDivs} (N))} ) = M {\displaystyle =M} as well as s u m ( p r o p D i v s ( M ) ) = N {\displaystyle \mathrm {sum} (\mathrm {propDivs} (M))=N} . Example 1184 and 1210 are an amicable pair, with proper divisors:   1, 2, 4, 8, 16, 32, 37, 74, 148, 296, 592   and   1, 2, 5, 10, 11, 22, 55, 110, 121, 242, 605   respectively. Task Calculate and show here the Amicable pairs below 20,000; (there are eight). Related tasks Proper divisors Abundant, deficient and perfect number classifications Aliquot sequence classifications and its amicable classification.
#PARI.2FGP
PARI/GP
for(x=1,20000,my(y=sigma(x)-x); if(y>x && x == sigma(y)-y,print(x" "y)))
http://rosettacode.org/wiki/Animate_a_pendulum
Animate a pendulum
One good way of making an animation is by simulating a physical system and illustrating the variables in that system using a dynamically changing graphical display. The classic such physical system is a simple gravity pendulum. Task Create a simple physical model of a pendulum and animate it.
#Racket
Racket
  #lang racket   (require 2htdp/image 2htdp/universe)   (define (pendulum) (define (accel θ) (- (sin θ))) (define θ (/ pi 2.5)) (define θ′ 0) (define θ′′ (accel (/ pi 2.5))) (define (x θ) (+ 200 (* 150 (sin θ)))) (define (y θ) (* 150 (cos θ))) (λ (n) (define p-image (underlay/xy (add-line (empty-scene 400 200) 200 0 (x θ) (y θ) "black") (- (x θ) 5) (- (y θ) 5) (circle 5 "solid" "blue"))) (set! θ (+ θ (* θ′ 0.04))) (set! θ′ (+ θ′ (* (accel θ) 0.04))) p-image))   (animate (pendulum))  
http://rosettacode.org/wiki/Amb
Amb
Define and give an example of the Amb operator. The Amb operator (short for "ambiguous") expresses nondeterminism. This doesn't refer to randomness (as in "nondeterministic universe") but is closely related to the term as it is used in automata theory ("non-deterministic finite automaton"). The Amb operator takes a variable number of expressions (or values if that's simpler in the language) and yields a correct one which will satisfy a constraint in some future computation, thereby avoiding failure. Problems whose solution the Amb operator naturally expresses can be approached with other tools, such as explicit nested iterations over data sets, or with pattern matching. By contrast, the Amb operator appears integrated into the language. Invocations of Amb are not wrapped in any visible loops or other search patterns; they appear to be independent. Essentially Amb(x, y, z) splits the computation into three possible futures: a future in which the value x is yielded, a future in which the value y is yielded and a future in which the value z is yielded. The future which leads to a successful subsequent computation is chosen. The other "parallel universes" somehow go away. Amb called with no arguments fails. For simplicity, one of the domain values usable with Amb may denote failure, if that is convenient. For instance, it is convenient if a Boolean false denotes failure, so that Amb(false) fails, and thus constraints can be expressed using Boolean expressions like Amb(x * y == 8) which unless x and y add to four. A pseudo-code program which satisfies this constraint might look like: let x = Amb(1, 2, 3) let y = Amb(7, 6, 4, 5) Amb(x * y = 8) print x, y The output is 2 4 because Amb(1, 2, 3) correctly chooses the future in which x has value 2, Amb(7, 6, 4, 5) chooses 4 and consequently Amb(x * y = 8) produces a success. Alternatively, failure could be represented using strictly Amb(): unless x * y = 8 do Amb() Or else Amb could take the form of two operators or functions: one for producing values and one for enforcing constraints: let x = Ambsel(1, 2, 3) let y = Ambsel(4, 5, 6) Ambassert(x * y = 8) print x, y where Ambassert behaves like Amb() if the Boolean expression is false, otherwise it allows the future computation to take place, without yielding any value. The task is to somehow implement Amb, and demonstrate it with a program which chooses one word from each of the following four sets of character strings to generate a four-word sentence: "the" "that" "a" "frog" "elephant" "thing" "walked" "treaded" "grows" "slowly" "quickly" The constraint to be satisfied is that the last character of each word (other than the last) is the same as the first character of its successor. The only successful sentence is "that thing grows slowly"; other combinations do not satisfy the constraint and thus fail. The goal of this task isn't to simply process the four lists of words with explicit, deterministic program flow such as nested iteration, to trivially demonstrate the correct output. The goal is to implement the Amb operator, or a facsimile thereof that is possible within the language limitations.
#jq
jq
def amb: .[];   def joins: (.[0][-1:]) as $left | (.[1][0:1]) as $right | if $left == $right then true else empty end;  
http://rosettacode.org/wiki/Accumulator_factory
Accumulator factory
A problem posed by Paul Graham is that of creating a function that takes a single (numeric) argument and which returns another function that is an accumulator. The returned accumulator function in turn also takes a single numeric argument, and returns the sum of all the numeric values passed in so far to that accumulator (including the initial value passed when the accumulator was created). Rules The detailed rules are at http://paulgraham.com/accgensub.html and are reproduced here for simplicity (with additions in small italic text). Before you submit an example, make sure the function Takes a number n and returns a function (lets call it g), that takes a number i, and returns n incremented by the accumulation of i from every call of function g(i). Although these exact function and parameter names need not be used Works for any numeric type-- i.e. can take both ints and floats and returns functions that can take both ints and floats. (It is not enough simply to convert all input to floats. An accumulator that has only seen integers must return integers.) (i.e., if the language doesn't allow for numeric polymorphism, you have to use overloading or something like that) Generates functions that return the sum of every number ever passed to them, not just the most recent. (This requires a piece of state to hold the accumulated value, which in turn means that pure functional languages can't be used for this task.) Returns a real function, meaning something that you can use wherever you could use a function you had defined in the ordinary way in the text of your program. (Follow your language's conventions here.) Doesn't store the accumulated value or the returned functions in a way that could cause them to be inadvertently modified by other code. (No global variables or other such things.) E.g. if after the example, you added the following code (in a made-up language) where the factory function is called foo: x = foo(1); x(5); foo(3); print x(2.3); It should print 8.3. (There is no need to print the form of the accumulator function returned by foo(3); it's not part of the task at all.) Task Create a function that implements the described rules. It need not handle any special error cases not described above. The simplest way to implement the task as described is typically to use a closure, providing the language supports them. Where it is not possible to hold exactly to the constraints above, describe the deviations.
#Ceylon
Ceylon
shared void run() { Integer|Float accumulator (variable Integer|Float n) (Integer|Float i) => switch (i) case (is Integer) (n = n.plusInteger(i)) case (is Float) (n = i + (switch(prev = n) case (is Float) prev case (is Integer) prev.float));   value x = accumulator(1); print(x(5)); print(accumulator(3)); print(x(2.3)); }
http://rosettacode.org/wiki/Accumulator_factory
Accumulator factory
A problem posed by Paul Graham is that of creating a function that takes a single (numeric) argument and which returns another function that is an accumulator. The returned accumulator function in turn also takes a single numeric argument, and returns the sum of all the numeric values passed in so far to that accumulator (including the initial value passed when the accumulator was created). Rules The detailed rules are at http://paulgraham.com/accgensub.html and are reproduced here for simplicity (with additions in small italic text). Before you submit an example, make sure the function Takes a number n and returns a function (lets call it g), that takes a number i, and returns n incremented by the accumulation of i from every call of function g(i). Although these exact function and parameter names need not be used Works for any numeric type-- i.e. can take both ints and floats and returns functions that can take both ints and floats. (It is not enough simply to convert all input to floats. An accumulator that has only seen integers must return integers.) (i.e., if the language doesn't allow for numeric polymorphism, you have to use overloading or something like that) Generates functions that return the sum of every number ever passed to them, not just the most recent. (This requires a piece of state to hold the accumulated value, which in turn means that pure functional languages can't be used for this task.) Returns a real function, meaning something that you can use wherever you could use a function you had defined in the ordinary way in the text of your program. (Follow your language's conventions here.) Doesn't store the accumulated value or the returned functions in a way that could cause them to be inadvertently modified by other code. (No global variables or other such things.) E.g. if after the example, you added the following code (in a made-up language) where the factory function is called foo: x = foo(1); x(5); foo(3); print x(2.3); It should print 8.3. (There is no need to print the form of the accumulator function returned by foo(3); it's not part of the task at all.) Task Create a function that implements the described rules. It need not handle any special error cases not described above. The simplest way to implement the task as described is typically to use a closure, providing the language supports them. Where it is not possible to hold exactly to the constraints above, describe the deviations.
#Clay
Clay
acc(n) { return (m) => { n = n + m; return n; }; }   main() { var x = acc(1.0); x(5); acc(3); println(x(2.3)); // Prints “8.300000000000001”. }
http://rosettacode.org/wiki/Ackermann_function
Ackermann function
The Ackermann function is a classic example of a recursive function, notable especially because it is not a primitive recursive function. It grows very quickly in value, as does the size of its call tree. The Ackermann function is usually defined as follows: A ( m , n ) = { n + 1 if  m = 0 A ( m − 1 , 1 ) if  m > 0  and  n = 0 A ( m − 1 , A ( m , n − 1 ) ) if  m > 0  and  n > 0. {\displaystyle A(m,n)={\begin{cases}n+1&{\mbox{if }}m=0\\A(m-1,1)&{\mbox{if }}m>0{\mbox{ and }}n=0\\A(m-1,A(m,n-1))&{\mbox{if }}m>0{\mbox{ and }}n>0.\end{cases}}} Its arguments are never negative and it always terminates. Task Write a function which returns the value of A ( m , n ) {\displaystyle A(m,n)} . Arbitrary precision is preferred (since the function grows so quickly), but not required. See also Conway chained arrow notation for the Ackermann function.
#8080_Assembly
8080 Assembly
org 100h jmp demo ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; ACK(M,N); DE=M, HL=N, return value in HL. ack: mov a,d ; M=0? ora e jnz ackm inx h ; If so, N+1. ret ackm: mov a,h ; N=0? ora l jnz ackmn lxi h,1 ; If so, N=1, dcx d ; N-=1, jmp ack ; A(M,N) - tail recursion ackmn: push d ; M>0 and N>0: store M on the stack dcx h ; N-=1 call ack ; N = ACK(M,N-1) pop d ; Restore previous M dcx d ; M-=1 jmp ack ; A(M,N) - tail recursion ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; Print table of ack(m,n) MMAX: equ 4 ; Size of table to print. Note that math is done in NMAX: equ 9 ; 16 bits. demo: lhld 6 ; Put stack pointer at top of available memory sphl lxi b,0 ; let B,C hold 8-bit M and N. acknum: xra a ; Set high bit of M and N to zero mov d,a ; DE = B (M) mov e,b mov h,a ; HL = C (N) mov l,c call ack ; HL = ack(DE,HL) call prhl ; Print the number inr c ; N += 1 mvi a,NMAX ; Time for next line? cmp c jnz acknum ; If not, print next number push b ; Otherwise, save BC mvi c,9 ; Print newline lxi d,nl call 5 pop b ; Restore BC mvi c,0 ; Set N to 0 inr b ; M += 1 mvi a,MMAX ; Time to stop? cmp b jnz acknum ; If not, print next number rst 0 ;;; Print HL as ASCII number. prhl: push h ; Save all registers push d push b lxi b,pnum ; Store pointer to num string on stack push b lxi b,-10 ; Divisor prdgt: lxi d,-1 prdgtl: inx d ; Divide by 10 through trial subtraction dad b jc prdgtl mvi a,'0'+10 add l ; L = remainder - 10 pop h ; Get pointer from stack dcx h ; Store digit mov m,a push h ; Put pointer back on stack xchg ; Put quotient in HL mov a,h ; Check if zero ora l jnz prdgt ; If not, next digit pop d ; Get pointer and put in DE mvi c,9 ; CP/M print string call 5 pop b ; Restore registers pop d pop h ret db '*****' ; Placeholder for number pnum: db 9,'$' nl: db 13,10,'$'
http://rosettacode.org/wiki/Abundant,_deficient_and_perfect_number_classifications
Abundant, deficient and perfect number classifications
These define three classifications of positive integers based on their   proper divisors. Let   P(n)   be the sum of the proper divisors of   n   where the proper divisors are all positive divisors of   n   other than   n   itself. if P(n) < n then n is classed as deficient (OEIS A005100). if P(n) == n then n is classed as perfect (OEIS A000396). if P(n) > n then n is classed as abundant (OEIS A005101). Example 6   has proper divisors of   1,   2,   and   3. 1 + 2 + 3 = 6,   so   6   is classed as a perfect number. Task Calculate how many of the integers   1   to   20,000   (inclusive) are in each of the three classes. Show the results here. Related tasks   Aliquot sequence classifications.   (The whole series from which this task is a subset.)   Proper divisors   Amicable pairs
#ALGOL_68
ALGOL 68
BEGIN # classify the numbers 1 : 20 000 as abudant, deficient or perfect # INT abundant count := 0; INT deficient count := 0; INT perfect count := 0; INT abundant example := 0; INT deficient example := 0; INT perfect example := 0; INT max number = 20 000; # construct a table of the proper divisor sums # [ 1 : max number ]INT pds; pds[ 1 ] := 0; FOR i FROM 2 TO UPB pds DO pds[ i ] := 1 OD; FOR i FROM 2 TO UPB pds DO FOR j FROM i + i BY i TO UPB pds DO pds[ j ] +:= i OD OD; # classify the numbers # FOR n TO max number DO IF INT pd sum = pds[ n ]; pd sum < n THEN # have a deficient number # deficient count +:= 1; deficient example := n ELIF pd sum = n THEN # have a perfect number # perfect count +:= 1; perfect example := n ELSE # pd sum > n # # have an abundant number # abundant count +:= 1; abundant example := n FI OD; # displays the classification, count and example # PROC show result = ( STRING classification, INT count, example )VOID: print( ( "There are " , whole( count, -8 ) , " " , classification , " numbers up to " , whole( max number, 0 ) , " e.g.: " , whole( example, 0 ) , newline ) );   # show how many of each type of number there are and an example # show result( "abundant ", abundant count, abundant example ); show result( "deficient", deficient count, deficient example ); show result( "perfect ", perfect count, perfect example ) END
http://rosettacode.org/wiki/Align_columns
Align columns
Given a text file of many lines, where fields within a line are delineated by a single 'dollar' character, write a program that aligns each column of fields by ensuring that words in each column are separated by at least one space. Further, allow for each word in a column to be either left justified, right justified, or center justified within its column. Use the following text to test your programs: Given$a$text$file$of$many$lines,$where$fields$within$a$line$ are$delineated$by$a$single$'dollar'$character,$write$a$program that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$ column$are$separated$by$at$least$one$space. Further,$allow$for$each$word$in$a$column$to$be$either$left$ justified,$right$justified,$or$center$justified$within$its$column. Note that:   The example input texts lines may, or may not, have trailing dollar characters.   All columns should share the same alignment.   Consecutive space characters produced adjacent to the end of lines are insignificant for the purposes of the task.   Output text will be viewed in a mono-spaced font on a plain text editor or basic terminal.   The minimum space between columns should be computed from the text and not hard-coded.   It is not a requirement to add separating characters between or around columns. 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
#Arturo
Arturo
text: { Given$a$text$file$of$many$lines,$where$fields$within$a$line$ are$delineated$by$a$single$'dollar'$character,$write$a$program that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$ column$are$separated$by$at$least$one$space. Further,$allow$for$each$word$in$a$column$to$be$either$left$ justified,$right$justified,$or$center$justified$within$its$column. }   output: map split.lines text => [split.by:"$"]   loop output 'line [ loop line 'word -> prints pad word 12 print "" ]
http://rosettacode.org/wiki/Active_object
Active object
In object-oriented programming an object is active when its state depends on clock. Usually an active object encapsulates a task that updates the object's state. To the outer world the object looks like a normal object with methods that can be called from outside. Implementation of such methods must have a certain synchronization mechanism with the encapsulated task in order to prevent object's state corruption. A typical instance of an active object is an animation widget. The widget state changes with the time, while as an object it has all properties of a normal widget. The task Implement an active integrator object. The object has an input and output. The input can be set using the method Input. The input is a function of time. The output can be queried using the method Output. The object integrates its input over the time and the result becomes the object's output. So if the input is K(t) and the output is S, the object state S is changed to S + (K(t1) + K(t0)) * (t1 - t0) / 2, i.e. it integrates K using the trapeze method. Initially K is constant 0 and S is 0. In order to test the object: set its input to sin (2π f t), where the frequency f=0.5Hz. The phase is irrelevant. wait 2s set the input to constant 0 wait 0.5s Verify that now the object's output is approximately 0 (the sine has the period of 2s). The accuracy of the result will depend on the OS scheduler time slicing and the accuracy of the clock.
#F.23
F#
open System open System.Threading   // current time in seconds let now() = float( DateTime.Now.Ticks / 10000L ) / 1000.0   type Integrator( intervalMs ) as x = let mutable k = fun _ -> 0.0 // function to integrate let mutable s = 0.0 // current value let mutable t0 = now() // last time s was updated let mutable running = true // still running?   do x.ScheduleNextUpdate()   member x.Input(f) = k <- f   member x.Output() = s   member x.Stop() = running <- false   member private x.Update() = let t1 = now() s <- s + (k t0 + k t1) * (t1 - t0) / 2.0 t0 <- t1 x.ScheduleNextUpdate()   member private x.ScheduleNextUpdate() = if running then async { do! Async.Sleep( intervalMs ) x.Update() } |> Async.Start   let i = new Integrator(10)   i.Input( fun t -> Math.Sin (2.0 * Math.PI * 0.5 * t) ) Thread.Sleep(2000)   i.Input( fun _ -> 0.0 ) Thread.Sleep(500)   printfn "%f" (i.Output()) i.Stop()
http://rosettacode.org/wiki/Aliquot_sequence_classifications
Aliquot sequence classifications
An aliquot sequence of a positive integer K is defined recursively as the first member being K and subsequent members being the sum of the Proper divisors of the previous term. If the terms eventually reach 0 then the series for K is said to terminate. There are several classifications for non termination: If the second term is K then all future terms are also K and so the sequence repeats from the first term with period 1 and K is called perfect. If the third term would be repeating K then the sequence repeats with period 2 and K is called amicable. If the Nth term would be repeating K for the first time, with N > 3 then the sequence repeats with period N - 1 and K is called sociable. Perfect, amicable and sociable numbers eventually repeat the original number K; there are other repetitions... Some K have a sequence that eventually forms a periodic repetition of period 1 but of a number other than K, for example 95 which forms the sequence 95, 25, 6, 6, 6, ... such K are called aspiring. K that have a sequence that eventually forms a periodic repetition of period >= 2 but of a number other than K, for example 562 which forms the sequence 562, 284, 220, 284, 220, ... such K are called cyclic. And finally: Some K form aliquot sequences that are not known to be either terminating or periodic; these K are to be called non-terminating. For the purposes of this task, K is to be classed as non-terminating if it has not been otherwise classed after generating 16 terms or if any term of the sequence is greater than 2**47 = 140,737,488,355,328. Task Create routine(s) to generate the aliquot sequence of a positive integer enough to classify it according to the classifications given above. Use it to display the classification and sequences of the numbers one to ten inclusive. Use it to show the classification and sequences of the following integers, in order: 11, 12, 28, 496, 220, 1184, 12496, 1264460, 790, 909, 562, 1064, 1488, and optionally 15355717786080. Show all output on this page. Related tasks   Abundant, deficient and perfect number classifications. (Classifications from only the first two members of the whole sequence).   Proper divisors   Amicable pairs
#Julia
Julia
  function aliquotclassifier{T<:Integer}(n::T) a = T[n] b = divisorsum(a[end]) len = 1 while len < 17 && !(b in a) && 0 < b && b < 2^47+1 push!(a, b) b = divisorsum(a[end]) len += 1 end if b in a 1 < len || return ("Perfect", a) if b == a[1] 2 < len || return ("Amicable", a) return ("Sociable", a) elseif b == a[end] return ("Aspiring", a) else return ("Cyclic", push!(a, b)) end end push!(a, b) b != 0 || return ("Terminating", a) return ("Non-terminating", a) end  
http://rosettacode.org/wiki/Add_a_variable_to_a_class_instance_at_runtime
Add a variable to a class instance at runtime
Demonstrate how to dynamically add variables to an object (a class instance) at runtime. This is useful when the methods/variables of an instance are based on a data file that isn't available until runtime. Hal Fulton gives an example of creating an OO CSV parser at An Exercise in Metaprogramming with Ruby. This is referred to as "monkeypatching" by Pythonistas and some others.
#Ruby
Ruby
class Empty end   e = Empty.new class << e attr_accessor :foo end e.foo = 1 puts e.foo # output: "1"   f = Empty.new f.foo = 1 # raises NoMethodError  
http://rosettacode.org/wiki/Add_a_variable_to_a_class_instance_at_runtime
Add a variable to a class instance at runtime
Demonstrate how to dynamically add variables to an object (a class instance) at runtime. This is useful when the methods/variables of an instance are based on a data file that isn't available until runtime. Hal Fulton gives an example of creating an OO CSV parser at An Exercise in Metaprogramming with Ruby. This is referred to as "monkeypatching" by Pythonistas and some others.
#Scala
Scala
import language.dynamics import scala.collection.mutable.HashMap   class A extends Dynamic { private val map = new HashMap[String, Any] def selectDynamic(name: String): Any = { return map(name) } def updateDynamic(name:String)(value: Any) = { map(name) = value } }
http://rosettacode.org/wiki/Add_a_variable_to_a_class_instance_at_runtime
Add a variable to a class instance at runtime
Demonstrate how to dynamically add variables to an object (a class instance) at runtime. This is useful when the methods/variables of an instance are based on a data file that isn't available until runtime. Hal Fulton gives an example of creating an OO CSV parser at An Exercise in Metaprogramming with Ruby. This is referred to as "monkeypatching" by Pythonistas and some others.
#Sidef
Sidef
class Empty{}; var e = Empty(); # create a new class instance e{:foo} = 42; # add variable 'foo' say e{:foo}; # print the value of 'foo'
http://rosettacode.org/wiki/Address_of_a_variable
Address of a variable
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation | Comparison | Matching Memory Operations Pointers & references | Addresses Task Demonstrate how to get the address of a variable and how to set the address of a variable.
#RapidQ
RapidQ
  Dim TheAddress as long Dim SecVar as byte Dim MyVar as byte MyVar = 10   'Get the address of MyVar TheAddress = varptr(MyVar)   'Set a new value on the address MEMSET(TheAddress, 102, SizeOf(byte))   'Myvar is now = 102 showmessage "MyVar = " + str$(MyVar)   '...or copy from one address to another using: MEMCPY(VarPtr(SecVar), TheAddress, SizeOf(byte))   'SecVar is now also = 102 showmessage "SecVar = " + str$(SecVar)  
http://rosettacode.org/wiki/Address_of_a_variable
Address of a variable
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation | Comparison | Matching Memory Operations Pointers & references | Addresses Task Demonstrate how to get the address of a variable and how to set the address of a variable.
#Retro
Retro
'a var &a
http://rosettacode.org/wiki/Address_of_a_variable
Address of a variable
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation | Comparison | Matching Memory Operations Pointers & references | Addresses Task Demonstrate how to get the address of a variable and how to set the address of a variable.
#REXX
REXX
zzz = storage(xxx)
http://rosettacode.org/wiki/Address_of_a_variable
Address of a variable
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation | Comparison | Matching Memory Operations Pointers & references | Addresses Task Demonstrate how to get the address of a variable and how to set the address of a variable.
#Ruby
Ruby
>foo = Object.new # => #<Object:0x10ae32000> >id = foo.object_id # => 2238812160 >"%x" % (id << 1) # => "10ae32000"  
http://rosettacode.org/wiki/AKS_test_for_primes
AKS test for primes
The AKS algorithm for testing whether a number is prime is a polynomial-time algorithm based on an elementary theorem about Pascal triangles. The theorem on which the test is based can be stated as follows:   a number   p {\displaystyle p}   is prime   if and only if   all the coefficients of the polynomial expansion of ( x − 1 ) p − ( x p − 1 ) {\displaystyle (x-1)^{p}-(x^{p}-1)} are divisible by   p {\displaystyle p} . Example Using   p = 3 {\displaystyle p=3} : (x-1)^3 - (x^3 - 1) = (x^3 - 3x^2 + 3x - 1) - (x^3 - 1) = -3x^2 + 3x And all the coefficients are divisible by 3,   so 3 is prime. Note: This task is not the AKS primality test.   It is an inefficient exponential time algorithm discovered in the late 1600s and used as an introductory lemma in the AKS derivation. Task Create a function/subroutine/method that given   p {\displaystyle p}   generates the coefficients of the expanded polynomial representation of   ( x − 1 ) p {\displaystyle (x-1)^{p}} . Use the function to show here the polynomial expansions of   ( x − 1 ) p {\displaystyle (x-1)^{p}}   for   p {\displaystyle p}   in the range   0   to at least   7,   inclusive. Use the previous function in creating another function that when given   p {\displaystyle p}   returns whether   p {\displaystyle p}   is prime using the theorem. Use your test to generate a list of all primes under   35. As a stretch goal,   generate all primes under   50   (needs integers larger than 31-bit). References Agrawal-Kayal-Saxena (AKS) primality test (Wikipedia) Fool-Proof Test for Primes - Numberphile (Video). The accuracy of this video is disputed -- at best it is an oversimplification.
#Factor
Factor
USING: combinators formatting io kernel make math math.parser math.polynomials prettyprint sequences ; IN: rosetta-code.aks-test   ! Polynomials are represented by the math.polynomials vocabulary ! as sequences with the highest exponent on the right. Hence ! { -1 1 } represents x - 1. : (x-1)^ ( n -- seq ) { -1 1 } swap p^ ;   : choose-exp ( n -- str ) { { 0 [ "" ] } { 1 [ "x" ] } [ "x^%d" sprintf ] } case ;   : choose-coeff ( n -- str ) [ dup neg? [ neg "- " ] [ "+ " ] if % # ] "" make ;   : terms ( coeffs-seq -- terms-seq ) [ [ choose-coeff ] [ choose-exp append ] bi* ] map-index ;   : (.p) ( n -- str ) (x-1)^ terms <reversed> " " join 3 tail ;   : .p ( n -- ) dup zero? [ drop "1" ] [ (.p) ] if print ;   : show-poly ( n -- ) [ "(x-1)^%d = " printf ] [ .p ] bi ;   : part1 ( -- ) 8 <iota> [ show-poly ] each ;   : (prime?) ( n -- ? ) (x-1)^ rest but-last dup first [ mod 0 = not ] curry find nip not ;   : prime? ( n -- ? ) dup 2 < [ drop f ] [ (prime?) ] if ;   : part2 ( -- ) "Primes up to 50 via AKS:" print 50 <iota> [ prime? ] filter . ;   : aks-test ( -- ) part1 nl part2 ;   MAIN: aks-test
http://rosettacode.org/wiki/Additive_primes
Additive primes
Definitions In mathematics, additive primes are prime numbers for which the sum of their decimal digits are also primes. Task Write a program to determine (and show here) all additive primes less than 500. Optionally, show the number of additive primes. Also see   the OEIS entry:   A046704 additive primes.   the prime-numbers entry:   additive primes.   the geeks for geeks entry: additive prime number.   the prime-numbers fandom: additive primes.
#langur
langur
val .isPrime = f .i == 2 or .i > 2 and not any f(.x) .i div .x, pseries 2 to .i ^/ 2   val .sumDigits = f fold f{+}, s2n toString .i   writeln "Additive primes less than 500:"   var .count = 0   for .i in [2] ~ series(3..500, 2) { if .isPrime(.i) and .isPrime(.sumDigits(.i)) { write $"\.i:3; " .count += 1 if .count div 10: writeln() } }   writeln $"\n\n\.count; additive primes found.\n"  
http://rosettacode.org/wiki/Additive_primes
Additive primes
Definitions In mathematics, additive primes are prime numbers for which the sum of their decimal digits are also primes. Task Write a program to determine (and show here) all additive primes less than 500. Optionally, show the number of additive primes. Also see   the OEIS entry:   A046704 additive primes.   the prime-numbers entry:   additive primes.   the geeks for geeks entry: additive prime number.   the prime-numbers fandom: additive primes.
#Lua
Lua
function sumdigits(n) local sum = 0 while n > 0 do sum = sum + n % 10 n = math.floor(n/10) end return sum end   primegen:generate(nil, 500) aprimes = primegen:filter(function(n) return primegen.tbd(sumdigits(n)) end) print(table.concat(aprimes, " ")) print("Count:", #aprimes)
http://rosettacode.org/wiki/Almost_prime
Almost prime
A   k-Almost-prime   is a natural number   n {\displaystyle n}   that is the product of   k {\displaystyle k}   (possibly identical) primes. Example 1-almost-primes,   where   k = 1 {\displaystyle k=1} ,   are the prime numbers themselves. 2-almost-primes,   where   k = 2 {\displaystyle k=2} ,   are the   semiprimes. Task Write a function/method/subroutine/... that generates k-almost primes and use it to create a table here of the first ten members of k-Almost primes for   1 <= K <= 5 {\displaystyle 1<=K<=5} . Related tasks   Semiprime   Category:Prime Numbers
#Kotlin
Kotlin
fun Int.k_prime(x: Int): Boolean { var n = x var f = 0 var p = 2 while (f < this && p * p <= n) { while (0 == n % p) { n /= p; f++ } p++ } return f + (if (n > 1) 1 else 0) == this }   fun Int.primes(n : Int) : List<Int> { var i = 2 var list = mutableListOf<Int>() while (list.size < n) { if (k_prime(i)) list.add(i) i++ } return list }   fun main(args: Array<String>) { for (k in 1..5) println("k = $k: " + k.primes(10)) }
http://rosettacode.org/wiki/Anagrams
Anagrams
When two or more words are composed of the same characters, but in a different order, they are called anagrams. Task[edit] Using the word list at   http://wiki.puzzlers.org/pub/wordlists/unixdict.txt, find the sets of words that share the same characters that contain the most words in them. Related tasks Word plays Ordered words Palindrome detection Semordnilap Anagrams Anagrams/Deranged anagrams Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#Eiffel
Eiffel
  class ANAGRAMS   create make   feature   make -- Set of Anagrams, containing most words. local count: INTEGER do read_wordlist across words as wo loop if wo.item.count > count then count := wo.item.count end end across words as wo loop if wo.item.count = count then across wo.item as list loop io.put_string (list.item + "%T") end io.new_line end end end   original_list: STRING = "unixdict.txt"   feature {NONE}   read_wordlist -- Preprocessed wordlist for finding Anagrams. local l_file: PLAIN_TEXT_FILE sorted: STRING empty_list: LINKED_LIST [STRING] do create l_file.make_open_read_write (original_list) l_file.read_stream (l_file.count) wordlist := l_file.last_string.split ('%N') l_file.close create words.make (wordlist.count) across wordlist as w loop create empty_list.make sorted := sort_letters (w.item) words.put (empty_list, sorted) if attached words.at (sorted) as ana then ana.extend (w.item) end end end   wordlist: LIST [STRING]   sort_letters (word: STRING): STRING --Sorted in alphabetical order. local letters: SORTED_TWO_WAY_LIST [STRING] do create letters.make create Result.make_empty across 1 |..| word.count as i loop letters.extend (word.at (i.item).out) end across letters as s loop Result.append (s.item) end end   words: HASH_TABLE [LINKED_LIST [STRING], STRING]   end  
http://rosettacode.org/wiki/Angle_difference_between_two_bearings
Angle difference between two bearings
Finding the angle between two bearings is often confusing.[1] Task Find the angle which is the result of the subtraction b2 - b1, where b1 and b2 are the bearings. Input bearings are expressed in the range   -180   to   +180   degrees. The  result  is also expressed in the range   -180   to   +180   degrees. Compute the angle for the following pairs: 20 degrees (b1) and 45 degrees (b2) -45 and 45 -85 and 90 -95 and 90 -45 and 125 -45 and 145 29.4803 and -88.6381 -78.3251 and -159.036 Optional extra Allow the input bearings to be any (finite) value. Test cases -70099.74233810938 and 29840.67437876723 -165313.6666297357 and 33693.9894517456 1174.8380510598456 and -154146.66490124757 60175.77306795546 and 42213.07192354373
#REXX
REXX
/*REXX pgm calculates difference between two angles (in degrees), normalizes the result.*/ numeric digits 25 /*use enough dec. digits for angles*/ call show 20, 45 /*display angular difference (deg).*/ call show -45, 45 /* " " " " */ call show -85, 90 /* " " " " */ call show -95, 90 /* " " " " */ call show -45, 125 /* " " " " */ call show 45, 145 /* " " " " */ call show 29.4803, -88.6361 /* " " " " */ call show -78.3251, -159.036 /* " " " " */ call show -70099.74233810938, 29840.67437876723 /* " " " " */ call show -165313.6666297357, 33693.9894517456 /* " " " " */ call show 1174.8380510598456, -154146.66490124757 /* " " " " */ call show 60175.773067955546, 42213.07192354373 /* " " " " */ exit /*stick a fork in it, we're done. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ show: parse arg a,b; d=digits(); $='º' /*obtain the 2 angles (are in degrees).*/ x=format( ( ( ((b-a) // 360) + 540) // 360) - 180, 4, d) /*compute and format. */ if pos(., x)\==0 then x=strip( strip(x, 'T', 0), "T", .) /*strip trailing chaff.*/ say center(a || $, d) '─' center(b || $, d) " ────► " x || $ return /* [↑] display the angular difference.*/
http://rosettacode.org/wiki/Anagrams/Deranged_anagrams
Anagrams/Deranged anagrams
Two or more words are said to be anagrams if they have the same characters, but in a different order. By analogy with derangements we define a deranged anagram as two words with the same characters, but in which the same character does not appear in the same position in both words. Task[edit] Use the word list at unixdict to find and display the longest deranged anagram. Related tasks Permutations/Derangements Best shuffle Word plays Ordered words Palindrome detection Semordnilap Anagrams Anagrams/Deranged anagrams Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#Run_BASIC
Run BASIC
a$ = httpGet$("http://www.puzzlers.org/pub/wordlists/unixdict.txt") dim theWord$(30000) dim ssWord$(30000)   c10$ = chr$(10) i = 1 while instr(a$,c10$,i) <> 0 j = instr(a$,c10$,i) ln = j - i again = 1 sWord$ = mid$(a$,i,j-i) n = n + 1 theWord$(n) = sWord$   while again = 1 again = 0 for kk = 1 to len(sWord$) - 1 if mid$(sWord$,kk,1) > mid$(sWord$,kk +1,1) then sWord$ = left$(sWord$,kk-1);mid$(sWord$,kk+1,1);mid$(sWord$,kk,1);mid$(sWord$,kk+2) again = 1 end if next kk wend ssWord$(n) = sWord$ i = j + 1 wend   for i = 1 to n if len(theWord$(i)) > maxLen then for j = 1 to n if ssWord$(i) = ssWord$(j) and i <> j then cnt = 0 for k = 1 to len(theWord$(i)) if mid$(theWord$(i),k,1) = mid$(theWord$(j),k,1) then cnt = cnt + 1 next k if cnt = 0 then maxLen = len(theWord$(i)) maxPtrI = i maxPtrJ = j end if end if next j end if next i   print maxLen;" ";theWord$(maxPtrI);" => ";theWord$(maxPtrJ) end
http://rosettacode.org/wiki/Anonymous_recursion
Anonymous recursion
While implementing a recursive function, it often happens that we must resort to a separate   helper function   to handle the actual recursion. This is usually the case when directly calling the current function would waste too many resources (stack space, execution time), causing unwanted side-effects,   and/or the function doesn't have the right arguments and/or return values. So we end up inventing some silly name like   foo2   or   foo_helper.   I have always found it painful to come up with a proper name, and see some disadvantages:   You have to think up a name, which then pollutes the namespace   Function is created which is called from nowhere else   The program flow in the source code is interrupted Some languages allow you to embed recursion directly in-place.   This might work via a label, a local gosub instruction, or some special keyword. Anonymous recursion can also be accomplished using the   Y combinator. Task If possible, demonstrate this by writing the recursive version of the fibonacci function   (see Fibonacci sequence)   which checks for a negative argument before doing the actual recursion.
#Phix
Phix
without js -- (no class yet) class Fib private function fib_i(integer n) return iff(n<2?n:this.fib_i(n-1)+this.fib_i(n-2)) end function public function fib(integer n) if n<0 then throw("constraint error") end if return this.fib_i(n) end function end class Fib f = new() function fib_i(integer i) return sprintf("this is not the fib_i(%d) you are looking for\n",i) end function ?f.fib(10) --?f.fib_i(10) -- illegal ?fib_i(10)
http://rosettacode.org/wiki/Amicable_pairs
Amicable pairs
Two integers N {\displaystyle N} and M {\displaystyle M} are said to be amicable pairs if N ≠ M {\displaystyle N\neq M} and the sum of the proper divisors of N {\displaystyle N} ( s u m ( p r o p D i v s ( N ) ) {\displaystyle \mathrm {sum} (\mathrm {propDivs} (N))} ) = M {\displaystyle =M} as well as s u m ( p r o p D i v s ( M ) ) = N {\displaystyle \mathrm {sum} (\mathrm {propDivs} (M))=N} . Example 1184 and 1210 are an amicable pair, with proper divisors:   1, 2, 4, 8, 16, 32, 37, 74, 148, 296, 592   and   1, 2, 5, 10, 11, 22, 55, 110, 121, 242, 605   respectively. Task Calculate and show here the Amicable pairs below 20,000; (there are eight). Related tasks Proper divisors Abundant, deficient and perfect number classifications Aliquot sequence classifications and its amicable classification.
#Pascal
Pascal
Chasing Chains of Sums of Factors of Numbers. Perfect!! 6, Perfect!! 28, Amicable! 220,284, Perfect!! 496, Amicable! 1184,1210, Amicable! 2620,2924, Amicable! 5020,5564, Amicable! 6232,6368, Perfect!! 8128, Amicable! 10744,10856, Amicable! 12285,14595, Sociable: 12496,14288,15472,14536,14264, Sociable: 14316,19116,31704,47616,83328,177792,295488,629072,589786,294896,358336,418904,366556,274924,275444,243760,376736,381028,285778,152990,122410,97946,48976,45946,22976,22744,19916,17716, Amicable! 17296,18416,
http://rosettacode.org/wiki/Animate_a_pendulum
Animate a pendulum
One good way of making an animation is by simulating a physical system and illustrating the variables in that system using a dynamically changing graphical display. The classic such physical system is a simple gravity pendulum. Task Create a simple physical model of a pendulum and animate it.
#Raku
Raku
use SDL2::Raw; use Cairo;   my $width = 1000; my $height = 400;   SDL_Init(VIDEO);   my $window = SDL_CreateWindow( 'Pendulum - Raku', SDL_WINDOWPOS_CENTERED_MASK, SDL_WINDOWPOS_CENTERED_MASK, $width, $height, RESIZABLE );   my $render = SDL_CreateRenderer($window, -1, ACCELERATED +| PRESENTVSYNC);   my $bob = Cairo::Image.create( Cairo::FORMAT_ARGB32, 32, 32 ); given Cairo::Context.new($bob) { my Cairo::Pattern::Gradient::Radial $sphere .= create(13.3, 12.8, 3.2, 12.8, 12.8, 32); $sphere.add_color_stop_rgba(0, 1, 1, .698, 1); $sphere.add_color_stop_rgba(1, .623, .669, .144, 1); .pattern($sphere); .arc(16, 16, 15, 0, 2 * pi); .fill; $sphere.destroy; }   my $bob_texture = SDL_CreateTexture( $render, %PIXELFORMAT<ARGB8888>, STATIC, 32, 32 );   SDL_UpdateTexture( $bob_texture, SDL_Rect.new(:x(0), :y(0), :w(32), :h(32)), $bob.data, $bob.stride // 32 );   SDL_SetTextureBlendMode($bob_texture, 1);   SDL_SetRenderDrawBlendMode($render, 1);   my $event = SDL_Event.new;   my $now = now; # time my $Θ = -π/3; # start angle my $ppi = 500; # scale my $g = -9.81; # accelaration of gravity my $ax = $width/2; # anchor x my $ay = 25; # anchor y my $len = $height - 75; # 'rope' length my $vel; # velocity my $dt; # delta time   main: loop { while SDL_PollEvent($event) { my $casted_event = SDL_CastEvent($event); given $casted_event { when *.type == QUIT { last main } when *.type == WINDOWEVENT { if .event == 5 { $width = .data1; $height = .data2; $ax = $width/2; $len = $height - 75; } } } }   $dt = now - $now; $now = now; $vel += $g / $len * sin($Θ) * $ppi * $dt; $Θ += $vel * $dt; my $bx = $ax + sin($Θ) * $len; my $by = $ay + cos($Θ) * $len;   SDL_SetRenderDrawColor($render, 255, 255, 255, 255); SDL_RenderDrawLine($render, |($ax, $ay, $bx, $by)».round); SDL_RenderCopy( $render, $bob_texture, Nil, SDL_Rect.new($bx - 16, $by - 16, 32, 32) ); SDL_RenderPresent($render); SDL_SetRenderDrawColor($render, 0, 0, 0, 0); SDL_RenderClear($render); }   SDL_Quit();
http://rosettacode.org/wiki/Amb
Amb
Define and give an example of the Amb operator. The Amb operator (short for "ambiguous") expresses nondeterminism. This doesn't refer to randomness (as in "nondeterministic universe") but is closely related to the term as it is used in automata theory ("non-deterministic finite automaton"). The Amb operator takes a variable number of expressions (or values if that's simpler in the language) and yields a correct one which will satisfy a constraint in some future computation, thereby avoiding failure. Problems whose solution the Amb operator naturally expresses can be approached with other tools, such as explicit nested iterations over data sets, or with pattern matching. By contrast, the Amb operator appears integrated into the language. Invocations of Amb are not wrapped in any visible loops or other search patterns; they appear to be independent. Essentially Amb(x, y, z) splits the computation into three possible futures: a future in which the value x is yielded, a future in which the value y is yielded and a future in which the value z is yielded. The future which leads to a successful subsequent computation is chosen. The other "parallel universes" somehow go away. Amb called with no arguments fails. For simplicity, one of the domain values usable with Amb may denote failure, if that is convenient. For instance, it is convenient if a Boolean false denotes failure, so that Amb(false) fails, and thus constraints can be expressed using Boolean expressions like Amb(x * y == 8) which unless x and y add to four. A pseudo-code program which satisfies this constraint might look like: let x = Amb(1, 2, 3) let y = Amb(7, 6, 4, 5) Amb(x * y = 8) print x, y The output is 2 4 because Amb(1, 2, 3) correctly chooses the future in which x has value 2, Amb(7, 6, 4, 5) chooses 4 and consequently Amb(x * y = 8) produces a success. Alternatively, failure could be represented using strictly Amb(): unless x * y = 8 do Amb() Or else Amb could take the form of two operators or functions: one for producing values and one for enforcing constraints: let x = Ambsel(1, 2, 3) let y = Ambsel(4, 5, 6) Ambassert(x * y = 8) print x, y where Ambassert behaves like Amb() if the Boolean expression is false, otherwise it allows the future computation to take place, without yielding any value. The task is to somehow implement Amb, and demonstrate it with a program which chooses one word from each of the following four sets of character strings to generate a four-word sentence: "the" "that" "a" "frog" "elephant" "thing" "walked" "treaded" "grows" "slowly" "quickly" The constraint to be satisfied is that the last character of each word (other than the last) is the same as the first character of its successor. The only successful sentence is "that thing grows slowly"; other combinations do not satisfy the constraint and thus fail. The goal of this task isn't to simply process the four lists of words with explicit, deterministic program flow such as nested iteration, to trivially demonstrate the correct output. The goal is to implement the Amb operator, or a facsimile thereof that is possible within the language limitations.
#Julia
Julia
# This is a general purpose AMB function that takes a two-argument failure function and # arbitrary number of iterable objects and returns the first solution found as an array # this function is in essence an iterative backtracking solver   function amb(failure, itrs...) n = length(itrs) if n == 1 return end states = Vector(n) values = Vector(n) # starting point, we put down the first value from the first iterable object states[1] = start(itrs[1]) values[1], states[1] = next(itrs[1], states[1]) i = 1 # main solver loop while true # test for failure if i > 1 && failure(values[i-1], values[i]) # loop for generating a new value upon failure # in fact this would be way more readable using goto, but Julia doesn't seem to have that :( while true # if we failed, we must generate a new value, but first we must check whether there is any if done(itrs[i], states[i]) # backtracking step with sanity check in case we ran out of values from the current generator if i == 1 return else i -= 1 continue end else # if there is indeed a new value, generate it values[i], states[i] = next(itrs[i], states[i]) break end end else # no failure branch # if solution is ready (i.e. all generators are used) just return it if i == n return values end # else start up the next generator i += 1 states[i] = start(itrs[i]) values[i], states[i] = next(itrs[i], states[i]) end end end   # Call our generic AMB function according to the task description and # form the solution sentence from the returned array of words amb((s1,s2) -> s1[end] != s2[1], # failure function ["the", "that", "a"], ["frog", "elephant", "thing"], ["walked", "treaded", "grows"], ["slowly", "quickly"]) |> x -> join(x, " ") |> println  
http://rosettacode.org/wiki/Accumulator_factory
Accumulator factory
A problem posed by Paul Graham is that of creating a function that takes a single (numeric) argument and which returns another function that is an accumulator. The returned accumulator function in turn also takes a single numeric argument, and returns the sum of all the numeric values passed in so far to that accumulator (including the initial value passed when the accumulator was created). Rules The detailed rules are at http://paulgraham.com/accgensub.html and are reproduced here for simplicity (with additions in small italic text). Before you submit an example, make sure the function Takes a number n and returns a function (lets call it g), that takes a number i, and returns n incremented by the accumulation of i from every call of function g(i). Although these exact function and parameter names need not be used Works for any numeric type-- i.e. can take both ints and floats and returns functions that can take both ints and floats. (It is not enough simply to convert all input to floats. An accumulator that has only seen integers must return integers.) (i.e., if the language doesn't allow for numeric polymorphism, you have to use overloading or something like that) Generates functions that return the sum of every number ever passed to them, not just the most recent. (This requires a piece of state to hold the accumulated value, which in turn means that pure functional languages can't be used for this task.) Returns a real function, meaning something that you can use wherever you could use a function you had defined in the ordinary way in the text of your program. (Follow your language's conventions here.) Doesn't store the accumulated value or the returned functions in a way that could cause them to be inadvertently modified by other code. (No global variables or other such things.) E.g. if after the example, you added the following code (in a made-up language) where the factory function is called foo: x = foo(1); x(5); foo(3); print x(2.3); It should print 8.3. (There is no need to print the form of the accumulator function returned by foo(3); it's not part of the task at all.) Task Create a function that implements the described rules. It need not handle any special error cases not described above. The simplest way to implement the task as described is typically to use a closure, providing the language supports them. Where it is not possible to hold exactly to the constraints above, describe the deviations.
#Clojure
Clojure
(defn accum [n] (let [acc (atom n)] (fn [m] (swap! acc + m))))
http://rosettacode.org/wiki/Accumulator_factory
Accumulator factory
A problem posed by Paul Graham is that of creating a function that takes a single (numeric) argument and which returns another function that is an accumulator. The returned accumulator function in turn also takes a single numeric argument, and returns the sum of all the numeric values passed in so far to that accumulator (including the initial value passed when the accumulator was created). Rules The detailed rules are at http://paulgraham.com/accgensub.html and are reproduced here for simplicity (with additions in small italic text). Before you submit an example, make sure the function Takes a number n and returns a function (lets call it g), that takes a number i, and returns n incremented by the accumulation of i from every call of function g(i). Although these exact function and parameter names need not be used Works for any numeric type-- i.e. can take both ints and floats and returns functions that can take both ints and floats. (It is not enough simply to convert all input to floats. An accumulator that has only seen integers must return integers.) (i.e., if the language doesn't allow for numeric polymorphism, you have to use overloading or something like that) Generates functions that return the sum of every number ever passed to them, not just the most recent. (This requires a piece of state to hold the accumulated value, which in turn means that pure functional languages can't be used for this task.) Returns a real function, meaning something that you can use wherever you could use a function you had defined in the ordinary way in the text of your program. (Follow your language's conventions here.) Doesn't store the accumulated value or the returned functions in a way that could cause them to be inadvertently modified by other code. (No global variables or other such things.) E.g. if after the example, you added the following code (in a made-up language) where the factory function is called foo: x = foo(1); x(5); foo(3); print x(2.3); It should print 8.3. (There is no need to print the form of the accumulator function returned by foo(3); it's not part of the task at all.) Task Create a function that implements the described rules. It need not handle any special error cases not described above. The simplest way to implement the task as described is typically to use a closure, providing the language supports them. Where it is not possible to hold exactly to the constraints above, describe the deviations.
#CoffeeScript
CoffeeScript
accumulator = (sum) -> (n) -> sum += n   f = accumulator(1) console.log f(5) console.log f(2.3)
http://rosettacode.org/wiki/Ackermann_function
Ackermann function
The Ackermann function is a classic example of a recursive function, notable especially because it is not a primitive recursive function. It grows very quickly in value, as does the size of its call tree. The Ackermann function is usually defined as follows: A ( m , n ) = { n + 1 if  m = 0 A ( m − 1 , 1 ) if  m > 0  and  n = 0 A ( m − 1 , A ( m , n − 1 ) ) if  m > 0  and  n > 0. {\displaystyle A(m,n)={\begin{cases}n+1&{\mbox{if }}m=0\\A(m-1,1)&{\mbox{if }}m>0{\mbox{ and }}n=0\\A(m-1,A(m,n-1))&{\mbox{if }}m>0{\mbox{ and }}n>0.\end{cases}}} Its arguments are never negative and it always terminates. Task Write a function which returns the value of A ( m , n ) {\displaystyle A(m,n)} . Arbitrary precision is preferred (since the function grows so quickly), but not required. See also Conway chained arrow notation for the Ackermann function.
#8086_Assembly
8086 Assembly
cpu 8086 bits 16 org 100h section .text jmp demo ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; ACK(M,N); DX=M, AX=N, return value in AX. ack: and dx,dx ; N=0? jnz .m inc ax ; If so, return N+1 ret .m: and ax,ax ; M=0? jnz .mn mov ax,1 ; If so, N=1, dec dx ; M -= 1 jmp ack ; ACK(M-1,1) - tail recursion .mn: push dx ; Keep M on the stack dec ax ; N-=1 call ack ; N = ACK(M,N-1) pop dx ; Restore M dec dx ; M -= 1 jmp ack ; ACK(M-1,ACK(M,N-1)) - tail recursion ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; Print table of ack(m,n) MMAX: equ 4 ; Size of table to print. Noe that math is done NMAX: equ 9 ; in 16 bits. demo: xor si,si ; Let SI hold M, xor di,di ; and DI hold N. acknum: mov dx,si ; Calculate ack(M,N) mov ax,di call ack call prax ; Print number inc di ; N += 1 cmp di,NMAX ; Row done? jb acknum ; If not, print next number on row xor di,di ; Otherwise, N=0, inc si ; M += 1 mov dx,nl ; Print newline call prstr cmp si,MMAX ; Done? jb acknum ; If not, start next row ret ; Otherwise, stop. ;;; Print AX as ASCII number. prax: mov bx,pnum ; Pointer to number string mov cx,10 ; Divisor .dgt: xor dx,dx ; Divide AX by ten div cx add dl,'0' ; DX holds remainder - add ASCII 0 dec bx ; Move pointer backwards mov [bx],dl ; Save digit in string and ax,ax ; Are we done yet? jnz .dgt ; If not, next digit mov dx,bx ; Tell DOS to print the string prstr: mov ah,9 int 21h ret section .data db '*****' ; Placeholder for ASCII number pnum: db 9,'$' nl: db 13,10,'$'
http://rosettacode.org/wiki/Abundant,_deficient_and_perfect_number_classifications
Abundant, deficient and perfect number classifications
These define three classifications of positive integers based on their   proper divisors. Let   P(n)   be the sum of the proper divisors of   n   where the proper divisors are all positive divisors of   n   other than   n   itself. if P(n) < n then n is classed as deficient (OEIS A005100). if P(n) == n then n is classed as perfect (OEIS A000396). if P(n) > n then n is classed as abundant (OEIS A005101). Example 6   has proper divisors of   1,   2,   and   3. 1 + 2 + 3 = 6,   so   6   is classed as a perfect number. Task Calculate how many of the integers   1   to   20,000   (inclusive) are in each of the three classes. Show the results here. Related tasks   Aliquot sequence classifications.   (The whole series from which this task is a subset.)   Proper divisors   Amicable pairs
#ALGOL_W
ALGOL W
begin % count abundant, perfect and deficient numbers up to 20 000  % integer MAX_NUMBER; MAX_NUMBER := 20000; begin integer array pds ( 1 :: MAX_NUMBER ); integer aCount, dCount, pCount, dSum;  % construct a table of proper divisor sums  % pds( 1 ) := 0; for i := 2 until MAX_NUMBER do pds( i ) := 1; for i := 2 until MAX_NUMBER do begin for j := i + i step i until MAX_NUMBER do pds( j ) := pds( j ) + i end for_i ; aCount := dCount := pCOunt := 0; for i := 1 until 20000 do begin dSum := pds( i ); if dSum > i then aCount := aCount + 1 else if dSum < i then dCount := dCOunt + 1 else % dSum = i  % pCount := pCount + 1 end for_i ; write( "Abundant numbers up to 20 000: ", aCount ); write( "Perfect numbers up to 20 000: ", pCount ); write( "Deficient numbers up to 20 000: ", dCount ) end end.
http://rosettacode.org/wiki/Align_columns
Align columns
Given a text file of many lines, where fields within a line are delineated by a single 'dollar' character, write a program that aligns each column of fields by ensuring that words in each column are separated by at least one space. Further, allow for each word in a column to be either left justified, right justified, or center justified within its column. Use the following text to test your programs: Given$a$text$file$of$many$lines,$where$fields$within$a$line$ are$delineated$by$a$single$'dollar'$character,$write$a$program that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$ column$are$separated$by$at$least$one$space. Further,$allow$for$each$word$in$a$column$to$be$either$left$ justified,$right$justified,$or$center$justified$within$its$column. Note that:   The example input texts lines may, or may not, have trailing dollar characters.   All columns should share the same alignment.   Consecutive space characters produced adjacent to the end of lines are insignificant for the purposes of the task.   Output text will be viewed in a mono-spaced font on a plain text editor or basic terminal.   The minimum space between columns should be computed from the text and not hard-coded.   It is not a requirement to add separating characters between or around columns. 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
#AutoHotkey
AutoHotkey
Alignment := "L" ; Options: L, R, C Text = ( LTrim Given$a$text$file$of$many$lines,$where$fields$within$a$line$ are$delineated$by$a$single$'dollar'$character,$write$a$program that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$ column$are$separated$by$at$least$one$space. Further,$allow$for$each$word$in$a$column$to$be$either$left$ justified,$right$justified,$or$center$justified$within$its$column. )   Loop, Parse, Text ; calculate column's width If A_LoopField in $,`n If (N > W) W := N, N := 0 Else N := 0 Else ++N Width := ++W   Loop, Parse, Text, `n ; process each line { Words := StrSplit(A_LoopField, "$") For i, Word in Words ; process each word Line .= Align(Word, Alignment, Width) Result .= RTrim(Line) . "`n" Line := "" }   Clipboard := Result ; present results MsgBox, The results are in the Clipboard   Align(Pal, How, Width) { ; function for alignment Length := StrLen(Pal) If (How = "L") Return Pal . Spc(Width - Length) Else If (How = "R") Return Spc(Width - Length) . Pal Else If (How = "C") Return Spc((Width - Length)//2) . Pal . Spc(Width - Length - (Width - Length)//2) }   Spc(Number) { ; function to concatenate space characters Loop, %Number% Ret .= A_Space Return Ret }  
http://rosettacode.org/wiki/Active_object
Active object
In object-oriented programming an object is active when its state depends on clock. Usually an active object encapsulates a task that updates the object's state. To the outer world the object looks like a normal object with methods that can be called from outside. Implementation of such methods must have a certain synchronization mechanism with the encapsulated task in order to prevent object's state corruption. A typical instance of an active object is an animation widget. The widget state changes with the time, while as an object it has all properties of a normal widget. The task Implement an active integrator object. The object has an input and output. The input can be set using the method Input. The input is a function of time. The output can be queried using the method Output. The object integrates its input over the time and the result becomes the object's output. So if the input is K(t) and the output is S, the object state S is changed to S + (K(t1) + K(t0)) * (t1 - t0) / 2, i.e. it integrates K using the trapeze method. Initially K is constant 0 and S is 0. In order to test the object: set its input to sin (2π f t), where the frequency f=0.5Hz. The phase is irrelevant. wait 2s set the input to constant 0 wait 0.5s Verify that now the object's output is approximately 0 (the sine has the period of 2s). The accuracy of the result will depend on the OS scheduler time slicing and the accuracy of the clock.
#Factor
Factor
USING: accessors alarms calendar combinators kernel locals math math.constants math.functions prettyprint system threads ; IN: rosettacode.active   TUPLE: active-object alarm function state previous-time ;   : apply-stack-effect ( quot -- quot' ) [ call( x -- x ) ] curry ; inline   : nano-to-seconds ( -- seconds ) nano-count 9 10^ / ;   : object-times ( active-object -- t1 t2 ) [ previous-time>> ] [ nano-to-seconds [ >>previous-time drop ] keep ] bi ; :: adding-function ( t1 t2 active-object -- function ) t2 t1 active-object function>> apply-stack-effect bi@ + t2 t1 - * 2 / [ + ] curry ; : integrate ( active-object -- ) [ object-times ] [ adding-function ] [ swap apply-stack-effect change-state drop ] tri ;   : <active-object> ( -- object ) active-object new 0 >>state nano-to-seconds >>previous-time [ drop 0 ] >>function dup [ integrate ] curry 1 nanoseconds every >>alarm ; : destroy ( active-object -- ) alarm>> cancel-alarm ;   : input ( object quot -- object ) >>function ; : output ( object -- val ) state>> ;   : active-test ( -- ) <active-object> [ 2 pi 0.5 * * * sin ] input 2 seconds sleep [ drop 0 ] input 0.5 seconds sleep [ output . ] [ destroy ] bi ; MAIN: active-test
http://rosettacode.org/wiki/Active_object
Active object
In object-oriented programming an object is active when its state depends on clock. Usually an active object encapsulates a task that updates the object's state. To the outer world the object looks like a normal object with methods that can be called from outside. Implementation of such methods must have a certain synchronization mechanism with the encapsulated task in order to prevent object's state corruption. A typical instance of an active object is an animation widget. The widget state changes with the time, while as an object it has all properties of a normal widget. The task Implement an active integrator object. The object has an input and output. The input can be set using the method Input. The input is a function of time. The output can be queried using the method Output. The object integrates its input over the time and the result becomes the object's output. So if the input is K(t) and the output is S, the object state S is changed to S + (K(t1) + K(t0)) * (t1 - t0) / 2, i.e. it integrates K using the trapeze method. Initially K is constant 0 and S is 0. In order to test the object: set its input to sin (2π f t), where the frequency f=0.5Hz. The phase is irrelevant. wait 2s set the input to constant 0 wait 0.5s Verify that now the object's output is approximately 0 (the sine has the period of 2s). The accuracy of the result will depend on the OS scheduler time slicing and the accuracy of the clock.
#FBSL
FBSL
#APPTYPE CONSOLE   #INCLUDE <Include\Windows.inc>   DIM Entity AS NEW Integrator(): SLEEP(2000) ' respawn and do the job   Entity.Relax(): SLEEP(500) ' get some rest   PRINT ">>> ", Entity.Yield(): DELETE Entity ' report and die   PAUSE   ' ------------- End Program Code -------------   #DEFINE SpawnMutex CreateMutex(NULL, FALSE, "mutex") #DEFINE LockMutex WaitForSingleObject(mutex, INFINITE) #DEFINE UnlockMutex ReleaseMutex(mutex) #DEFINE KillMutex CloseHandle(mutex)   CLASS Integrator   PRIVATE:   TYPE LARGE_INTEGER lowPart AS INTEGER highPart AS INTEGER END TYPE   DIM dfreq AS DOUBLE, dlast AS DOUBLE, dnow AS DOUBLE, llint AS LARGE_INTEGER DIM dret0 AS DOUBLE, dret1 AS DOUBLE, mutex AS INTEGER, sum AS DOUBLE, thread AS INTEGER   ' -------------------------------------------- SUB INITIALIZE() mutex = SpawnMutex QueryPerformanceFrequency(@llint) dfreq = LargeInt2Double(llint) QueryPerformanceCounter(@llint) dlast = LargeInt2Double(llint) / dfreq thread = FBSLTHREAD(ADDRESSOF Sampler) FBSLTHREADRESUME(thread) END SUB SUB TERMINATE() ' nothing special END SUB ' --------------------------------------------   SUB Sampler() DO LockMutex SLEEP(5) QueryPerformanceCounter(@llint) dnow = LargeInt2Double(llint) / dfreq dret0 = Task(dlast): dret1 = Task(dnow) sum = sum + (dret1 + dret0) * (dnow - dlast) / 2 dlast = dnow UnlockMutex LOOP END SUB   FUNCTION LargeInt2Double(obj AS VARIANT) AS DOUBLE STATIC ret ret = obj.highPart IF obj.highPart < 0 THEN ret = ret + (2 ^ 32) ret = ret * 2 ^ 32 ret = ret + obj.lowPart IF obj.lowPart < 0 THEN ret = ret + (2 ^ 32) RETURN ret END FUNCTION   PUBLIC:   METHOD Relax() LockMutex ADDRESSOF Task = ADDRESSOF Idle UnlockMutex END METHOD   METHOD Yield() AS DOUBLE LockMutex Yield = sum FBSLTHREADKILL(thread) UnlockMutex KillMutex END METHOD   END CLASS   FUNCTION Idle(BYVAL t AS DOUBLE) AS DOUBLE RETURN 0.0 END FUNCTION   FUNCTION Task(BYVAL t AS DOUBLE) AS DOUBLE RETURN SIN(2 * PI * 0.5 * t) END FUNCTION
http://rosettacode.org/wiki/Aliquot_sequence_classifications
Aliquot sequence classifications
An aliquot sequence of a positive integer K is defined recursively as the first member being K and subsequent members being the sum of the Proper divisors of the previous term. If the terms eventually reach 0 then the series for K is said to terminate. There are several classifications for non termination: If the second term is K then all future terms are also K and so the sequence repeats from the first term with period 1 and K is called perfect. If the third term would be repeating K then the sequence repeats with period 2 and K is called amicable. If the Nth term would be repeating K for the first time, with N > 3 then the sequence repeats with period N - 1 and K is called sociable. Perfect, amicable and sociable numbers eventually repeat the original number K; there are other repetitions... Some K have a sequence that eventually forms a periodic repetition of period 1 but of a number other than K, for example 95 which forms the sequence 95, 25, 6, 6, 6, ... such K are called aspiring. K that have a sequence that eventually forms a periodic repetition of period >= 2 but of a number other than K, for example 562 which forms the sequence 562, 284, 220, 284, 220, ... such K are called cyclic. And finally: Some K form aliquot sequences that are not known to be either terminating or periodic; these K are to be called non-terminating. For the purposes of this task, K is to be classed as non-terminating if it has not been otherwise classed after generating 16 terms or if any term of the sequence is greater than 2**47 = 140,737,488,355,328. Task Create routine(s) to generate the aliquot sequence of a positive integer enough to classify it according to the classifications given above. Use it to display the classification and sequences of the numbers one to ten inclusive. Use it to show the classification and sequences of the following integers, in order: 11, 12, 28, 496, 220, 1184, 12496, 1264460, 790, 909, 562, 1064, 1488, and optionally 15355717786080. Show all output on this page. Related tasks   Abundant, deficient and perfect number classifications. (Classifications from only the first two members of the whole sequence).   Proper divisors   Amicable pairs
#Kotlin
Kotlin
// version 1.1.3   data class Classification(val sequence: List<Long>, val aliquot: String)   const val THRESHOLD = 1L shl 47   fun sumProperDivisors(n: Long): Long { if (n < 2L) return 0L val sqrt = Math.sqrt(n.toDouble()).toLong() var sum = 1L + (2L..sqrt) .filter { n % it == 0L } .map { it + n / it } .sum() if (sqrt * sqrt == n) sum -= sqrt return sum }   fun classifySequence(k: Long): Classification { require(k > 0) var last = k val seq = mutableListOf(k) while (true) { last = sumProperDivisors(last) seq.add(last) val n = seq.size val aliquot = when { last == 0L -> "Terminating" n == 2 && last == k -> "Perfect" n == 3 && last == k -> "Amicable" n >= 4 && last == k -> "Sociable[${n - 1}]" last == seq[n - 2] -> "Aspiring" last in seq.slice(1..n - 3) -> "Cyclic[${n - 1 - seq.indexOf(last)}]" n == 16 || last > THRESHOLD -> "Non-Terminating" else -> "" } if (aliquot != "") return Classification(seq, aliquot) } }   fun main(args: Array<String>) { println("Aliqot classifications - periods for Sociable/Cyclic in square brackets:\n") for (k in 1L..10) { val (seq, aliquot) = classifySequence(k) println("${"%2d".format(k)}: ${aliquot.padEnd(15)} $seq") }   val la = longArrayOf( 11, 12, 28, 496, 220, 1184, 12496, 1264460, 790, 909, 562, 1064, 1488 ) println()   for (k in la) { val (seq, aliquot) = classifySequence(k) println("${"%7d".format(k)}: ${aliquot.padEnd(15)} $seq") }   println()   val k = 15355717786080L val (seq, aliquot) = classifySequence(k) println("$k: ${aliquot.padEnd(15)} $seq") }
http://rosettacode.org/wiki/Add_a_variable_to_a_class_instance_at_runtime
Add a variable to a class instance at runtime
Demonstrate how to dynamically add variables to an object (a class instance) at runtime. This is useful when the methods/variables of an instance are based on a data file that isn't available until runtime. Hal Fulton gives an example of creating an OO CSV parser at An Exercise in Metaprogramming with Ruby. This is referred to as "monkeypatching" by Pythonistas and some others.
#Slate
Slate
define: #Empty -> Cloneable clone. define: #e -> Empty clone. e addSlotNamed: #foo valued: 1.
http://rosettacode.org/wiki/Add_a_variable_to_a_class_instance_at_runtime
Add a variable to a class instance at runtime
Demonstrate how to dynamically add variables to an object (a class instance) at runtime. This is useful when the methods/variables of an instance are based on a data file that isn't available until runtime. Hal Fulton gives an example of creating an OO CSV parser at An Exercise in Metaprogramming with Ruby. This is referred to as "monkeypatching" by Pythonistas and some others.
#Smalltalk
Smalltalk
|addSlot p|   addSlot := [:obj :slotName | |anonCls newObj| anonCls := obj class subclass:(obj class name,'+') asSymbol instanceVariableNames:slotName classVariableNames:'' poolDictionaries:'' category:nil inEnvironment:nil. anonCls compile:('%1 ^  %1' bindWith:slotName). anonCls compile:('%1:v %1 := v' bindWith:slotName). newObj := anonCls cloneFrom:obj. obj become:newObj. ].
http://rosettacode.org/wiki/Add_a_variable_to_a_class_instance_at_runtime
Add a variable to a class instance at runtime
Demonstrate how to dynamically add variables to an object (a class instance) at runtime. This is useful when the methods/variables of an instance are based on a data file that isn't available until runtime. Hal Fulton gives an example of creating an OO CSV parser at An Exercise in Metaprogramming with Ruby. This is referred to as "monkeypatching" by Pythonistas and some others.
#Swift
Swift
import Foundation   let fooKey = UnsafeMutablePointer<UInt8>.alloc(1)   class MyClass { } let e = MyClass()   // set objc_setAssociatedObject(e, fooKey, 1, .OBJC_ASSOCIATION_RETAIN)   // get if let associatedObject = objc_getAssociatedObject(e, fooKey) { print("associated object: \(associatedObject)") } else { print("no associated object") }
http://rosettacode.org/wiki/Add_a_variable_to_a_class_instance_at_runtime
Add a variable to a class instance at runtime
Demonstrate how to dynamically add variables to an object (a class instance) at runtime. This is useful when the methods/variables of an instance are based on a data file that isn't available until runtime. Hal Fulton gives an example of creating an OO CSV parser at An Exercise in Metaprogramming with Ruby. This is referred to as "monkeypatching" by Pythonistas and some others.
#Tcl
Tcl
% package require TclOO % oo::class create summation { constructor {} { variable v 0 } method add x { variable v incr v $x } method value {{var v}} { variable $var return [set $var] } destructor { variable v puts "Ended with value $v" } } ::summation % set s [summation new] % # Do the monkey patch! % set [info object namespace $s]::time now now % # Prove it's really part of the object... % $s value time now %
http://rosettacode.org/wiki/Address_of_a_variable
Address of a variable
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation | Comparison | Matching Memory Operations Pointers & references | Addresses Task Demonstrate how to get the address of a variable and how to set the address of a variable.
#Rust
Rust
let v1 = vec![vec![1,2,3]; 10]; println!("Original address: {:p}", &v1); let mut v2; // Override rust protections on reading from uninitialized memory unsafe {v2 = mem::uninitialized();} let addr = &mut v2 as *mut _;   // ptr::write() though it takes v1 by value, v1s destructor is not run when it goes out of // scope, which is good since then we'd have a vector of free'd vectors unsafe {ptr::write(addr, v1)} println!("New address: {:p}", &v2);
http://rosettacode.org/wiki/Address_of_a_variable
Address of a variable
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation | Comparison | Matching Memory Operations Pointers & references | Addresses Task Demonstrate how to get the address of a variable and how to set the address of a variable.
#Scala
Scala
var n = 42; say Sys.refaddr(\n); # prints the address of the variable say Sys.refaddr(n); # prints the address of the object at which the variable points to
http://rosettacode.org/wiki/Address_of_a_variable
Address of a variable
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation | Comparison | Matching Memory Operations Pointers & references | Addresses Task Demonstrate how to get the address of a variable and how to set the address of a variable.
#Sidef
Sidef
var n = 42; say Sys.refaddr(\n); # prints the address of the variable say Sys.refaddr(n); # prints the address of the object at which the variable points to
http://rosettacode.org/wiki/Address_of_a_variable
Address of a variable
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation | Comparison | Matching Memory Operations Pointers & references | Addresses Task Demonstrate how to get the address of a variable and how to set the address of a variable.
#Smalltalk
Smalltalk
|p| p := Point x:10 y:20. ObjectMemory addressOf:p. ObjectMemory collectGarbage. ObjectMemory addressOf:p "may return another value"
http://rosettacode.org/wiki/AKS_test_for_primes
AKS test for primes
The AKS algorithm for testing whether a number is prime is a polynomial-time algorithm based on an elementary theorem about Pascal triangles. The theorem on which the test is based can be stated as follows:   a number   p {\displaystyle p}   is prime   if and only if   all the coefficients of the polynomial expansion of ( x − 1 ) p − ( x p − 1 ) {\displaystyle (x-1)^{p}-(x^{p}-1)} are divisible by   p {\displaystyle p} . Example Using   p = 3 {\displaystyle p=3} : (x-1)^3 - (x^3 - 1) = (x^3 - 3x^2 + 3x - 1) - (x^3 - 1) = -3x^2 + 3x And all the coefficients are divisible by 3,   so 3 is prime. Note: This task is not the AKS primality test.   It is an inefficient exponential time algorithm discovered in the late 1600s and used as an introductory lemma in the AKS derivation. Task Create a function/subroutine/method that given   p {\displaystyle p}   generates the coefficients of the expanded polynomial representation of   ( x − 1 ) p {\displaystyle (x-1)^{p}} . Use the function to show here the polynomial expansions of   ( x − 1 ) p {\displaystyle (x-1)^{p}}   for   p {\displaystyle p}   in the range   0   to at least   7,   inclusive. Use the previous function in creating another function that when given   p {\displaystyle p}   returns whether   p {\displaystyle p}   is prime using the theorem. Use your test to generate a list of all primes under   35. As a stretch goal,   generate all primes under   50   (needs integers larger than 31-bit). References Agrawal-Kayal-Saxena (AKS) primality test (Wikipedia) Fool-Proof Test for Primes - Numberphile (Video). The accuracy of this video is disputed -- at best it is an oversimplification.
#Forth
Forth
: coeffs ( u -- nu ... n0 ) \ coefficients of (x-1)^u 1 swap 1+ dup 1 ?do over over i - i */ negate swap loop drop ;   : prime? ( u -- f ) dup 2 < if drop false exit then dup >r coeffs 1+ \ if not prime, this loop consumes at most half the coefficients, otherwise all begin dup 1 <> while r@ mod 0= while repeat then rdrop dup 1 = >r begin 1 = until r> ;   : .monom ( u1 u2 -- ) dup 0> if [char] + emit then 0 .r ?dup if ." x^" . else space then ; : .poly ( u -- ) dup >r coeffs 0 r> 1+ 0 ?do tuck swap .monom 1+ loop ;   : main 11 0 ?do i . ." : " i .poly cr loop cr 50 1 ?do i prime? if i . then loop cr ;
http://rosettacode.org/wiki/Additive_primes
Additive primes
Definitions In mathematics, additive primes are prime numbers for which the sum of their decimal digits are also primes. Task Write a program to determine (and show here) all additive primes less than 500. Optionally, show the number of additive primes. Also see   the OEIS entry:   A046704 additive primes.   the prime-numbers entry:   additive primes.   the geeks for geeks entry: additive prime number.   the prime-numbers fandom: additive primes.
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
ClearAll[AdditivePrimeQ] AdditivePrimeQ[n_Integer] := PrimeQ[n] \[And] PrimeQ[Total[IntegerDigits[n]]] Select[Range[500], AdditivePrimeQ]
http://rosettacode.org/wiki/Additive_primes
Additive primes
Definitions In mathematics, additive primes are prime numbers for which the sum of their decimal digits are also primes. Task Write a program to determine (and show here) all additive primes less than 500. Optionally, show the number of additive primes. Also see   the OEIS entry:   A046704 additive primes.   the prime-numbers entry:   additive primes.   the geeks for geeks entry: additive prime number.   the prime-numbers fandom: additive primes.
#Modula-2
Modula-2
MODULE AdditivePrimes; FROM InOut IMPORT WriteString, WriteCard, WriteLn;   CONST Max = 500;   VAR N: CARDINAL; Count: CARDINAL; Prime: ARRAY [2..Max] OF BOOLEAN;   PROCEDURE DigitSum(n: CARDINAL): CARDINAL; BEGIN IF n < 10 THEN RETURN n; ELSE RETURN (n MOD 10) + DigitSum(n DIV 10); END; END DigitSum;   PROCEDURE Sieve; VAR i, j, max2: CARDINAL; BEGIN FOR i := 2 TO Max DO Prime[i] := TRUE; END;   FOR i := 2 TO Max DIV 2 DO IF Prime[i] THEN; j := i*2; WHILE j <= Max DO Prime[j] := FALSE; j := j + i; END; END; END; END Sieve;   BEGIN Count := 0; Sieve(); FOR N := 2 TO Max DO IF Prime[N] AND Prime[DigitSum(N)] THEN WriteCard(N, 4); Count := Count + 1; IF Count MOD 10 = 0 THEN WriteLn(); END; END; END; WriteLn(); WriteString('There are '); WriteCard(Count,0); WriteString(' additive primes less than '); WriteCard(Max,0); WriteString('.'); WriteLn(); END AdditivePrimes.
http://rosettacode.org/wiki/Almost_prime
Almost prime
A   k-Almost-prime   is a natural number   n {\displaystyle n}   that is the product of   k {\displaystyle k}   (possibly identical) primes. Example 1-almost-primes,   where   k = 1 {\displaystyle k=1} ,   are the prime numbers themselves. 2-almost-primes,   where   k = 2 {\displaystyle k=2} ,   are the   semiprimes. Task Write a function/method/subroutine/... that generates k-almost primes and use it to create a table here of the first ten members of k-Almost primes for   1 <= K <= 5 {\displaystyle 1<=K<=5} . Related tasks   Semiprime   Category:Prime Numbers
#Liberty_BASIC
Liberty BASIC
  ' Almost prime for k = 1 to 5 print "k = "; k; ":"; i = 2 c = 0 while c < 10 if kPrime(i, k) then print " "; using("###", i); c = c + 1 end if i = i + 1 wend print next k end   function kPrime(n, k) f = 0 for i = 2 to n while n mod i = 0 if f = k then kPrime = 0: exit function f = f + 1 n = int(n / i) wend next i kPrime = abs(f = k) end function  
http://rosettacode.org/wiki/Anagrams
Anagrams
When two or more words are composed of the same characters, but in a different order, they are called anagrams. Task[edit] Using the word list at   http://wiki.puzzlers.org/pub/wordlists/unixdict.txt, find the sets of words that share the same characters that contain the most words in them. Related tasks Word plays Ordered words Palindrome detection Semordnilap Anagrams Anagrams/Deranged anagrams Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#Ela
Ela
open monad io list string   groupon f x y = f x == f y   lines = split "\n" << replace "\n\n" "\n" << replace "\r" "\n"   main = do fh <- readFile "c:\\test\\unixdict.txt" OpenMode f <- readLines fh closeFile fh let words = lines f let wix = groupBy (groupon fst) << sort $ zip (map sort words) words let mxl = maximum $ map length wix mapM_ (putLn << map snd) << filter ((==mxl) << length) $ wix
http://rosettacode.org/wiki/Angle_difference_between_two_bearings
Angle difference between two bearings
Finding the angle between two bearings is often confusing.[1] Task Find the angle which is the result of the subtraction b2 - b1, where b1 and b2 are the bearings. Input bearings are expressed in the range   -180   to   +180   degrees. The  result  is also expressed in the range   -180   to   +180   degrees. Compute the angle for the following pairs: 20 degrees (b1) and 45 degrees (b2) -45 and 45 -85 and 90 -95 and 90 -45 and 125 -45 and 145 29.4803 and -88.6381 -78.3251 and -159.036 Optional extra Allow the input bearings to be any (finite) value. Test cases -70099.74233810938 and 29840.67437876723 -165313.6666297357 and 33693.9894517456 1174.8380510598456 and -154146.66490124757 60175.77306795546 and 42213.07192354373
#Ring
Ring
  # Project : Angle difference between two bearings   decimals(4) see "Input in -180 to +180 range:" + nl see getDifference(20.0, 45.0) + nl see getDifference(-45.0, 45.0) + nl see getDifference(-85.0, 90.0) + nl see getDifference(-95.0, 90.0) + nl see getDifference(-45.0, 125.0) + nl see getDifference(-45.0, 145.0) + nl see getDifference(-45.0, 125.0) + nl see getDifference(-45.0, 145.0) + nl see getDifference(29.4803, -88.6381) + nl see getDifference(-78.3251, -159.036) + nl   func getDifference(b1, b2) r = (b2 - b1) % 360.0 if r >= 180.0 r = r - 360.0 end return r  
http://rosettacode.org/wiki/Angle_difference_between_two_bearings
Angle difference between two bearings
Finding the angle between two bearings is often confusing.[1] Task Find the angle which is the result of the subtraction b2 - b1, where b1 and b2 are the bearings. Input bearings are expressed in the range   -180   to   +180   degrees. The  result  is also expressed in the range   -180   to   +180   degrees. Compute the angle for the following pairs: 20 degrees (b1) and 45 degrees (b2) -45 and 45 -85 and 90 -95 and 90 -45 and 125 -45 and 145 29.4803 and -88.6381 -78.3251 and -159.036 Optional extra Allow the input bearings to be any (finite) value. Test cases -70099.74233810938 and 29840.67437876723 -165313.6666297357 and 33693.9894517456 1174.8380510598456 and -154146.66490124757 60175.77306795546 and 42213.07192354373
#Ruby
Ruby
def getDifference(b1, b2) r = (b2 - b1) % 360.0 # Ruby modulus has same sign as divisor, which is positive here, # so no need to consider negative case if r >= 180.0 r -= 360.0 end return r end   if __FILE__ == $PROGRAM_NAME puts "Input in -180 to +180 range" puts getDifference(20.0, 45.0) puts getDifference(-45.0, 45.0) puts getDifference(-85.0, 90.0) puts getDifference(-95.0, 90.0) puts getDifference(-45.0, 125.0) puts getDifference(-45.0, 145.0) puts getDifference(-45.0, 125.0) puts getDifference(-45.0, 145.0) puts getDifference(29.4803, -88.6381) puts getDifference(-78.3251, -159.036)   puts "Input in wider range" puts getDifference(-70099.74233810938, 29840.67437876723) puts getDifference(-165313.6666297357, 33693.9894517456) puts getDifference(1174.8380510598456, -154146.66490124757) puts getDifference(60175.77306795546, 42213.07192354373) end
http://rosettacode.org/wiki/Anagrams/Deranged_anagrams
Anagrams/Deranged anagrams
Two or more words are said to be anagrams if they have the same characters, but in a different order. By analogy with derangements we define a deranged anagram as two words with the same characters, but in which the same character does not appear in the same position in both words. Task[edit] Use the word list at unixdict to find and display the longest deranged anagram. Related tasks Permutations/Derangements Best shuffle Word plays Ordered words Palindrome detection Semordnilap Anagrams Anagrams/Deranged anagrams Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#Rust
Rust
//! Deranged anagrams use std::cmp::Ordering; use std::collections::HashMap; use std::fs::File; use std::io; use std::io::BufReader; use std::io::BufRead; use std::usize::MAX;   /// Get words from unix dictionary file pub fn get_words() -> Result<Vec<String>, io::Error> { let mut words = vec!(); // open file let f = File::open("data/unixdict.txt")?; // read line by line let reader = BufReader::new(&f); for line in reader.lines() { words.push(line?) } Ok(words) }   /// Get the longest deranged anagram in the given list of word if any pub fn longest_deranged(v: &mut Vec<String>) -> Option<(String,String)>{ // sort by length descending then by alphabetical order v.sort_by(|s1, s2| { let mut c = s2.len().cmp(&s1.len()); if c == Ordering::Equal { c = s1.cmp(s2); } c }); // keep all strings keyed by sorted characters (since anagrams have the same list of sorted characters) let mut signatures : HashMap<Vec<char>, Vec<&String>> = HashMap::new(); // save on memory by only keeping in the map strings of the current processed length let mut previous_length = MAX; for s in v { // length change, clear the map if s.len()<previous_length { signatures.clear(); previous_length = s.len(); } // generate key as sorted characters let mut sorted_chars = s.chars().collect::<Vec<char>>(); sorted_chars.sort(); let anagrams = signatures.entry(sorted_chars).or_insert(vec!()); // find if any anagram (string with the same sorted character vector) is deranged if let Some(a) = anagrams.iter().filter(|anagram| is_deranged(anagram, s)).next(){ return Some(((*a).clone(), s.clone())); } anagrams.push(s); } None }   /// check if two strings do NOT have the same character in the same position pub fn is_deranged(s1: &String, s2: &String) -> bool { // we zip the character iterators and check we find no position with the same two characters s1.chars().zip(s2.chars()).filter(|(a,b)| a == b).next().is_none() }   /// an example main method printing the results fn main() { let r = get_words(); match r { Ok(mut v) => { let od = longest_deranged(&mut v); match od { None => println!("No deranged anagrams found!"), Some((s1,s2)) => println!("{} {}",s1,s2), } }, Err(e) => panic!("Could not read words: {}",e) } }
http://rosettacode.org/wiki/Anonymous_recursion
Anonymous recursion
While implementing a recursive function, it often happens that we must resort to a separate   helper function   to handle the actual recursion. This is usually the case when directly calling the current function would waste too many resources (stack space, execution time), causing unwanted side-effects,   and/or the function doesn't have the right arguments and/or return values. So we end up inventing some silly name like   foo2   or   foo_helper.   I have always found it painful to come up with a proper name, and see some disadvantages:   You have to think up a name, which then pollutes the namespace   Function is created which is called from nowhere else   The program flow in the source code is interrupted Some languages allow you to embed recursion directly in-place.   This might work via a label, a local gosub instruction, or some special keyword. Anonymous recursion can also be accomplished using the   Y combinator. Task If possible, demonstrate this by writing the recursive version of the fibonacci function   (see Fibonacci sequence)   which checks for a negative argument before doing the actual recursion.
#PHP
PHP
<?php function fib($n) { if ($n < 0) throw new Exception('Negative numbers not allowed'); $f = function($n) { // This function must be called using call_user_func() only if ($n < 2) return 1; else { $g = debug_backtrace()[1]['args'][0]; return call_user_func($g, $n-1) + call_user_func($g, $n-2); } }; return call_user_func($f, $n); } echo fib(8), "\n"; ?>
http://rosettacode.org/wiki/Amicable_pairs
Amicable pairs
Two integers N {\displaystyle N} and M {\displaystyle M} are said to be amicable pairs if N ≠ M {\displaystyle N\neq M} and the sum of the proper divisors of N {\displaystyle N} ( s u m ( p r o p D i v s ( N ) ) {\displaystyle \mathrm {sum} (\mathrm {propDivs} (N))} ) = M {\displaystyle =M} as well as s u m ( p r o p D i v s ( M ) ) = N {\displaystyle \mathrm {sum} (\mathrm {propDivs} (M))=N} . Example 1184 and 1210 are an amicable pair, with proper divisors:   1, 2, 4, 8, 16, 32, 37, 74, 148, 296, 592   and   1, 2, 5, 10, 11, 22, 55, 110, 121, 242, 605   respectively. Task Calculate and show here the Amicable pairs below 20,000; (there are eight). Related tasks Proper divisors Abundant, deficient and perfect number classifications Aliquot sequence classifications and its amicable classification.
#Perl
Perl
use ntheory qw/divisor_sum/; for my $x (1..20000) { my $y = divisor_sum($x)-$x; say "$x $y" if $y > $x && $x == divisor_sum($y)-$y; }
http://rosettacode.org/wiki/Animate_a_pendulum
Animate a pendulum
One good way of making an animation is by simulating a physical system and illustrating the variables in that system using a dynamically changing graphical display. The classic such physical system is a simple gravity pendulum. Task Create a simple physical model of a pendulum and animate it.
#REXX
REXX
/*REXX program displays the (x, y) coördinates (at the end of a swinging pendulum). */ parse arg cycles Plength theta . /*obtain optional argument from the CL.*/ if cycles=='' | cycles=="," then cycles= 60 /*Not specified? Then use the default.*/ if pLength=='' | pLength=="," then pLength= 10 /* " " " " " " */ if theta=='' | theta=="," then theta= 30 /* " " " " " " */ theta= theta / 180 * pi() /* 'cause that's the way Ada did it. */ was= time('R') /*obtain the current elapsed time (was)*/ g= -9.81 /*gravitation constant (for earth). */ speed= 0 /*velocity of the pendulum, now resting*/ do cycles; call delay 1/20 /*swing the pendulum a number of times.*/ now= time('E') /*obtain the current time (in seconds).*/ duration= now - was /*calculate duration since last cycle. */ acceleration= g / pLength * sin(theta) /*compute the pendulum acceleration. */ x= sin(theta) * pLength /*calculate X coördinate of pendulum.*/ y= cos(theta) * pLength /* " Y " " */ speed= speed + acceleration * duration /*calculate " speed " " */ theta= theta + speed * duration /* " " angle " " */ was= now /*save the elapsed time as it was then.*/ say right('X: ',20) fmt(x) right("Y: ", 10) fmt(y) end /*cycles*/ exit 0 /*stick a fork in it, we're all done. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ fmt: procedure; parse arg z; return left('', z>=0)format(z, , digits() - 1) /*align#*/ pi: pi= 3.1415926535897932384626433832795028841971693993751058209749445923078; return pi r2r: return arg(1) // (pi() * 2) /*normalize radians ──► a unit circle. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ cos: procedure; parse arg x; x=r2r(x); numeric fuzz min(6,digits()-3); z=1; _=1; x=x*x p=z; do k=2 by 2; _=-_*x/(k*(k-1)); z=z+_; if z=p then leave; p=z; end; return z /*──────────────────────────────────────────────────────────────────────────────────────*/ sin: procedure; parse arg x; x=r2r(x); _=x; numeric fuzz min(5, max(1,digits()-3)); q=x*x z=x; do k=2 by 2 until p=z; p= z; _= -_*q/(k*k+k); z= z+_; end; return z
http://rosettacode.org/wiki/Amb
Amb
Define and give an example of the Amb operator. The Amb operator (short for "ambiguous") expresses nondeterminism. This doesn't refer to randomness (as in "nondeterministic universe") but is closely related to the term as it is used in automata theory ("non-deterministic finite automaton"). The Amb operator takes a variable number of expressions (or values if that's simpler in the language) and yields a correct one which will satisfy a constraint in some future computation, thereby avoiding failure. Problems whose solution the Amb operator naturally expresses can be approached with other tools, such as explicit nested iterations over data sets, or with pattern matching. By contrast, the Amb operator appears integrated into the language. Invocations of Amb are not wrapped in any visible loops or other search patterns; they appear to be independent. Essentially Amb(x, y, z) splits the computation into three possible futures: a future in which the value x is yielded, a future in which the value y is yielded and a future in which the value z is yielded. The future which leads to a successful subsequent computation is chosen. The other "parallel universes" somehow go away. Amb called with no arguments fails. For simplicity, one of the domain values usable with Amb may denote failure, if that is convenient. For instance, it is convenient if a Boolean false denotes failure, so that Amb(false) fails, and thus constraints can be expressed using Boolean expressions like Amb(x * y == 8) which unless x and y add to four. A pseudo-code program which satisfies this constraint might look like: let x = Amb(1, 2, 3) let y = Amb(7, 6, 4, 5) Amb(x * y = 8) print x, y The output is 2 4 because Amb(1, 2, 3) correctly chooses the future in which x has value 2, Amb(7, 6, 4, 5) chooses 4 and consequently Amb(x * y = 8) produces a success. Alternatively, failure could be represented using strictly Amb(): unless x * y = 8 do Amb() Or else Amb could take the form of two operators or functions: one for producing values and one for enforcing constraints: let x = Ambsel(1, 2, 3) let y = Ambsel(4, 5, 6) Ambassert(x * y = 8) print x, y where Ambassert behaves like Amb() if the Boolean expression is false, otherwise it allows the future computation to take place, without yielding any value. The task is to somehow implement Amb, and demonstrate it with a program which chooses one word from each of the following four sets of character strings to generate a four-word sentence: "the" "that" "a" "frog" "elephant" "thing" "walked" "treaded" "grows" "slowly" "quickly" The constraint to be satisfied is that the last character of each word (other than the last) is the same as the first character of its successor. The only successful sentence is "that thing grows slowly"; other combinations do not satisfy the constraint and thus fail. The goal of this task isn't to simply process the four lists of words with explicit, deterministic program flow such as nested iteration, to trivially demonstrate the correct output. The goal is to implement the Amb operator, or a facsimile thereof that is possible within the language limitations.
#Kotlin
Kotlin
// version 1.2.41 import kotlin.coroutines.experimental.* import kotlin.coroutines.experimental.intrinsics.*   fun main(args: Array<String>) = amb { val a = amb("the", "that", "a") val b = amb("frog", "elephant", "thing") val c = amb("walked", "treaded", "grows") val d = amb("slowly", "quickly")   if (a[a.lastIndex] != b[0]) amb() if (b[b.lastIndex] != c[0]) amb() if (c[c.lastIndex] != d[0]) amb()   println(listOf(a, b, c, d))     val x = amb(1, 2, 3) val y = amb(7, 6, 4, 5) if (x * y != 8) amb() println(listOf(x, y)) }     class AmbException(): Exception("Refusing to execute") data class AmbPair<T>(val cont: Continuation<T>, val valuesLeft: MutableList<T>)   @RestrictsSuspension class AmbEnvironment { val ambList = mutableListOf<AmbPair<*>>()   suspend fun <T> amb(value: T, vararg rest: T): T = suspendCoroutineOrReturn { cont -> if (rest.size > 0) { ambList.add(AmbPair(clone(cont), mutableListOf(*rest))) }   value }   suspend fun amb(): Nothing = suspendCoroutine<Nothing> { } }   @Suppress("UNCHECKED_CAST") fun <R> amb(block: suspend AmbEnvironment.() -> R): R { var result: R? = null var toThrow: Throwable? = null   val dist = AmbEnvironment() block.startCoroutine(receiver = dist, completion = object : Continuation<R> { override val context: CoroutineContext get() = EmptyCoroutineContext override fun resume(value: R) { result = value } override fun resumeWithException(exception: Throwable) { toThrow = exception } })   while (result == null && toThrow == null && !dist.ambList.isEmpty()) { val last = dist.ambList.run { this[lastIndex] }   if (last.valuesLeft.size == 1) { dist.ambList.removeAt(dist.ambList.lastIndex) last.apply { (cont as Continuation<Any?>).resume(valuesLeft[0]) } } else { val value = last.valuesLeft.removeAt(last.valuesLeft.lastIndex) (clone(last.cont) as Continuation<Any?>).resume(value) } }   if (toThrow != null) { throw toThrow!! } else if (result != null) { return result!! } else { throw AmbException() } }   val UNSAFE = Class.forName("sun.misc.Unsafe") .getDeclaredField("theUnsafe") .apply { isAccessible = true } .get(null) as sun.misc.Unsafe   @Suppress("UNCHECKED_CAST") fun <T: Any> clone(obj: T): T { val clazz = obj::class.java val copy = UNSAFE.allocateInstance(clazz) as T copyDeclaredFields(obj, copy, clazz) return copy }   tailrec fun <T> copyDeclaredFields(obj: T, copy: T, clazz: Class<out T>) { for (field in clazz.declaredFields) { field.isAccessible = true val v = field.get(obj) field.set(copy, if (v === obj) copy else v) } val superclass = clazz.superclass if (superclass != null) copyDeclaredFields(obj, copy, superclass) }
http://rosettacode.org/wiki/Accumulator_factory
Accumulator factory
A problem posed by Paul Graham is that of creating a function that takes a single (numeric) argument and which returns another function that is an accumulator. The returned accumulator function in turn also takes a single numeric argument, and returns the sum of all the numeric values passed in so far to that accumulator (including the initial value passed when the accumulator was created). Rules The detailed rules are at http://paulgraham.com/accgensub.html and are reproduced here for simplicity (with additions in small italic text). Before you submit an example, make sure the function Takes a number n and returns a function (lets call it g), that takes a number i, and returns n incremented by the accumulation of i from every call of function g(i). Although these exact function and parameter names need not be used Works for any numeric type-- i.e. can take both ints and floats and returns functions that can take both ints and floats. (It is not enough simply to convert all input to floats. An accumulator that has only seen integers must return integers.) (i.e., if the language doesn't allow for numeric polymorphism, you have to use overloading or something like that) Generates functions that return the sum of every number ever passed to them, not just the most recent. (This requires a piece of state to hold the accumulated value, which in turn means that pure functional languages can't be used for this task.) Returns a real function, meaning something that you can use wherever you could use a function you had defined in the ordinary way in the text of your program. (Follow your language's conventions here.) Doesn't store the accumulated value or the returned functions in a way that could cause them to be inadvertently modified by other code. (No global variables or other such things.) E.g. if after the example, you added the following code (in a made-up language) where the factory function is called foo: x = foo(1); x(5); foo(3); print x(2.3); It should print 8.3. (There is no need to print the form of the accumulator function returned by foo(3); it's not part of the task at all.) Task Create a function that implements the described rules. It need not handle any special error cases not described above. The simplest way to implement the task as described is typically to use a closure, providing the language supports them. Where it is not possible to hold exactly to the constraints above, describe the deviations.
#Common_Lisp
Common Lisp
(defun accumulator (sum) (lambda (n) (incf sum n)))
http://rosettacode.org/wiki/Accumulator_factory
Accumulator factory
A problem posed by Paul Graham is that of creating a function that takes a single (numeric) argument and which returns another function that is an accumulator. The returned accumulator function in turn also takes a single numeric argument, and returns the sum of all the numeric values passed in so far to that accumulator (including the initial value passed when the accumulator was created). Rules The detailed rules are at http://paulgraham.com/accgensub.html and are reproduced here for simplicity (with additions in small italic text). Before you submit an example, make sure the function Takes a number n and returns a function (lets call it g), that takes a number i, and returns n incremented by the accumulation of i from every call of function g(i). Although these exact function and parameter names need not be used Works for any numeric type-- i.e. can take both ints and floats and returns functions that can take both ints and floats. (It is not enough simply to convert all input to floats. An accumulator that has only seen integers must return integers.) (i.e., if the language doesn't allow for numeric polymorphism, you have to use overloading or something like that) Generates functions that return the sum of every number ever passed to them, not just the most recent. (This requires a piece of state to hold the accumulated value, which in turn means that pure functional languages can't be used for this task.) Returns a real function, meaning something that you can use wherever you could use a function you had defined in the ordinary way in the text of your program. (Follow your language's conventions here.) Doesn't store the accumulated value or the returned functions in a way that could cause them to be inadvertently modified by other code. (No global variables or other such things.) E.g. if after the example, you added the following code (in a made-up language) where the factory function is called foo: x = foo(1); x(5); foo(3); print x(2.3); It should print 8.3. (There is no need to print the form of the accumulator function returned by foo(3); it's not part of the task at all.) Task Create a function that implements the described rules. It need not handle any special error cases not described above. The simplest way to implement the task as described is typically to use a closure, providing the language supports them. Where it is not possible to hold exactly to the constraints above, describe the deviations.
#Crystal
Crystal
  # Make types a bit easier with an alias alias Num = Int32 | Int64 | Float32 | Float64   def accumulator(sum : Num) # This proc is very similar to a Ruby lambda ->(n : Num){ sum += n } end   x = accumulator(5) puts x.call(5) #=> 10 puts x.call(10) #=> 20 puts x.call(2.4) #=> 22.4  
http://rosettacode.org/wiki/Ackermann_function
Ackermann function
The Ackermann function is a classic example of a recursive function, notable especially because it is not a primitive recursive function. It grows very quickly in value, as does the size of its call tree. The Ackermann function is usually defined as follows: A ( m , n ) = { n + 1 if  m = 0 A ( m − 1 , 1 ) if  m > 0  and  n = 0 A ( m − 1 , A ( m , n − 1 ) ) if  m > 0  and  n > 0. {\displaystyle A(m,n)={\begin{cases}n+1&{\mbox{if }}m=0\\A(m-1,1)&{\mbox{if }}m>0{\mbox{ and }}n=0\\A(m-1,A(m,n-1))&{\mbox{if }}m>0{\mbox{ and }}n>0.\end{cases}}} Its arguments are never negative and it always terminates. Task Write a function which returns the value of A ( m , n ) {\displaystyle A(m,n)} . Arbitrary precision is preferred (since the function grows so quickly), but not required. See also Conway chained arrow notation for the Ackermann function.
#8th
8th
  \ Ackermann function, illustrating use of "memoization".   \ Memoization is a technique whereby intermediate computed values are stored \ away against later need. It is particularly valuable when calculating those \ values is time or resource intensive, as with the Ackermann function.   \ make the stack much bigger so this can complete! 100000 stack-size   \ This is where memoized values are stored: {} var, dict   \ Simple accessor words : dict! \ "key" val -- dict @ -rot m:! drop ;   : dict@ \ "key" -- val dict @ swap m:@ nip ;   defer: ack1   \ We just jam the string representation of the two numbers together for a key: : makeKey \ m n -- m n key 2dup >s swap >s s:+ ;   : ack2 \ m n -- A makeKey dup dict@ null? if \ can't find key in dict \ m n key null drop \ m n key -rot \ key m n ack1 \ key A tuck \ A key A dict! \ A else \ found value \ m n key value >r drop 2drop r> then ;   : ack \ m n -- A over not if nip n:1+ else dup not if drop n:1- 1 ack2 else over swap n:1- ack2 swap n:1- swap ack2 then then ;   ' ack is ack1   : ackOf \ m n -- 2dup "Ack(" . swap . ", " . . ") = " . ack . cr ;     0 0 ackOf 0 4 ackOf 1 0 ackOf 1 1 ackOf 2 1 ackOf 2 2 ackOf 3 1 ackOf 3 3 ackOf 4 0 ackOf   \ this last requires a very large data stack. So start 8th with a parameter '-k 100000' 4 1 ackOf   bye
http://rosettacode.org/wiki/Abundant,_deficient_and_perfect_number_classifications
Abundant, deficient and perfect number classifications
These define three classifications of positive integers based on their   proper divisors. Let   P(n)   be the sum of the proper divisors of   n   where the proper divisors are all positive divisors of   n   other than   n   itself. if P(n) < n then n is classed as deficient (OEIS A005100). if P(n) == n then n is classed as perfect (OEIS A000396). if P(n) > n then n is classed as abundant (OEIS A005101). Example 6   has proper divisors of   1,   2,   and   3. 1 + 2 + 3 = 6,   so   6   is classed as a perfect number. Task Calculate how many of the integers   1   to   20,000   (inclusive) are in each of the three classes. Show the results here. Related tasks   Aliquot sequence classifications.   (The whole series from which this task is a subset.)   Proper divisors   Amicable pairs
#AppleScript
AppleScript
on aliquotSum(n) if (n < 2) then return 0 set sum to 1 set sqrt to n ^ 0.5 set limit to sqrt div 1 if (limit = sqrt) then set sum to sum + limit set limit to limit - 1 end if repeat with i from 2 to limit if (n mod i is 0) then set sum to sum + i + n div i end repeat   return sum end aliquotSum   on task() set {deficient, perfect, abundant} to {0, 0, 0} repeat with n from 1 to 20000 set s to aliquotSum(n) if (s < n) then set deficient to deficient + 1 else if (s > n) then set abundant to abundant + 1 else set perfect to perfect + 1 end if end repeat   return {deficient:deficient, perfect:perfect, abundant:abundant} end task   task()
http://rosettacode.org/wiki/Align_columns
Align columns
Given a text file of many lines, where fields within a line are delineated by a single 'dollar' character, write a program that aligns each column of fields by ensuring that words in each column are separated by at least one space. Further, allow for each word in a column to be either left justified, right justified, or center justified within its column. Use the following text to test your programs: Given$a$text$file$of$many$lines,$where$fields$within$a$line$ are$delineated$by$a$single$'dollar'$character,$write$a$program that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$ column$are$separated$by$at$least$one$space. Further,$allow$for$each$word$in$a$column$to$be$either$left$ justified,$right$justified,$or$center$justified$within$its$column. Note that:   The example input texts lines may, or may not, have trailing dollar characters.   All columns should share the same alignment.   Consecutive space characters produced adjacent to the end of lines are insignificant for the purposes of the task.   Output text will be viewed in a mono-spaced font on a plain text editor or basic terminal.   The minimum space between columns should be computed from the text and not hard-coded.   It is not a requirement to add separating characters between or around columns. 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
#AutoIt
AutoIt
  ; == If the given text is in an file, it will read with: #include <File.au3> Global $aRead _FileReadToArray($sPath, $aRead) ; == $aRead[0] includes count of lines, every line stored in one item (without linebreak)   ; == For example we get the same result with StringSplit() Global $sText = _ "Given$a$text$file$of$many$lines,$where$fields$within$a$line$" & @CRLF & _ "are$delineated$by$a$single$'dollar'$character,$write$a$program" & @CRLF & _ "that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$" & @CRLF & _ "column$are$separated$by$at$least$one$space." & @CRLF & _ "Further,$allow$for$each$word$in$a$column$to$be$either$left$" & @CRLF & _ "justified,$right$justified,$or$center$justified$within$its$column." & @CRLF   $aRead = StringSplit($sText, @CRLF, 1)   ; == strip leading and trailing "$" and trailing spaces, count remaining "$" to get max column number Global $iMaxColumn = 0, $iLines = 0 For $i = 1 To $aRead[0] If $aRead[$i] = '' Then ContinueLoop ; skip empty lines $iLines += 1 $aRead[$i] = StringRegExpReplace(StringRegExpReplace(StringRegExpReplace($aRead[$i], '^\$', ''), '\$$', ''), '\s*$', '') StringReplace($aRead[$i], '$', '$') If @extended +1 > $iMaxColumn Then $iMaxColumn = @extended +1 Next   ; == build array to store all fields and length of every item Global $aFields[$iLines][$iMaxColumn +1][2] ; == and store the max. length of item in columns Global $aColLen[$iMaxColumn]   ; == fill the array Global $aSplitLine $iLines = 0 For $i = 1 To $aRead[0] If $aRead[$i] = '' Then ContinueLoop ; skip empty lines $iMaxColLen = 0 $aSplitLine = StringSplit($aRead[$i], '$') For $j = 1 To $aSplitLine[0] $aFields[$iLines][$j-1][0] = $aSplitLine[$j] $aFields[$iLines][$j-1][1] = StringLen($aSplitLine[$j]) If $aFields[$iLines][$j-1][1] > $aColLen[$j-1] Then $aColLen[$j-1] = $aFields[$iLines][$j-1][1] Next $iLines += 1 Next   ; == let the user select the alignment for every column $sAlign = InputBox('Column alignment', 'There are ' & $iMaxColumn & ' columns.' & @LF & '0 = left 1 = center 2 = right' & @LF & _ 'Input alignment for all columns without delimiters.' & @LF & 'Let it empty, to align all left.') If $sAlign = '' Then For $i = 1 To $iMaxColumn $sAlign &= '0' Next EndIf Global $aAlignment = StringSplit($sAlign, '', 2)   ; == output all to console Global $sLineOut For $i = 0 To UBound($aFields) -1 $sLineOut = '' For $j = 0 To $iMaxColumn -1 If $aFields[$i][$j][0] = '' Then ContinueLoop $sLineOut &= _GetAligned($aFields[$i][$j][0], $aFields[$i][$j][1], $aAlignment[$j], $aColLen[$j]) Next ConsoleWrite(StringTrimRight($sLineOut, 1) & @LF) Next   Func _GetAligned($_sString, $_iLen, $_iAlign, $_iMaxLen) Local $sSpace = '' For $i = 1 To $_iMaxLen $sSpace &= ' ' Next Switch $_iAlign Case 0 Return $_sString & StringLeft($sSpace, $_iMaxLen - $_iLen +1) Case 1 Local $iLenLeft = Int(($_iMaxLen - $_iLen)/2) Local $iLenRight = $_iMaxLen - $iLenLeft - $_iLen Return StringLeft($sSpace, $iLenLeft) & $_sString & StringLeft($sSpace, $iLenRight) & ' ' Case 2 Return StringLeft($sSpace, $_iMaxLen - $_iLen) & $_sString & ' ' EndSwitch EndFunc ;==>_GetAligned  
http://rosettacode.org/wiki/Active_object
Active object
In object-oriented programming an object is active when its state depends on clock. Usually an active object encapsulates a task that updates the object's state. To the outer world the object looks like a normal object with methods that can be called from outside. Implementation of such methods must have a certain synchronization mechanism with the encapsulated task in order to prevent object's state corruption. A typical instance of an active object is an animation widget. The widget state changes with the time, while as an object it has all properties of a normal widget. The task Implement an active integrator object. The object has an input and output. The input can be set using the method Input. The input is a function of time. The output can be queried using the method Output. The object integrates its input over the time and the result becomes the object's output. So if the input is K(t) and the output is S, the object state S is changed to S + (K(t1) + K(t0)) * (t1 - t0) / 2, i.e. it integrates K using the trapeze method. Initially K is constant 0 and S is 0. In order to test the object: set its input to sin (2π f t), where the frequency f=0.5Hz. The phase is irrelevant. wait 2s set the input to constant 0 wait 0.5s Verify that now the object's output is approximately 0 (the sine has the period of 2s). The accuracy of the result will depend on the OS scheduler time slicing and the accuracy of the clock.
#FreeBASIC
FreeBASIC
#define twopi 6.2831853071795864769252867665590057684 dim shared as double S = 0 'set up the state as a global variable dim shared as double t0, t1, ta   function sine( x as double, f as double ) as double return sin(twopi*f*x) end function   function zero( x as double, f as double ) as double return 0 end function   sub integrate( K as function(as double, as double) as double, f as double ) 'represent input as pointers to functions t1 = timer s += (K(t1,f) + K(t0,f))*(t1-t0)/2.0 t0 = t1 end sub   t0 = timer ta = timer   while timer-ta <= 2.5 if timer-ta <= 2 then integrate( @sine, 0.5 ) else integrate( @zero, 0 ) wend   print S  
http://rosettacode.org/wiki/Active_object
Active object
In object-oriented programming an object is active when its state depends on clock. Usually an active object encapsulates a task that updates the object's state. To the outer world the object looks like a normal object with methods that can be called from outside. Implementation of such methods must have a certain synchronization mechanism with the encapsulated task in order to prevent object's state corruption. A typical instance of an active object is an animation widget. The widget state changes with the time, while as an object it has all properties of a normal widget. The task Implement an active integrator object. The object has an input and output. The input can be set using the method Input. The input is a function of time. The output can be queried using the method Output. The object integrates its input over the time and the result becomes the object's output. So if the input is K(t) and the output is S, the object state S is changed to S + (K(t1) + K(t0)) * (t1 - t0) / 2, i.e. it integrates K using the trapeze method. Initially K is constant 0 and S is 0. In order to test the object: set its input to sin (2π f t), where the frequency f=0.5Hz. The phase is irrelevant. wait 2s set the input to constant 0 wait 0.5s Verify that now the object's output is approximately 0 (the sine has the period of 2s). The accuracy of the result will depend on the OS scheduler time slicing and the accuracy of the clock.
#Go
Go
package main   import ( "fmt" "math" "time" )   // type for input function, k. // input is duration since an arbitrary start time t0. type tFunc func(time.Duration) float64   // active integrator object. state variables are not here, but in // function aif, started as a goroutine in the constructor. type aio struct { iCh chan tFunc // channel for setting input function oCh chan chan float64 // channel for requesting output }   // constructor func newAio() *aio { var a aio a.iCh = make(chan tFunc) a.oCh = make(chan chan float64) go aif(&a) return &a }   // input method required by task description. in practice, this method is // unnecessary; you would just put that single channel send statement in // your code wherever you wanted to set the input function. func (a aio) input(f tFunc) { a.iCh <- f }   // output method required by task description. in practice, this method too // would not likely be best. instead any client interested in the value would // likely make a return channel sCh once, and then reuse it as needed. func (a aio) output() float64 { sCh := make(chan float64) a.oCh <- sCh return <-sCh }   // integration function that returns constant 0 func zeroFunc(time.Duration) float64 { return 0 }   // goroutine serializes access to integrated function k and state variable s func aif(a *aio) { var k tFunc = zeroFunc // integration function s := 0. // "object state" initialized to 0 t0 := time.Now() // initial time k0 := k(0) // initial sample value t1 := t0 // t1, k1 used for trapezoid formula k1 := k0   tk := time.Tick(10 * time.Millisecond) // 10 ms -> 100 Hz for { select { case t2 := <-tk: // timer tick event k2 := k(t2.Sub(t0)) // new sample value s += (k1 + k2) * .5 * t2.Sub(t1).Seconds() // trapezoid formula t1, k1 = t2, k2 // save time and value case k = <-a.iCh: // input method event: function change case sCh := <-a.oCh: // output method event: sample object state sCh <- s } } }   func main() { a := newAio() // create object a.input(func(t time.Duration) float64 { // 1. set input to sin function return math.Sin(t.Seconds() * math.Pi) }) time.Sleep(2 * time.Second) // 2. sleep 2 sec a.input(zeroFunc) // 3. set input to zero function time.Sleep(time.Second / 2) // 4. sleep .5 sec fmt.Println(a.output()) // output should be near zero }
http://rosettacode.org/wiki/Aliquot_sequence_classifications
Aliquot sequence classifications
An aliquot sequence of a positive integer K is defined recursively as the first member being K and subsequent members being the sum of the Proper divisors of the previous term. If the terms eventually reach 0 then the series for K is said to terminate. There are several classifications for non termination: If the second term is K then all future terms are also K and so the sequence repeats from the first term with period 1 and K is called perfect. If the third term would be repeating K then the sequence repeats with period 2 and K is called amicable. If the Nth term would be repeating K for the first time, with N > 3 then the sequence repeats with period N - 1 and K is called sociable. Perfect, amicable and sociable numbers eventually repeat the original number K; there are other repetitions... Some K have a sequence that eventually forms a periodic repetition of period 1 but of a number other than K, for example 95 which forms the sequence 95, 25, 6, 6, 6, ... such K are called aspiring. K that have a sequence that eventually forms a periodic repetition of period >= 2 but of a number other than K, for example 562 which forms the sequence 562, 284, 220, 284, 220, ... such K are called cyclic. And finally: Some K form aliquot sequences that are not known to be either terminating or periodic; these K are to be called non-terminating. For the purposes of this task, K is to be classed as non-terminating if it has not been otherwise classed after generating 16 terms or if any term of the sequence is greater than 2**47 = 140,737,488,355,328. Task Create routine(s) to generate the aliquot sequence of a positive integer enough to classify it according to the classifications given above. Use it to display the classification and sequences of the numbers one to ten inclusive. Use it to show the classification and sequences of the following integers, in order: 11, 12, 28, 496, 220, 1184, 12496, 1264460, 790, 909, 562, 1064, 1488, and optionally 15355717786080. Show all output on this page. Related tasks   Abundant, deficient and perfect number classifications. (Classifications from only the first two members of the whole sequence).   Proper divisors   Amicable pairs
#Liberty_BASIC
Liberty BASIC
  print "ROSETTA CODE - Aliquot sequence classifications" [Start] input "Enter an integer: "; K K=abs(int(K)): if K=0 then goto [Quit] call PrintAS K goto [Start]   [Quit] print "Program complete." end   sub PrintAS K Length=52 dim Aseq(Length) n=K: class=0 for element=2 to Length Aseq(element)=PDtotal(n) print Aseq(element); " "; select case case Aseq(element)=0 print " terminating": class=1: exit for case Aseq(element)=K and element=2 print " perfect": class=2: exit for case Aseq(element)=K and element=3 print " amicable": class=3: exit for case Aseq(element)=K and element>3 print " sociable": class=4: exit for case Aseq(element)<>K and Aseq(element-1)=Aseq(element) print " aspiring": class=5: exit for case Aseq(element)<>K and Aseq(element-2)= Aseq(element) print " cyclic": class=6: exit for end select n=Aseq(element) if n>priorn then priorn=n: inc=inc+1 else inc=0: priorn=0 if inc=11 or n>30000000 then exit for next element if class=0 then print " non-terminating" end sub   function PDtotal(n) for y=2 to n if (n mod y)=0 then PDtotal=PDtotal+(n/y) next end function  
http://rosettacode.org/wiki/Add_a_variable_to_a_class_instance_at_runtime
Add a variable to a class instance at runtime
Demonstrate how to dynamically add variables to an object (a class instance) at runtime. This is useful when the methods/variables of an instance are based on a data file that isn't available until runtime. Hal Fulton gives an example of creating an OO CSV parser at An Exercise in Metaprogramming with Ruby. This is referred to as "monkeypatching" by Pythonistas and some others.
#Wren
Wren
import "io" for Stdin, Stdout   class Birds { construct new(userFields) { _userFields = userFields } userFields { _userFields } }   var userFields = {} System.print("Enter three fields to add to the Birds class:") for (i in 0..2) { System.write("\n name : ") Stdout.flush() var name = Stdin.readLine() System.write(" value: ") Stdout.flush() var value = Num.fromString(Stdin.readLine()) userFields[name] = value }   var birds = Birds.new(userFields)   System.print("\nYour fields are:\n") for (kv in birds.userFields) { System.print("  %(kv.key) = %(kv.value)") }
http://rosettacode.org/wiki/Add_a_variable_to_a_class_instance_at_runtime
Add a variable to a class instance at runtime
Demonstrate how to dynamically add variables to an object (a class instance) at runtime. This is useful when the methods/variables of an instance are based on a data file that isn't available until runtime. Hal Fulton gives an example of creating an OO CSV parser at An Exercise in Metaprogramming with Ruby. This is referred to as "monkeypatching" by Pythonistas and some others.
#XBS
XBS
set Object = {} Object.Hello = "World"; log(Object.Hello);
http://rosettacode.org/wiki/Address_of_a_variable
Address of a variable
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation | Comparison | Matching Memory Operations Pointers & references | Addresses Task Demonstrate how to get the address of a variable and how to set the address of a variable.
#Stata
Stata
a = 1 &a   function f(x) { return(x+1) }   &f()
http://rosettacode.org/wiki/Address_of_a_variable
Address of a variable
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation | Comparison | Matching Memory Operations Pointers & references | Addresses Task Demonstrate how to get the address of a variable and how to set the address of a variable.
#Swift
Swift
  class MyClass { }   func printAddress<T>(of pointer: UnsafePointer<T>) { print(pointer) }   func test() { var x = 42 var y = 3.14 var z = "foo" var obj = MyClass()   // Use a pointer to a variable on the stack and print its address. withUnsafePointer(to: &x) { print($0) } withUnsafePointer(to: &y) { print($0) } withUnsafePointer(to: &z) { print($0) } withUnsafePointer(to: &obj) { print($0) }   // Alternately: printAddress(of: &x) printAddress(of: &y) printAddress(of: &z) printAddress(of: &obj)   // Printing the address of an object that an object reference points to. print(Unmanaged.passUnretained(obj).toOpaque()) }   test()  
http://rosettacode.org/wiki/Address_of_a_variable
Address of a variable
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation | Comparison | Matching Memory Operations Pointers & references | Addresses Task Demonstrate how to get the address of a variable and how to set the address of a variable.
#Tcl
Tcl
package require critcl # This code assumes an ILP32 architecture, like classic x86 or VAX. critcl::cproc peek {int addr} int { union { int i; int *a; } u;   u.i = addr; return *u.a; } critcl::cproc poke {int addr int value} void { union { int i; int *a; } u;   u.i = addr; *u.a = value; } package provide poker 1.0
http://rosettacode.org/wiki/Address_of_a_variable
Address of a variable
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation | Comparison | Matching Memory Operations Pointers & references | Addresses Task Demonstrate how to get the address of a variable and how to set the address of a variable.
#Toka
Toka
variable foo foo .
http://rosettacode.org/wiki/AKS_test_for_primes
AKS test for primes
The AKS algorithm for testing whether a number is prime is a polynomial-time algorithm based on an elementary theorem about Pascal triangles. The theorem on which the test is based can be stated as follows:   a number   p {\displaystyle p}   is prime   if and only if   all the coefficients of the polynomial expansion of ( x − 1 ) p − ( x p − 1 ) {\displaystyle (x-1)^{p}-(x^{p}-1)} are divisible by   p {\displaystyle p} . Example Using   p = 3 {\displaystyle p=3} : (x-1)^3 - (x^3 - 1) = (x^3 - 3x^2 + 3x - 1) - (x^3 - 1) = -3x^2 + 3x And all the coefficients are divisible by 3,   so 3 is prime. Note: This task is not the AKS primality test.   It is an inefficient exponential time algorithm discovered in the late 1600s and used as an introductory lemma in the AKS derivation. Task Create a function/subroutine/method that given   p {\displaystyle p}   generates the coefficients of the expanded polynomial representation of   ( x − 1 ) p {\displaystyle (x-1)^{p}} . Use the function to show here the polynomial expansions of   ( x − 1 ) p {\displaystyle (x-1)^{p}}   for   p {\displaystyle p}   in the range   0   to at least   7,   inclusive. Use the previous function in creating another function that when given   p {\displaystyle p}   returns whether   p {\displaystyle p}   is prime using the theorem. Use your test to generate a list of all primes under   35. As a stretch goal,   generate all primes under   50   (needs integers larger than 31-bit). References Agrawal-Kayal-Saxena (AKS) primality test (Wikipedia) Fool-Proof Test for Primes - Numberphile (Video). The accuracy of this video is disputed -- at best it is an oversimplification.
#Fortran
Fortran
  program aks implicit none   ! Coefficients of polynomial expansion integer(kind=16), dimension(:), allocatable :: coeffs integer(kind=16) :: n ! Character variable for I/O character(len=40) :: tmp   ! Point #2 do n = 0, 7 write(tmp, *) n call polynomial_expansion(n, coeffs) write(*, fmt='(A)', advance='no') '(x - 1)^'//trim(adjustl(tmp))//' =' call print_polynom(coeffs) end do   ! Point #4 do n = 2, 35 if (is_prime(n)) write(*, '(I4)', advance='no') n end do write(*, *)   ! Point #5 do n = 2, 124 if (is_prime(n)) write(*, '(I4)', advance='no') n end do write(*, *)   if (allocated(coeffs)) deallocate(coeffs) contains ! Calculate coefficients of (x - 1)^n using binomial theorem subroutine polynomial_expansion(n, coeffs) integer(kind=16), intent(in) :: n integer(kind=16), dimension(:), allocatable, intent(out) :: coeffs integer(kind=16) :: i, j   if (allocated(coeffs)) deallocate(coeffs)   allocate(coeffs(n + 1))   do i = 1, n + 1 coeffs(i) = binomial(n, i - 1)*(-1)**(n - i - 1) end do end subroutine   ! Calculate binomial coefficient using recurrent relation, as calculation ! using factorial overflows too quickly. function binomial(n, k) result (res) integer(kind=16), intent(in) :: n, k integer(kind=16) :: res integer(kind=16) :: i   if (k == 0) then res = 1 return end if   res = 1 do i = 0, k - 1 res = res*(n - i)/(i + 1) end do end function   ! Outputs polynomial with given coefficients subroutine print_polynom(coeffs) integer(kind=16), dimension(:), allocatable, intent(in) :: coeffs integer(kind=4) :: i, p character(len=40) :: cbuf, pbuf logical(kind=1) :: non_zero   if (.not. allocated(coeffs)) return   non_zero = .false.   do i = 1, size(coeffs) if (coeffs(i) .eq. 0) cycle   p = i - 1 write(cbuf, '(I40)') abs(coeffs(i)) write(pbuf, '(I40)') p   if (non_zero) then if (coeffs(i) .gt. 0) then write(*, fmt='(A)', advance='no') ' + ' else write(*, fmt='(A)', advance='no') ' - ' endif else if (coeffs(i) .gt. 0) then write(*, fmt='(A)', advance='no') ' ' else write(*, fmt='(A)', advance='no') ' - ' endif endif   if (p .eq. 0) then write(*, fmt='(A)', advance='no') trim(adjustl(cbuf)) elseif (p .eq. 1) then if (coeffs(i) .eq. 1) then write(*, fmt='(A)', advance='no') 'x' else write(*, fmt='(A)', advance='no') trim(adjustl(cbuf))//'x' end if else if (coeffs(i) .eq. 1) then write(*, fmt='(A)', advance='no') 'x^'//trim(adjustl(pbuf)) else write(*, fmt='(A)', advance='no') & trim(adjustl(cbuf))//'x^'//trim(adjustl(pbuf)) end if end if non_zero = .true. end do   write(*, *) end subroutine   ! Test if n is prime using AKS test. Point #3. function is_prime(n) result (res) integer(kind=16), intent (in) :: n logical(kind=1) :: res integer(kind=16), dimension(:), allocatable :: coeffs integer(kind=16) :: i   call polynomial_expansion(n, coeffs) coeffs(1) = coeffs(1) + 1 coeffs(n + 1) = coeffs(n + 1) - 1   res = .true.   do i = 1, n + 1 res = res .and. (mod(coeffs(i), n) == 0) end do   if (allocated(coeffs)) deallocate(coeffs) end function end program aks  
http://rosettacode.org/wiki/Additive_primes
Additive primes
Definitions In mathematics, additive primes are prime numbers for which the sum of their decimal digits are also primes. Task Write a program to determine (and show here) all additive primes less than 500. Optionally, show the number of additive primes. Also see   the OEIS entry:   A046704 additive primes.   the prime-numbers entry:   additive primes.   the geeks for geeks entry: additive prime number.   the prime-numbers fandom: additive primes.
#Nim
Nim
import math, strutils   const N = 499   # Sieve of Erathostenes. var composite: array[2..N, bool] # Initialized to false, ie. prime.   for n in 2..sqrt(N.toFloat).int: if not composite[n]: for k in countup(n * n, N, n): composite[k] = true     func digitSum(n: Positive): Natural = ## Compute sum of digits. var n = n.int while n != 0: result += n mod 10 n = n div 10     echo "Additive primes less than 500:" var count = 0 for n in 2..N: if not composite[n] and not composite[digitSum(n)]: inc count stdout.write ($n).align(3) stdout.write if count mod 10 == 0: '\n' else: ' ' echo()   echo "\nNumber of additive primes found: ", count
http://rosettacode.org/wiki/Additive_primes
Additive primes
Definitions In mathematics, additive primes are prime numbers for which the sum of their decimal digits are also primes. Task Write a program to determine (and show here) all additive primes less than 500. Optionally, show the number of additive primes. Also see   the OEIS entry:   A046704 additive primes.   the prime-numbers entry:   additive primes.   the geeks for geeks entry: additive prime number.   the prime-numbers fandom: additive primes.
#Pari.2FGP
Pari/GP
hasPrimeDigitsum(n)=isprime(sumdigits(n)); \\ see A028834 in the OEIS   v1 = select(isprime, select(hasPrimeDigitsum, [1..499])); v2 = select(hasPrimeDigitsum, select(isprime, [1..499])); v3 = select(hasPrimeDigitsum, primes([1, 499]));   s=0; forprime(p=2,499, if(hasPrimeDigitsum(p), s++)); s; [#v1, #v2, #v3, s]
http://rosettacode.org/wiki/Almost_prime
Almost prime
A   k-Almost-prime   is a natural number   n {\displaystyle n}   that is the product of   k {\displaystyle k}   (possibly identical) primes. Example 1-almost-primes,   where   k = 1 {\displaystyle k=1} ,   are the prime numbers themselves. 2-almost-primes,   where   k = 2 {\displaystyle k=2} ,   are the   semiprimes. Task Write a function/method/subroutine/... that generates k-almost primes and use it to create a table here of the first ten members of k-Almost primes for   1 <= K <= 5 {\displaystyle 1<=K<=5} . Related tasks   Semiprime   Category:Prime Numbers
#Lua
Lua
-- Returns boolean indicating whether n is k-almost prime function almostPrime (n, k) local divisor, count = 2, 0 while count < k + 1 and n ~= 1 do if n % divisor == 0 then n = n / divisor count = count + 1 else divisor = divisor + 1 end end return count == k end   -- Generates table containing first ten k-almost primes for given k function kList (k) local n, kTab = 2^k, {} while #kTab < 10 do if almostPrime(n, k) then table.insert(kTab, n) end n = n + 1 end return kTab end   -- Main procedure, displays results from five calls to kList() for k = 1, 5 do io.write("k=" .. k .. ": ") for _, v in pairs(kList(k)) do io.write(v .. ", ") end print("...") end
http://rosettacode.org/wiki/Anagrams
Anagrams
When two or more words are composed of the same characters, but in a different order, they are called anagrams. Task[edit] Using the word list at   http://wiki.puzzlers.org/pub/wordlists/unixdict.txt, find the sets of words that share the same characters that contain the most words in them. Related tasks Word plays Ordered words Palindrome detection Semordnilap Anagrams Anagrams/Deranged anagrams Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#Elena
Elena
import system'routines; import system'calendar; import system'io; import system'collections; import extensions; import extensions'routines; import extensions'text;   extension op { string normalized() = self.toArray().ascendant().summarize(new StringWriter()); }   public program() { var start := now;   auto dictionary := new Map<string,object>();   File.assign("unixdict.txt").forEachLine:(word) { var key := word.normalized(); var item := dictionary[key]; if (nil == item) { item := new ArrayList(); dictionary[key] := item };   item.append:word };   dictionary.Values .sort:(former,later => former.Item2.Length > later.Item2.Length ) .top:20 .forEach:(pair){ console.printLine(pair.Item2) };   var end := now;   var diff := end - start;   console.printLine("Time elapsed in msec:",diff.Milliseconds);   console.readChar() }
http://rosettacode.org/wiki/Angle_difference_between_two_bearings
Angle difference between two bearings
Finding the angle between two bearings is often confusing.[1] Task Find the angle which is the result of the subtraction b2 - b1, where b1 and b2 are the bearings. Input bearings are expressed in the range   -180   to   +180   degrees. The  result  is also expressed in the range   -180   to   +180   degrees. Compute the angle for the following pairs: 20 degrees (b1) and 45 degrees (b2) -45 and 45 -85 and 90 -95 and 90 -45 and 125 -45 and 145 29.4803 and -88.6381 -78.3251 and -159.036 Optional extra Allow the input bearings to be any (finite) value. Test cases -70099.74233810938 and 29840.67437876723 -165313.6666297357 and 33693.9894517456 1174.8380510598456 and -154146.66490124757 60175.77306795546 and 42213.07192354373
#Run_BASIC
Run BASIC
sub getDifference b1, b2 r = (b2 - b1) mod 360 if r >= 180 then r = r - 360 print r end sub   print "Input in -180 to +180 range:" call getDifference 20, 45 call getDifference -45, 45 call getDifference -85, 90 call getDifference -95, 90 call getDifference -45, 125 call getDifference -45, 145 call getDifference -45, 125 call getDifference -45, 145 call getDifference 29.4803, -88.6381 call getDifference -78.3251, -159.036 print "Input in wider range:" call getDifference -70099.74233810938, 29840.67437876723 call getDifference -165313.6666297357, 33693.9894517456 call getDifference 1174.8380510598456, -154146.66490124757
http://rosettacode.org/wiki/Angle_difference_between_two_bearings
Angle difference between two bearings
Finding the angle between two bearings is often confusing.[1] Task Find the angle which is the result of the subtraction b2 - b1, where b1 and b2 are the bearings. Input bearings are expressed in the range   -180   to   +180   degrees. The  result  is also expressed in the range   -180   to   +180   degrees. Compute the angle for the following pairs: 20 degrees (b1) and 45 degrees (b2) -45 and 45 -85 and 90 -95 and 90 -45 and 125 -45 and 145 29.4803 and -88.6381 -78.3251 and -159.036 Optional extra Allow the input bearings to be any (finite) value. Test cases -70099.74233810938 and 29840.67437876723 -165313.6666297357 and 33693.9894517456 1174.8380510598456 and -154146.66490124757 60175.77306795546 and 42213.07192354373
#Rust
Rust
  /// Calculate difference between two bearings, in -180 to 180 degrees range pub fn angle_difference(bearing1: f64, bearing2: f64) -> f64 { let diff = (bearing2 - bearing1) % 360.0; if diff < -180.0 { 360.0 + diff } else if diff > 180.0 { -360.0 + diff } else { diff }   }   #[cfg(test)] mod tests { use super::*;   #[test] fn test_angle_difference() { assert_eq!(25.00, angle_difference(20.00, 45.00)); assert_eq!(90.00, angle_difference(-45.00, 45.00)); assert_eq!(175.00, angle_difference(-85.00, 90.00)); assert_eq!(-175.00, angle_difference(-95.00, 90.00)); assert_eq!(170.00, angle_difference(-45.00, 125.00)); assert_eq!(-170.00, angle_difference(-45.00, 145.00)); approx_eq(-118.1184, angle_difference(29.4803, -88.6381)); approx_eq(-80.7109, angle_difference(-78.3251 , -159.036)); approx_eq(-139.5832, angle_difference(-70099.74233810938, 29840.67437876723)); approx_eq(-72.3439, angle_difference(-165313.6666297357, 33693.9894517456)); approx_eq(-161.5029, angle_difference(1174.8380510598456, -154146.66490124757)); approx_eq(37.2988, angle_difference(60175.77306795546, 42213.07192354373)); }   // approximate equality on floats. // see also https://crates.io/crates/float-cmp fn approx_eq(f1: f64, f2: f64) { assert!((f2-f1).abs() < 0.0001, "{} != {}", f1, f2) } }  
http://rosettacode.org/wiki/Anagrams/Deranged_anagrams
Anagrams/Deranged anagrams
Two or more words are said to be anagrams if they have the same characters, but in a different order. By analogy with derangements we define a deranged anagram as two words with the same characters, but in which the same character does not appear in the same position in both words. Task[edit] Use the word list at unixdict to find and display the longest deranged anagram. Related tasks Permutations/Derangements Best shuffle Word plays Ordered words Palindrome detection Semordnilap Anagrams Anagrams/Deranged anagrams Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#Scala
Scala
object DerangedAnagrams {   /** Returns a map of anagrams keyed by the sorted characters */ def groupAnagrams(words: Iterable[String]): Map[String, Set[String]] = words.foldLeft (Map[String, Set[String]]()) { (map, word) => val sorted = word.sorted val entry = map.getOrElse(sorted, Set.empty) map + (sorted -> (entry + word)) }   /* Returns true if the pair of strings has no positions with the same * characters */ def isDeranged(ss: (String, String)): Boolean = ss._1 zip ss._2 forall { case (c1, c2) => c1 != c2 }   /* Returns pairwise combination of all Strings in the argument Iterable */ def pairWords(as: Iterable[String]): Iterable[(String, String)] = if (as.size < 2) Seq() else (as.tail map (as.head -> _)) ++ pairWords(as.tail)   /* Returns the contents of the argument URL as an Iterable[String], each * String is one line in the file */ def readLines(url: String): Iterable[String] = io.Source.fromURL(url).getLines().toIterable   val wordsURL = "http://www.puzzlers.org/pub/wordlists/unixdict.txt"   def main(args: Array[String]): Unit = { val anagramMap = groupAnagrams(readLines(wordsURL)) val derangedPairs = anagramMap.values flatMap (pairWords) filter (isDeranged) val (w1, w2) = derangedPairs maxBy (pair => pair._1.length) println("Longest deranged pair: "+w1+" and "+w2) }   }
http://rosettacode.org/wiki/Anonymous_recursion
Anonymous recursion
While implementing a recursive function, it often happens that we must resort to a separate   helper function   to handle the actual recursion. This is usually the case when directly calling the current function would waste too many resources (stack space, execution time), causing unwanted side-effects,   and/or the function doesn't have the right arguments and/or return values. So we end up inventing some silly name like   foo2   or   foo_helper.   I have always found it painful to come up with a proper name, and see some disadvantages:   You have to think up a name, which then pollutes the namespace   Function is created which is called from nowhere else   The program flow in the source code is interrupted Some languages allow you to embed recursion directly in-place.   This might work via a label, a local gosub instruction, or some special keyword. Anonymous recursion can also be accomplished using the   Y combinator. Task If possible, demonstrate this by writing the recursive version of the fibonacci function   (see Fibonacci sequence)   which checks for a negative argument before doing the actual recursion.
#PicoLisp
PicoLisp
(de fibo (N) (if (lt0 N) (quit "Illegal argument" N) ) (recur (N) (if (> 2 N) 1 (+ (recurse (dec N)) (recurse (- N 2))) ) ) )
http://rosettacode.org/wiki/Amicable_pairs
Amicable pairs
Two integers N {\displaystyle N} and M {\displaystyle M} are said to be amicable pairs if N ≠ M {\displaystyle N\neq M} and the sum of the proper divisors of N {\displaystyle N} ( s u m ( p r o p D i v s ( N ) ) {\displaystyle \mathrm {sum} (\mathrm {propDivs} (N))} ) = M {\displaystyle =M} as well as s u m ( p r o p D i v s ( M ) ) = N {\displaystyle \mathrm {sum} (\mathrm {propDivs} (M))=N} . Example 1184 and 1210 are an amicable pair, with proper divisors:   1, 2, 4, 8, 16, 32, 37, 74, 148, 296, 592   and   1, 2, 5, 10, 11, 22, 55, 110, 121, 242, 605   respectively. Task Calculate and show here the Amicable pairs below 20,000; (there are eight). Related tasks Proper divisors Abundant, deficient and perfect number classifications Aliquot sequence classifications and its amicable classification.
#Phix
Phix
integer n for m=1 to 20000 do n = sum(factors(m,-1)) if m<n and m=sum(factors(n,-1)) then ?{m,n} end if end for
http://rosettacode.org/wiki/Animate_a_pendulum
Animate a pendulum
One good way of making an animation is by simulating a physical system and illustrating the variables in that system using a dynamically changing graphical display. The classic such physical system is a simple gravity pendulum. Task Create a simple physical model of a pendulum and animate it.
#Ring
Ring
  # Project : Animate a pendulum   load "guilib.ring" load "stdlib.ring"   CounterMan = 1 paint = null pi = 22/7 theta = pi/180*40 g = 9.81 l = 0.50 speed = 0   new qapp { win1 = new qwidget() { setwindowtitle("Animate a pendulum") setgeometry(100,100,800,600) label1 = new qlabel(win1) { setgeometry(10,10,800,600) settext("") } new qpushbutton(win1) { setgeometry(150,500,100,30) settext("draw") setclickevent("draw()") } TimerMan = new qtimer(win1) { setinterval(1000) settimeoutevent("draw()") start() } show() } exec() }   func draw p1 = new qpicture() color = new qcolor() { setrgb(0,0,255,255) } pen = new qpen() { setcolor(color) setwidth(1) } paint = new qpainter() { begin(p1) setpen(pen) ptime() endpaint() } label1 { setpicture(p1) show() } return   func ptime() TimerMan.start() pPlaySleep() sleep(0.1) CounterMan++ if CounterMan = 20 TimerMan.stop() ok   func pPlaySleep() pendulum(theta, l) pendulum(theta, l) accel = - g * sin(theta) / l / 100 speed = speed + accel / 100 theta = theta + speed   func pendulum(a, l) pivotx = 640 pivoty = 800 bobx = pivotx + l * 1000 * sin(a) boby = pivoty - l * 1000 * cos(a) paint.drawline(pivotx, pivoty, bobx, boby) paint.drawellipse(bobx + 24 * sin(a), boby - 24 * cos(a), 24, 24)  
http://rosettacode.org/wiki/Amb
Amb
Define and give an example of the Amb operator. The Amb operator (short for "ambiguous") expresses nondeterminism. This doesn't refer to randomness (as in "nondeterministic universe") but is closely related to the term as it is used in automata theory ("non-deterministic finite automaton"). The Amb operator takes a variable number of expressions (or values if that's simpler in the language) and yields a correct one which will satisfy a constraint in some future computation, thereby avoiding failure. Problems whose solution the Amb operator naturally expresses can be approached with other tools, such as explicit nested iterations over data sets, or with pattern matching. By contrast, the Amb operator appears integrated into the language. Invocations of Amb are not wrapped in any visible loops or other search patterns; they appear to be independent. Essentially Amb(x, y, z) splits the computation into three possible futures: a future in which the value x is yielded, a future in which the value y is yielded and a future in which the value z is yielded. The future which leads to a successful subsequent computation is chosen. The other "parallel universes" somehow go away. Amb called with no arguments fails. For simplicity, one of the domain values usable with Amb may denote failure, if that is convenient. For instance, it is convenient if a Boolean false denotes failure, so that Amb(false) fails, and thus constraints can be expressed using Boolean expressions like Amb(x * y == 8) which unless x and y add to four. A pseudo-code program which satisfies this constraint might look like: let x = Amb(1, 2, 3) let y = Amb(7, 6, 4, 5) Amb(x * y = 8) print x, y The output is 2 4 because Amb(1, 2, 3) correctly chooses the future in which x has value 2, Amb(7, 6, 4, 5) chooses 4 and consequently Amb(x * y = 8) produces a success. Alternatively, failure could be represented using strictly Amb(): unless x * y = 8 do Amb() Or else Amb could take the form of two operators or functions: one for producing values and one for enforcing constraints: let x = Ambsel(1, 2, 3) let y = Ambsel(4, 5, 6) Ambassert(x * y = 8) print x, y where Ambassert behaves like Amb() if the Boolean expression is false, otherwise it allows the future computation to take place, without yielding any value. The task is to somehow implement Amb, and demonstrate it with a program which chooses one word from each of the following four sets of character strings to generate a four-word sentence: "the" "that" "a" "frog" "elephant" "thing" "walked" "treaded" "grows" "slowly" "quickly" The constraint to be satisfied is that the last character of each word (other than the last) is the same as the first character of its successor. The only successful sentence is "that thing grows slowly"; other combinations do not satisfy the constraint and thus fail. The goal of this task isn't to simply process the four lists of words with explicit, deterministic program flow such as nested iteration, to trivially demonstrate the correct output. The goal is to implement the Amb operator, or a facsimile thereof that is possible within the language limitations.
#langur
langur
val .wordsets = [ w/the that a/, w/frog elephant thing/, w/walked treaded grows/, w/slowly quickly/, ]   val .alljoin = f(.words) for[=true] .i of len(.words)-1 { if last(.words[.i]) != first(.words[.i+1]): break = false }   # .amb expects 2 or more arguments val .amb = f(...[2 to -1] .words) if(.alljoin(.words): join " ", .words)   writeln join "\n", where(mapX(.amb, .wordsets...))