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/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.
#Qi
Qi
  (define fib N -> (let A (/. A N (if (< N 2) N (+ (A A (- N 2)) (A A (- N 1))))) (A A 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.
#PL.2FI
PL/I
*process source xref; ami: Proc Options(main); p9a=time(); Dcl (p9a,p9b,p9c) Pic'(9)9'; Dcl sumpd(20000) Bin Fixed(31); Dcl pd(300) Bin Fixed(31); Dcl npd Bin Fixed(31); Dcl (x,y) Bin Fixed(31);   Do x=1 To 20000; Call proper_divisors(x,pd,npd); sumpd(x)=sum(pd,npd); End; p9b=time(); Put Edit('sum(pd) computed in',(p9b-p9a)/1000,' seconds elapsed') (Skip,col(7),a,f(6,3),a);   Do x=1 To 20000; Do y=x+1 To 20000; If y=sumpd(x) & x=sumpd(y) Then Put Edit(x,y,' found after ',elapsed(),' seconds') (Skip,2(f(6)),a,f(6,3),a); End; End; Put Edit(elapsed(),' seconds total search time')(Skip,f(6,3),a);   proper_divisors: Proc(n,pd,npd); Dcl (n,pd(300),npd) Bin Fixed(31); Dcl (d,delta) Bin Fixed(31); npd=0; If n>1 Then Do; If mod(n,2)=1 Then /* odd number */ delta=2; Else /* even number */ delta=1; Do d=1 To n/2 By delta; If mod(n,d)=0 Then Do; npd+=1; pd(npd)=d; End; End; End; End;   sum: Proc(pd,npd) Returns(Bin Fixed(31)); Dcl (pd(300),npd) Bin Fixed(31); Dcl sum Bin Fixed(31) Init(0); Dcl i Bin Fixed(31); Do i=1 To npd; sum+=pd(i); End; Return(sum); End;   elapsed: Proc Returns(Dec Fixed(6,3)); p9c=time(); Return((p9c-p9b)/1000); End; End;
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.
#Scheme
Scheme
#!r6rs   ;;; R6RS implementation of Pendulum Animation   (import (rnrs) (lib pstk main) ; change this for your pstk installation )   (define PI 3.14159) (define *conv-radians* (/ PI 180)) (define *theta* 45.0) (define *d-theta* 0.0) (define *length* 150) (define *home-x* 160) (define *home-y* 25)   ;;; estimates new angle of pendulum (define (recompute-angle) (define (avg a b) (/ (+ a b) 2)) (let* ((scaling (/ 3000.0 (* *length* *length*))) ; first estimate (first-dd-theta (- (* (sin (* *theta* *conv-radians*)) scaling))) (mid-d-theta (+ *d-theta* first-dd-theta)) (mid-theta (+ *theta* (avg *d-theta* mid-d-theta))) ; second estimate (mid-dd-theta (- (* (sin (* mid-theta *conv-radians*)) scaling))) (mid-d-theta-2 (+ *d-theta* (avg first-dd-theta mid-dd-theta))) (mid-theta-2 (+ *theta* (avg *d-theta* mid-d-theta-2))) ; again first (mid-dd-theta-2 (- (* (sin (* mid-theta-2 *conv-radians*)) scaling))) (last-d-theta (+ mid-d-theta-2 mid-dd-theta-2)) (last-theta (+ mid-theta-2 (avg mid-d-theta-2 last-d-theta))) ; again second (last-dd-theta (- (* (sin (* last-theta *conv-radians*)) scaling))) (last-d-theta-2 (+ mid-d-theta-2 (avg mid-dd-theta-2 last-dd-theta))) (last-theta-2 (+ mid-theta-2 (avg mid-d-theta-2 last-d-theta-2)))) ; put values back in globals (set! *d-theta* last-d-theta-2) (set! *theta* last-theta-2)))   ;;; The main event loop and graphics context (let ((tk (tk-start))) (tk/wm 'title tk "Pendulum Animation") (let ((canvas (tk 'create-widget 'canvas)))   ;;; redraw the pendulum on canvas ;;; - uses angle and length to compute new (x,y) position of bob (define (show-pendulum canvas) (let* ((pendulum-angle (* *conv-radians* *theta*)) (x (+ *home-x* (* *length* (sin pendulum-angle)))) (y (+ *home-y* (* *length* (cos pendulum-angle))))) (canvas 'coords 'rod *home-x* *home-y* x y) (canvas 'coords 'bob (- x 15) (- y 15) (+ x 15) (+ y 15))))   ;;; move the pendulum and repeat after 20ms (define (animate) (recompute-angle) (show-pendulum canvas) (tk/after 20 animate))   ;; layout the canvas (tk/grid canvas 'column: 0 'row: 0) (canvas 'create 'line 0 25 320 25 'tags: 'plate 'width: 2 'fill: 'grey50) (canvas 'create 'oval 155 20 165 30 'tags: 'pivot 'outline: "" 'fill: 'grey50) (canvas 'create 'line 1 1 1 1 'tags: 'rod 'width: 3 'fill: 'black) (canvas 'create 'oval 1 1 2 2 'tags: 'bob 'outline: 'black 'fill: 'yellow)   ;; get everything started (show-pendulum canvas) (tk/after 500 animate) (tk-event-loop tk)))  
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.
#Mercury
Mercury
:- module amb. :- interface. :- import_module io. :- pred main(io::di, io::uo) is cc_multi. :- implementation. :- import_module list, string, char, int.   main(!IO) :- ( solution(S) -> io.write_string(S, !IO), io.nl(!IO)  ; io.write_string("No solutions found :-(\n", !IO) ).   :- pred solution(string::out) is nondet. solution(S) :- member(A, ["the", "that", "a"]), member(N, ["frog", "elephant", "thing"]), member(V, ["walked", "treaded", "grows"]), member(E, ["slowly", "quickly"]), S = join_list(" ", [A, N, V, E]), rule1(A, N), rule1(N, V), rule1(V, E).   :- pred rule1(string::in, string::in) is semidet. rule1(A, B) :- last_char(A) = C, first_char(B, C, _).   :- func last_char(string::in) = (char::out) is semidet. last_char(S) = C :- index(S, length(S) - 1, C).
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.
#ERRE
ERRE
PROGRAM ACCUMULATOR   PROCEDURE ACCUMULATOR(SUM,N,A->SUM) IF NOT A THEN SUM=N ELSE SUM=SUM+N END PROCEDURE   BEGIN PRINT(CHR$(12);) ! CLS ACCUMULATOR(X,1,FALSE->X)  ! INIT FIRST ACCUMULATOR ACCUMULATOR(X,-15,TRUE->X) ACCUMULATOR(X,2.3,TRUE->X)   ACCUMULATOR(Z,3,FALSE->Z)  ! INIT SECOND ACCUMULATOR ACCUMULATOR(Z,5,TRUE->Z) ACCUMULATOR(Z,2.3,TRUE->Z) PRINT(X,Z) END PROGRAM
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.
#F.23
F#
// dynamically typed add let add (x: obj) (y: obj) = match x, y with | (:? int as m), (:? int as n) -> box(m+n) | (:? int as n), (:? float as x) | (:? float as x), (:? int as n) -> box(x + float n) | (:? float as x), (:? float as y) -> box(x + y) | _ -> failwith "Run-time type error"   let acc init = let state = ref (box init) fun y -> state := add !state (box y) !state   do let x : obj -> obj = acc 1 printfn "%A" (x 5) // prints "6" acc 3 |> ignore printfn "%A" (x 2.3) // prints "8.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.
#Agda
Agda
  open import Data.Nat open import Data.Nat.Show open import IO   module Ackermann where   ack : ℕ -> ℕ -> ℕ ack zero n = n + 1 ack (suc m) zero = ack m 1 ack (suc m) (suc n) = ack m (ack (suc m) n)   main = run (putStrLn (show (ack 3 9)))  
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
#BASIC
BASIC
10 DEFINT A-Z: LM=20000 20 DIM P(LM) 30 FOR I=1 TO LM: P(I)=-32767: NEXT 40 FOR I=1 TO LM/2: FOR J=I+I TO LM STEP I: P(J)=P(J)+I: NEXT: NEXT 50 FOR I=1 TO LM 60 X=I-32767 70 IF P(I)<X THEN D=D+1 ELSE IF P(I)=X THEN P=P+1 ELSE A=A+1 80 NEXT 90 PRINT "DEFICIENT:";D 100 PRINT "PERFECT:";P 110 PRINT "ABUNDANT:";A
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
#BQN
BQN
Split ← (⊢-˜+`׬)∘=⊔⊢ PadRow ← { w‿t𝕊𝕩: # t → type. # 0 → left # 1 → right # 2 → center pstyle←t⊑⟨{0‿𝕩},{𝕩‿0},{⟨⌊𝕩÷2,⌈𝕩÷2⟩}⟩ 𝕩{(⊣∾𝕨∾⊢)´(Pstyle 𝕩)/¨<w}¨(⌈´-⊢)≠¨𝕩 } Align ← {{𝕨∾' '∾𝕩}´˘⍉" "‿𝕨⊸PadRow˘⍉>⟨""⟩‿0 PadRow '$' Split¨(@+10) Split 𝕩}   1 Align text
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.
#Lingo
Lingo
property _sum property _func property _timeLast property _valueLast property _ms0 property _updateTimer   on new (me, func) if voidP(func) then func = "0.0" me._sum = 0.0 -- update frequency: 100/sec (arbitrary) me._updateTimer = timeout().new("update", 10, #_update, me) me.input(func) return me end   on stop (me) me._updateTimer.period = 0 -- deactivates timer end   -- func is a term (as string) that might contain "t" and is evaluated at runtime on input (me, func) me._func = func me._ms0 = _system.milliseconds me._timeLast = 0.0 t = 0.0 me._valueLast = value(me._func) end   on output (me) return me._sum end   on _update (me) now = _system.milliseconds - me._ms0 t = now/1000.0 val = value(me._func) me._sum = me._sum + (me._valueLast+val)*(t - me._timeLast)/2 me._timeLast = t me._valueLast = val end
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.
#Lua
Lua
local seconds = os.clock   local integrator = { new = function(self, fn) return setmetatable({fn=fn,t0=seconds(),v0=0,sum=0,nup=0},self) end, update = function(self) self.t1 = seconds() self.v1 = self.fn(self.t1) self.sum = self.sum + (self.v0 + self.v1) * (self.t1 - self.t0) / 2 self.t0, self.v0, self.nup = self.t1, self.v1, self.nup+1 end, input = function(self, fn) self.fn = fn end, output = function(self) return self.sum end, } integrator.__index = integrator   -- "fake multithreaded sleep()" -- waits for "duration" seconds calling "f" at every "interval" seconds local function sample(duration, interval, f) local now = seconds() local untilwhen, nextinterval = now+duration, now+interval f() repeat if seconds() >= nextinterval then f() nextinterval=nextinterval+interval end until seconds() >= untilwhen end   local pi, sin = math.pi, math.sin local ks = function(t) return sin(2.0*pi*0.5*t) end local kz = function(t) return 0 end local intervals = { 0.5, 0.25, 0.1, 0.05, 0.025, 0.01, 0.005, 0.0025, 0.001 } for _,interval in ipairs(intervals) do local i = integrator:new(ks) sample(2.0, interval, function() i:update() end) i:input(kz) sample(0.5, interval, function() i:update() end) print(string.format("sampling interval: %f, %5d updates over 2.5s total = %.15f", interval, i.nup, i:output())) end
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
#Phix
Phix
function aliquot(atom n) sequence s = {n} integer k if n=0 then return {"terminating",{0}} end if while length(s)<16 and n<140737488355328 do n = sum(factors(n,-1)) k = find(n,s) if k then if k=1 then if length(s)=1 then return {"perfect",s} elsif length(s)=2 then return {"amicable",s} end if return {"sociable",s} elsif k=length(s) then return {"aspiring",s} end if return {"cyclic",append(s,n)} elsif n=0 then return {"terminating",s} end if s = append(s,n) end while return {"non-terminating",s} end function constant n = tagset(12)&{28, 496, 220, 1184, 12496, 1264460, 790, 909, 562, 1064, 1488, 15355717786080} for i=1 to length(n) do {string classification, sequence dseq} = aliquot(n[i]) dseq = join(apply(true,sprintf,{{"%d"},dseq}),",") printf(1,"%14d => %15s, {%s}\n",{n[i],classification,dseq}) end for
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.
#Java
Java
public class AksTest { private static final long[] c = new long[64];   public static void main(String[] args) { for (int n = 0; n < 10; n++) { coeff(n); show(n); }   System.out.print("Primes:"); for (int n = 1; n < c.length; n++) if (isPrime(n)) System.out.printf(" %d", n);   System.out.println(); }   static void coeff(int n) { c[0] = 1; for (int i = 0; i < n; c[0] = -c[0], i++) { c[1 + i] = 1; for (int j = i; j > 0; j--) c[j] = c[j - 1] - c[j]; } }   static boolean isPrime(int n) { coeff(n); c[0]++; c[n]--;   int i = n; while (i-- != 0 && c[i] % n == 0) continue; return i < 0; }   static void show(int n) { System.out.print("(x-1)^" + n + " ="); for (int i = n; i >= 0; i--) { System.out.print(" + " + c[i] + "x^" + i); } System.out.println(); } }
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.
#Polyglot:PL.2FI_and_PL.2FM
Polyglot:PL/I and PL/M
/* FIND ADDITIVE PRIMES - PRIMES WHOSE DIGIT SUM IS ALSO PRIME */ additive_primes_100H: procedure options (main);   /* PROGRAM-SPECIFIC %REPLACE STATEMENTS MUST APPEAR BEFORE THE %INCLUDE AS */ /* E.G. THE CP/M PL/I COMPILER DOESN'T LIKE THEM TO FOLLOW PROCEDURES */ /* PL/I */  %replace dclsieve by 500; /* PL/M */ /* DECLARE DCLSIEVE LITERALLY '501'; /* */   /* PL/I DEFINITIONS */ %include 'pg.inc'; /* PL/M DEFINITIONS: CP/M BDOS SYSTEM CALL AND CONSOLE I/O ROUTINES, ETC. */ /* DECLARE BINARY LITERALLY 'ADDRESS', CHARACTER LITERALLY 'BYTE'; DECLARE FIXED LITERALLY ' ', BIT LITERALLY 'BYTE'; DECLARE STATIC LITERALLY ' ', RETURNS LITERALLY ' '; DECLARE FALSE LITERALLY '0', TRUE LITERALLY '1'; DECLARE HBOUND LITERALLY 'LAST', SADDR LITERALLY '.'; BDOSF: PROCEDURE( FN, ARG )BYTE; DECLARE FN BYTE, ARG ADDRESS; GOTO 5; END; BDOS: PROCEDURE( FN, ARG ); DECLARE FN BYTE, ARG ADDRESS; GOTO 5; END; PRCHAR: PROCEDURE( C ); DECLARE C BYTE; CALL BDOS( 2, C ); END; PRSTRING: PROCEDURE( S ); DECLARE S ADDRESS; CALL BDOS( 9, S ); END; PRNL: PROCEDURE; CALL PRCHAR( 0DH ); CALL PRCHAR( 0AH ); END; PRNUMBER: PROCEDURE( N ); DECLARE N ADDRESS; DECLARE V ADDRESS, N$STR( 6 ) BYTE, W BYTE; N$STR( W := LAST( N$STR ) ) = '$'; N$STR( W := W - 1 ) = '0' + ( ( V := N ) MOD 10 ); DO WHILE( ( V := V / 10 ) > 0 ); N$STR( W := W - 1 ) = '0' + ( V MOD 10 ); END; CALL BDOS( 9, .N$STR( W ) ); END PRNUMBER; MODF: PROCEDURE( A, B )ADDRESS; DECLARE ( A, B ) ADDRESS; RETURN A MOD B; END MODF; /* END LANGUAGE DEFINITIONS */   /* TASK */   /* PRIME ELEMENTS ARE 0, 1, ... 500 IN PL/M AND 1, 2, ... 500 IN PL/I */ /* ELEMENT 0 IN PL/M IS IS UNUSED */ DECLARE PRIME( DCLSIEVE ) BIT; DECLARE ( MAXPRIME, MAXROOT, ACOUNT, I, J, DSUM, V ) FIXED BINARY; /* SIEVE THE PRIMES UP TO MAX PRIME */ PRIME( 1 ) = FALSE; PRIME( 2 ) = TRUE; MAXPRIME = HBOUND( PRIME , 1 ); MAXROOT = 1; /* FIND THE ROOT OF MAXPRIME TO AVOID 16-BIT OVERFLOW */ DO WHILE( MAXROOT * MAXROOT < MAXPRIME ); MAXROOT = MAXROOT + 1; END; DO I = 3 TO MAXPRIME BY 2; PRIME( I ) = TRUE; END; DO I = 4 TO MAXPRIME BY 2; PRIME( I ) = FALSE; END; DO I = 3 TO MAXROOT BY 2; IF PRIME( I ) THEN DO; DO J = I * I TO MAXPRIME BY I; PRIME( J ) = FALSE; END; END; END; /* FIND THE PRIMES THAT ARE ADDITIVE PRIMES */ ACOUNT = 0; DO I = 1 TO MAXPRIME; IF PRIME( I ) THEN DO; V = I; DSUM = 0; DO WHILE( V > 0 ); DSUM = DSUM + MODF( V, 10 ); V = V / 10; END; IF PRIME( DSUM ) THEN DO; CALL PRCHAR( ' ' ); IF I < 10 THEN CALL PRCHAR( ' ' ); IF I < 100 THEN CALL PRCHAR( ' ' ); CALL PRNUMBER( I ); ACOUNT = ACOUNT + 1; IF MODF( ACOUNT, 12 ) = 0 THEN CALL PRNL; END; END; END; CALL PRNL; CALL PRSTRING( SADDR( 'FOUND $' ) ); CALL PRNUMBER( ACOUNT ); CALL PRSTRING( SADDR( ' ADDITIVE PRIMES BELOW $' ) ); CALL PRNUMBER( MAXPRIME ); CALL PRNL;   EOF: end additive_primes_100H;
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
#Pascal
Pascal
program AlmostPrime; {$IFDEF FPC} {$Mode Delphi} {$ENDIF} uses primtrial; var i,K,cnt : longWord; BEGIN K := 1; repeat cnt := 0; i := 2; write('K=',K:2,':'); repeat if isAlmostPrime(i,K) then Begin write(i:6,' '); inc(cnt); end; inc(i); until cnt = 9; writeln; inc(k); until k > 10; 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
#Fortran
Fortran
!*************************************************************************************** module anagram_routines !*************************************************************************************** implicit none   !the dictionary file: integer,parameter :: file_unit = 1000 character(len=*),parameter :: filename = 'unixdict.txt'   !maximum number of characters in a word: integer,parameter :: max_chars = 50   !maximum number of characters in the string displaying the anagram lists: integer,parameter :: str_len = 256   type word character(len=max_chars) :: str = repeat(' ',max_chars) !the word from the dictionary integer :: n = 0 !length of this word integer :: n_anagrams = 0 !number of anagrams found logical :: checked = .false. !if this one has already been checked character(len=str_len) :: anagrams = repeat(' ',str_len) !the anagram list for this word end type word   !the dictionary structure: type(word),dimension(:),allocatable,target :: dict   contains !***************************************************************************************   !****************************************************************************** function count_lines_in_file(fid) result(n_lines) !****************************************************************************** implicit none   integer :: n_lines integer,intent(in) :: fid character(len=1) :: tmp integer :: i integer :: ios   !the file is assumed to be open already.   rewind(fid) !rewind to beginning of the file   n_lines = 0 do !read each line until the end of the file. read(fid,'(A1)',iostat=ios) tmp if (ios < 0) exit !End of file n_lines = n_lines + 1 !row counter end do   rewind(fid) !rewind to beginning of the file   !****************************************************************************** end function count_lines_in_file !******************************************************************************   !****************************************************************************** pure elemental function is_anagram(x,y) !****************************************************************************** implicit none character(len=*),intent(in) :: x character(len=*),intent(in) :: y logical :: is_anagram   character(len=len(x)) :: x_tmp !a copy of x integer :: i,j   !a character not found in any word: character(len=1),parameter :: null = achar(0)   !x and y are assumed to be the same size.   x_tmp = x do i=1,len_trim(x) j = index(x_tmp, y(i:i)) !look for this character in x_tmp if (j/=0) then x_tmp(j:j) = null !clear it so it won't be checked again else is_anagram = .false. !character not found: x,y are not anagrams return end if end do   !if we got to this point, all the characters ! were the same, so x,y are anagrams: is_anagram = .true.   !****************************************************************************** end function is_anagram !******************************************************************************   !*************************************************************************************** end module anagram_routines !***************************************************************************************   !*************************************************************************************** program main !*************************************************************************************** use anagram_routines implicit none   integer :: n,i,j,n_max type(word),pointer :: x,y logical :: first_word real :: start, finish   call cpu_time(start) !..start timer   !open the dictionary and read in all the words: open(unit=file_unit,file=filename) !open the file n = count_lines_in_file(file_unit) !count lines in the file allocate(dict(n)) !allocate dictionary structure do i=1,n ! read(file_unit,'(A)') dict(i)%str !each line is a word in the dictionary dict(i)%n = len_trim(dict(i)%str) !saving length here to avoid trim's below end do close(file_unit) !close the file   !search dictionary for anagrams: do i=1,n   x => dict(i) !pointer to simplify code first_word = .true. !initialize   do j=i,n   y => dict(j) !pointer to simplify code   !checks to avoid checking words unnecessarily: if (x%checked .or. y%checked) cycle !both must not have been checked already if (x%n/=y%n) cycle !must be the same size if (x%str(1:x%n)==y%str(1:y%n)) cycle !can't be the same word   ! check to see if x,y are anagrams: if (is_anagram(x%str(1:x%n), y%str(1:y%n))) then !they are anagrams. y%checked = .true. !don't check this one again. x%n_anagrams = x%n_anagrams + 1 if (first_word) then !this is the first anagram found for this word. first_word = .false. x%n_anagrams = x%n_anagrams + 1 x%anagrams = trim(x%anagrams)//x%str(1:x%n) !add first word to list end if x%anagrams = trim(x%anagrams)//','//y%str(1:y%n) !add next word to list end if   end do x%checked = .true. !don't check this one again   end do   !anagram groups with the most words: write(*,*) '' n_max = maxval(dict%n_anagrams) do i=1,n if (dict(i)%n_anagrams==n_max) write(*,'(A)') trim(dict(i)%anagrams) end do   !anagram group containing longest words: write(*,*) '' n_max = maxval(dict%n, mask=dict%n_anagrams>0) do i=1,n if (dict(i)%n_anagrams>0 .and. dict(i)%n==n_max) write(*,'(A)') trim(dict(i)%anagrams) end do write(*,*) ''   call cpu_time(finish) !...stop timer write(*,'(A,F6.3,A)') '[Runtime = ',finish-start,' sec]' write(*,*) ''   !*************************************************************************************** end program main !***************************************************************************************
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
#VBA
VBA
Private Function tx(a As Variant) As String Dim s As String s = CStr(Format(a, "0.######")) If Right(s, 1) = "," Then s = Mid(s, 1, Len(s) - 1) & " " Else i = InStr(1, s, ",") s = s & String$(6 - Len(s) + i, " ") End If tx = s End Function Private Sub test(b1 As Variant, b2 As Variant) Dim diff As Variant diff = (b2 - b1) - ((b2 - b1) \ 360) * 360 diff = diff - IIf(diff > 180, 360, 0) diff = diff + IIf(diff < -180, 360, 0) Debug.Print Format(tx(b1), "@@@@@@@@@@@@@@@@"); Format(tx(b2), "@@@@@@@@@@@@@@@@@"); Format(tx(diff), "@@@@@@@@@@@@@@@@@") End Sub Public Sub angle_difference() Debug.Print " b1 b2 diff" Debug.Print "---------------- ---------------- ----------------" test 20, 45 test -45, 45 test -85, 90 test -95, 90 test -45, 125 test -45, 145 test 29.4803, -88.6381 test -78.3251, -159.036 test -70099.7423381094, 29840.6743787672 test -165313.666629736, 33693.9894517456 test 1174.83805105985, -154146.664901248 test 60175.7730679555, 42213.0719235437 End Sub
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
#UNIX_Shell
UNIX Shell
function get_words { typeset host=www.puzzlers.org typeset page=/pub/wordlists/unixdict.txt exec 7<>/dev/tcp/$host/80 print -e -u7 "GET $page HTTP/1.1\r\nhost: $host\r\nConnection: close\r\n\r\n" # remove the http header and save the word list sed 's/\r$//; 1,/^$/d' <&7 >"$1" exec 7<&- }   function is_deranged { typeset -i i for ((i=0; i<${#1}; i++)); do [[ ${1:i:1} == ${2:i:1} ]] && return 1 done return 0 }   function word2key { typeset -a chars=( $( for ((i=0; i<${#word}; i++)); do echo "${word:i:1}" done | sort ) ) typeset IFS="" echo "${chars[*]}" }   [[ -f word.list ]] || get_words word.list   typeset -A words typeset -i max=0   while IFS= read -r word; do key=$(word2key $word) if [[ -z "${words["$key"]}" ]]; then words["$key"]=$word else if (( ${#word} > max )); then if is_deranged "${words["$key"]}" "$word"; then max_deranged=("${words["$key"]}" "$word") max=${#word} fi fi fi done <word.list echo $max - ${max_deranged[@]}
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.
#Quackery
Quackery
[ dup 0 < iff $ "negative argument passed to fibonacci" fail [ dup 2 < if done dup 1 - recurse swap 2 - recurse + ] ] is fibonacci ( n --> 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.
#PL.2FM
PL/M
100H: /* CP/M CALLS */ BDOS: PROCEDURE (FN, ARG); DECLARE FN BYTE, ARG ADDRESS; GO TO 5; END BDOS; EXIT: PROCEDURE; CALL BDOS(0,0); END EXIT; PRINT: PROCEDURE (S); DECLARE S ADDRESS; CALL BDOS(9,S); END PRINT;   /* PRINT A NUMBER */ PRINT$NUMBER: PROCEDURE (N); DECLARE S (6) BYTE INITIAL ('.....$'); DECLARE (N, P) ADDRESS, C BASED P BYTE; P = .S(5); DIGIT: P = P - 1; C = N MOD 10 + '0'; N = N / 10; IF N > 0 THEN GO TO DIGIT; CALL PRINT(P); END PRINT$NUMBER;   /* CALCULATE SUMS OF PROPER DIVISORS */ DECLARE DIV$SUM (20$001) ADDRESS; DECLARE (I, J) ADDRESS;   DO I=2 TO 20$000; DIV$SUM(I) = 1; END; DO I=2 TO 10$000; DO J = I*2 TO 20$000 BY I; DIV$SUM(J) = DIV$SUM(J) + I; END; END;   /* TEST EACH PAIR */ DO I=2 TO 20$000; DO J=I+1 TO 20$000; IF DIV$SUM(I)=J AND DIV$SUM(J)=I THEN DO; CALL PRINT$NUMBER(I); CALL PRINT(.', $'); CALL PRINT$NUMBER(J); CALL PRINT(.(13,10,'$')); END; END; END;   CALL EXIT; EOF
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.
#Scilab
Scilab
//Input variables (Assumptions: massless pivot, no energy loss) bob_mass=10; g=-9.81; L=2; theta0=-%pi/6; v0=0; t0=0;   //No. of steps steps=300;   //Setting deltaT or duration (comment either of the lines below) //deltaT=0.1; t_max=t0+deltaT*steps; t_max=5; deltaT=(t_max-t0)/steps;   if t_max<=t0 then error("Check duration (t0 and t_f), number of steps and deltaT."); end   //Initial position not_a_pendulum=%F; t=zeros(1,steps); t(1)=t0; //time theta=zeros(1,steps); theta(1)=theta0; //angle F=zeros(1,steps); F(1)=bob_mass*g*sin(theta0); //force A=zeros(1,steps); A(1)=F(1)/bob_mass; //acceleration V=zeros(1,steps); V(1)=v0; //linear speed W=zeros(1,steps); W(1)=v0/L; //angular speed   for i=2:steps t(i)=t(i-1)+deltaT; V(i)=A(i-1)*deltaT+V(i-1); W(i)=V(i)/L; theta(i)=theta(i-1)+W(i)*deltaT; F(i)=bob_mass*g*sin(theta(i)); A(i)=F(i)/bob_mass; if (abs(theta(i))>=%pi | (abs(theta(i))==0 & V(i)==0)) & ~not_a_pendulum then disp("Initial conditions do not describe a pendulum."); not_a_pendulum = %T; end end clear i   //Ploting the pendulum bob_r=0.08*L; bob_shape=bob_r*exp(%i.*linspace(0,360,20)/180*%pi);   bob_pos=zeros(20,steps); rod_pos=zeros(1,steps); for i=1:steps rod_pos(i)=L*exp(%i*(-%pi/2+theta(i))); bob_pos(:,i)=bob_shape'+rod_pos(i); end clear i   scf(0); clf(); xname("Simple gravity pendulum"); plot2d(real([0 rod_pos(1)]),imag([0 rod_pos(1)])); axes=gca(); axes.isoview="on"; axes.children(1).children.mark_style=3; axes.children(1).children.mark_size=1; axes.children(1).children.thickness=3;   plot2d(real(bob_pos(:,1)),imag(bob_pos(:,1))); axes=gca(); axes.children(1).children.fill_mode="on"; axes.children(1).children.foreground=2; axes.children(1).children.background=2;   if max(imag(bob_pos))>0 then axes.data_bounds=[-L-bob_r,-L-1.01*bob_r;L+bob_r,max(imag(bob_pos))]; else axes.data_bounds=[-L-bob_r,-L-1.01*bob_r;L+bob_r,bob_r]; end       //Animating the plot disp("Duration: "+string(max(t)+deltaT-t0)+"s."); sleep(850); for i=2:steps axes.children(1).children.data=[real(bob_pos(:,i)), imag(bob_pos(:,i))]; axes.children(2).children.data=[0, 0; real(rod_pos(i)), imag(rod_pos(i))]; sleep(deltaT*1000) end clear i
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.
#NetRexx
NetRexx
/* REXX ************************************************************** * 25.08.2013 Walter Pachl derived from REXX version 2 *********************************************************************/ w='' l=0 mm=0 mkset(1,'the that a if',w,mm,l) mkset(2,'frog elephant thing',w,mm,l) mkset(3,'walked treaded grows trots',w,mm,l) mkset(4,'slowly quickly',w,mm,l) show(w,mm,l)   Loop i=1 to 3 /* loop over sets */ k=i+1 /* the following set */ Loop ii=1 To 10 /* loop over elements in set k*/ If w[i,ii].words=i Then Do /* a sentence part found */ Loop jj=1 To 10 /* loop over following words */ If w[i,ii].right(1)=w[k,jj].left(1) Then Do /* fitting */ ns=w[i,ii]' 'w[k,jj] /* build new sentence (part) */ If ns.words=k Then /* 'complete' part */ add(w,k,ns) /* add to set k */ End End End End End Say 'Results:' Loop jj=1 To 10 /* show the results */ If w[4,jj].words=4 Then Say '-->' w[4,jj] End   method add(w,k,s) public static /********************************************************************* * add a fitting sentence (part) s to set w[k,*] *********************************************************************/ Loop i=1 To 10 While w[k,i]>'' /* look for an empty slot */ End w[k,i]=s /* add the sentence (part) */ Return   method mkset(n,arg,smp,mm,l) public static /********************************************************************* * create set smp[n,*] from data in arg * mm[0] maximum number of elements in any set * l[n] maximum word length in set n *********************************************************************/ loop i = 1 to arg.words smp[n,i] = arg.word(i) If smp[n,i].length>l[n] Then l[n]=smp[n,i].length end if i-1>mm[0] Then Do mm[0]=i-1 End return   method show(w,mm,l) public static /********************************************************************* * show the input *********************************************************************/ Say 'Input:' Loop j=1 To mm[0] /* output lines */ ol='' Loop i=1 To 4 ol=ol w[i,j].left(l[i]) End Say ol.strip End; say '' Return
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.
#Factor
Factor
USE: locals :: accumulator ( n! -- quot ) [ n + dup n! ] ;   1 accumulator [ 5 swap call drop ] [ drop 3 accumulator drop ] [ 2.3 swap call ] tri .
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.
#Fantom
Fantom
class AccumulatorFactory { static |Num -> Num| accumulator (Num sum) { return |Num a -> Num| { // switch on type of sum if (sum is Int) { // and then type of a if (a is Int) return sum = sum->plus(a) else if (a is Float) return sum = sum->plusFloat(a) else return sum = sum->plusDecimal(a) } else if (sum is Float) { if (a is Int) return sum = sum->plusInt(a) else if (a is Float) return sum = sum->plus(a) else return sum = sum->plusDecimal(a) } else // if (sum is Decimal) { if (a is Int) return sum = sum->plusInt(a) else if (a is Float) return sum = sum->plusFloat(a) else return sum = sum->plus(a) } } }   public static Void main () { x := accumulator (3.1) y := accumulator (3f) echo (x(5)) // the Decimal sum combines with an Int echo (x(2)) echo (y(5.1)) // the Float sum combines with a Decimal   x = accumulator (1) x (5) accumulator (3) echo (x(2.3)) // the Int sum is now a Decimal } }
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.
#ALGOL_60
ALGOL 60
begin integer procedure ackermann(m,n);value m,n;integer m,n; ackermann:=if m=0 then n+1 else if n=0 then ackermann(m-1,1) else ackermann(m-1,ackermann(m,n-1)); integer m,n; for m:=0 step 1 until 3 do begin for n:=0 step 1 until 6 do outinteger(1,ackermann(m,n)); outstring(1,"\n") end end
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
#BCPL
BCPL
get "libhdr" manifest $( maximum = 20000 $)   let calcpdivs(p, max) be $( for i=0 to max do p!i := 0 for i=1 to max/2 $( let j = i+i while 0 < j <= max $( p!j := p!j + i j := j + i $) $) $)   let classify(p, n, def, per, ab) be $( let z = 0<=p!n<n -> def, p!n=n -> per, ab  !z := !z + 1 $)   let start() be $( let p = getvec(maximum) let def, per, ab = 0, 0, 0   calcpdivs(p, maximum) for i=1 to maximum do classify(p, i, @def, @per, @ab)   writef("Deficient numbers: %N*N", def) writef("Perfect numbers: %N*N", per) writef("Abundant numbers: %N*N", ab) freevec(p) $)
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
#C
C
using System; class ColumnAlignerProgram { delegate string Justification(string s, int width);   static string[] AlignColumns(string[] lines, Justification justification) { const char Separator = '$'; // build input table and calculate columns count string[][] table = new string[lines.Length][]; int columns = 0; for (int i = 0; i < lines.Length; i++) { string[] row = lines[i].TrimEnd(Separator).Split(Separator); if (columns < row.Length) columns = row.Length; table[i] = row; } // create formatted table string[][] formattedTable = new string[table.Length][]; for (int i = 0; i < formattedTable.Length; i++) { formattedTable[i] = new string[columns]; } for (int j = 0; j < columns; j++) { // get max column width int columnWidth = 0; for (int i = 0; i < table.Length; i++) { if (j < table[i].Length && columnWidth < table[i][j].Length) columnWidth = table[i][j].Length; } // justify column cells for (int i = 0; i < formattedTable.Length; i++) { if (j < table[i].Length) formattedTable[i][j] = justification(table[i][j], columnWidth); else formattedTable[i][j] = new String(' ', columnWidth); } } // create result string[] result = new string[formattedTable.Length]; for (int i = 0; i < result.Length; i++) { result[i] = String.Join(" ", formattedTable[i]); } return result; }   static string JustifyLeft(string s, int width) { return s.PadRight(width); } static string JustifyRight(string s, int width) { return s.PadLeft(width); } static string JustifyCenter(string s, int width) { return s.PadLeft((width + s.Length) / 2).PadRight(width); }   static void Main() { string[] input = { "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.", };   foreach (string line in AlignColumns(input, JustifyCenter)) { Console.WriteLine(line); } } }
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.
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
Block[{start = SessionTime[], K, t0 = 0, t1, kt0, S = 0}, K[t_] = Sin[2 Pi f t] /. f -> 0.5; kt0 = K[t0]; While[True, t1 = SessionTime[] - start; S += (kt0 + (kt0 = K[t1])) (t1 - t0)/2; t0 = t1; If[t1 > 2, K[t_] = 0; If[t1 > 2.5, Break[]]]]; 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.
#Nim
Nim
  # Active object. # Compile with "nim c --threads:on".   import locks import os import std/monotimes   type   # Function to use for integration. TimeFunction = proc (t: float): float {.gcsafe.}   # Integrator object. Integrator = ptr TIntegrator TIntegrator = object k: TimeFunction # The function to integrate. dt: int # Time interval in milliseconds. thread: Thread[Integrator] # Thread which does the computation. s: float # Computed value. lock: Lock # Lock to manage concurrent accesses. isRunning: bool # True if integrator is running.   #---------------------------------------------------------------------------------------------------   proc newIntegrator(f: TimeFunction; dt: int): Integrator = ## Create an integrator.   result = cast[Integrator](allocShared(sizeof(TIntegrator))) result.k = f result.dt = dt result.s = 0 result.lock.initLock() result.isRunning = false   #---------------------------------------------------------------------------------------------------   proc process(integrator: Integrator) {.thread, gcsafe.} = ## Do the integration.   integrator.isRunning = true let start = getMonotime().ticks var t0: float = 0 var k0 = integrator.k(0) while true: sleep(integrator.dt) withLock integrator.lock: if not integrator.isRunning: break let t1 = float(getMonoTime().ticks - start) / 1e9 let k1 = integrator.k(t1) integrator.s += (k1 + k0) * (t1 - t0) / 2 t0 = t1 k0 = k1   #---------------------------------------------------------------------------------------------------   proc start(integrator: Integrator) = ## Start the integrator by launching a thread to do the computation. integrator.thread.createThread(process, integrator)   #---------------------------------------------------------------------------------------------------   proc stop(integrator: Integrator) = ## Stop the integrator.   withLock integrator.lock: integrator.isRunning = false integrator.thread.joinThread()   #---------------------------------------------------------------------------------------------------   proc setInput(integrator: Integrator; f: TimeFunction) = ## Set the function. withLock integrator.lock: integrator.k = f   #---------------------------------------------------------------------------------------------------   proc output(integrator: Integrator): float = ## Return the current output. withLock integrator.lock: result = integrator.s   #---------------------------------------------------------------------------------------------------   proc destroy(integrator: Integrator) = ## Destroy an integrator, freing the resources.   if integrator.isRunning: integrator.stop() integrator.lock.deinitLock() integrator.deallocShared()   #---------------------------------------------------------------------------------------------------   from math import PI, sin   # Create the integrator and start it. let integrator = newIntegrator(proc (t: float): float {.gcsafe.} = sin(PI * t), 1) integrator.start() echo "Integrator started." sleep(2000) echo "Value after 2 seconds: ", integrator.output()   # Change the function to use. integrator.setInput(proc (t: float): float {.gcsafe.} = 0) echo "K function changed." sleep(500)   # Stop the integrator and display the computed value. integrator.stop() echo "Value after 0.5 more second: ", integrator.output() integrator.destroy()  
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
#Picat
Picat
divisor_sum(N) = R => Total = 1, Power = 2,  % Deal with powers of 2 first while (N mod 2 == 0) Total := Total + Power, Power := Power*2, N := N div 2 end,  % Odd prime factors up to the square root P = 3, while (P*P =< N) Sum = 1, Power1 = P, while (N mod P == 0) Sum := Sum + Power1, Power1 := Power1*P, N := N div P end, Total := Total * Sum, P := P+2 end,  % If n > 1 then it's prime if N > 1 then Total := Total*(N + 1) end, R = Total.   % See https://en.wikipedia.org/wiki/Aliquot_sequence aliquot_sequence(N,Limit,Seq,Class) => aliquot_sequence(N,Limit,[N],Seq,Class).   aliquot_sequence(_,0,_,Seq,Class) => Seq = [], Class = 'non-terminating'. aliquot_sequence(_,_,[0|_],Seq,Class) => Seq = [0], Class = terminating. aliquot_sequence(N,_,[N,N|_],Seq,Class) => Seq = [], Class = perfect. aliquot_sequence(N,_,[N,_,N|_],Seq,Class) => Seq = [N], Class = amicable. aliquot_sequence(N,_,[N|S],Seq,Class), membchk(N,S) => Seq = [N], Class = sociable. aliquot_sequence(_,_,[Term,Term|_],Seq,Class) => Seq = [], Class = aspiring. aliquot_sequence(_,_,[Term|S],Seq,Class), membchk(Term,S) => Seq = [Term], Class = cyclic. aliquot_sequence(N,Limit,[Term|S],Seq,Class) => Seq = [Term|Rest], Sum = divisor_sum(Term), Term1 is Sum - Term, aliquot_sequence(N,Limit-1,[Term1,Term|S],Rest,Class).   main => foreach (N in [11,12,28,496,220,1184,12496,1264460,790,909,562,1064,1488,15355717786080,153557177860800]) aliquot_sequence(N,16,Seq,Class), printf("%w: %w, sequence: %w ", N, Class, Seq[1]), foreach (I in 2..len(Seq), break(Seq[I] == Seq[I-1])) printf("%w ", Seq[I]) end, nl end.  
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.
#JavaScript
JavaScript
var i, p, pascal, primerow, primes, show, _i;   pascal = function() { var a; a = []; return function() { var b, i; if (a.length === 0) { return a = [1]; } else { b = (function() { var _i, _ref, _results; _results = []; for (i = _i = 0, _ref = a.length - 1; 0 <= _ref ? _i < _ref : _i > _ref; i = 0 <= _ref ? ++_i : --_i) { _results.push(a[i] + a[i + 1]); } return _results; })(); return a = [1].concat(b).concat([1]); } }; };   show = function(a) { var degree, i, sgn, show_x, str, _i, _ref; show_x = function(e) { switch (e) { case 0: return ""; case 1: return "x"; default: return "x^" + e; } }; degree = a.length - 1; str = "(x - 1)^" + degree + " ="; sgn = 1; for (i = _i = 0, _ref = a.length; 0 <= _ref ? _i < _ref : _i > _ref; i = 0 <= _ref ? ++_i : --_i) { str += ' ' + (sgn > 0 ? "+" : "-") + ' ' + a[i] + show_x(degree - i); sgn = -sgn; } return str; };   primerow = function(row) { var degree; degree = row.length - 1; return row.slice(1, degree).every(function(x) { return x % degree === 0; }); };   p = pascal();   for (i = _i = 0; _i <= 7; i = ++_i) { console.log(show(p())); }   p = pascal();   p();   p();   primes = (function() { var _j, _results; _results = []; for (i = _j = 1; _j <= 49; i = ++_j) { if (primerow(p())) { _results.push(i + 1); } } return _results; })();   console.log("");   console.log("The primes upto 50 are: " + primes);
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.
#Processing
Processing
IntList primes = new IntList();   void setup() { sieve(500); int count = 0; for (int i = 2; i < 500; i++) { if (primes.hasValue(i) && primes.hasValue(sumDigits(i))) { print(i + " "); count++; } } println(); print("Number of additive primes less than 500: " + count); }   int sumDigits(int n) { int sum = 0; for (int i = 0; i <= floor(log(n) / log(10)); i++) { sum += floor(n / pow(10, i)) % 10; } return sum; }   void sieve(int max) { for (int i = 2; i <= max; i++) { primes.append(i); } for (int i = 0; i < primes.size(); i++) { for (int j = i + 1; j < primes.size(); j++) { if (primes.get(j) % primes.get(i) == 0) { primes.remove(j); j--; } } } }
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.
#PureBasic
PureBasic
#MAX=500 Global Dim P.b(#MAX) : FillMemory(@P(),#MAX,1,#PB_Byte) If OpenConsole()=0 : End 1 : EndIf For n=2 To Sqr(#MAX)+1 : If P(n) : m=n*n : While m<=#MAX : P(m)=0 : m+n : Wend : EndIf : Next   Procedure.i qsum(v.i) While v : qs+v%10 : v/10 : Wend ProcedureReturn qs EndProcedure   For i=2 To #MAX If P(i) And P(qsum(i)) : c+1 : Print(RSet(Str(i),5)) : If c%10=0 : PrintN("") : EndIf : EndIf Next PrintN(~"\n\n"+Str(c)+" additive primes below 500.") Input()
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
#Perl
Perl
use ntheory qw/factor/; sub almost { my($k,$n) = @_; my $i = 1; map { $i++ while scalar factor($i) != $k; $i++ } 1..$n; } say "$_ : ", join(" ", almost($_,10)) for 1..5;
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
#FBSL
FBSL
#APPTYPE CONSOLE   DIM gtc = GetTickCount() Anagram() PRINT "Done in ", (GetTickCount() - gtc) / 1000, " seconds"   PAUSE   DYNC Anagram() #include <windows.h> #include <stdio.h>   char* sortedWord(const char* word, char* wbuf) { char* p1, *p2, *endwrd; char t; int swaps;   strcpy(wbuf, word); endwrd = wbuf + strlen(wbuf); do { swaps = 0; p1 = wbuf; p2 = endwrd - 1; while (p1 < p2) { if (*p2 >* p1) { t = *p2; *p2 = *p1; *p1 = t; swaps = 1; } p1++; p2--; } p1 = wbuf; p2 = p1 + 1; while (p2 < endwrd) { if (*p2 >* p1) { t = *p2; *p2 = *p1; *p1 = t; swaps = 1; } p1++; p2++; } } while (swaps); return wbuf; }   static short cxmap[] = { 0x06, 0x1f, 0x4d, 0x0c, 0x5c, 0x28, 0x5d, 0x0e, 0x09, 0x33, 0x31, 0x56, 0x52, 0x19, 0x29, 0x53, 0x32, 0x48, 0x35, 0x55, 0x5e, 0x14, 0x27, 0x24, 0x02, 0x3e, 0x18, 0x4a, 0x3f, 0x4c, 0x45, 0x30, 0x08, 0x2c, 0x1a, 0x03, 0x0b, 0x0d, 0x4f, 0x07, 0x20, 0x1d, 0x51, 0x3b, 0x11, 0x58, 0x00, 0x49, 0x15, 0x2d, 0x41, 0x17, 0x5f, 0x39, 0x16, 0x42, 0x37, 0x22, 0x1c, 0x0f, 0x43, 0x5b, 0x46, 0x4b, 0x0a, 0x26, 0x2e, 0x40, 0x12, 0x21, 0x3c, 0x36, 0x38, 0x1e, 0x01, 0x1b, 0x05, 0x4e, 0x44, 0x3d, 0x04, 0x10, 0x5a, 0x2a, 0x23, 0x34, 0x25, 0x2f, 0x2b, 0x50, 0x3a, 0x54, 0x47, 0x59, 0x13, 0x57, }; #define CXMAP_SIZE (sizeof(cxmap) / sizeof(short))   int Str_Hash(const char* key, int ix_max) { const char* cp; short mash; int hash = 33501551; for (cp = key; *cp; cp++) { mash = cxmap[*cp % CXMAP_SIZE]; hash = (hash >>4) ^ 0x5C5CF5C ^ ((hash << 1) + (mash << 5)); hash &= 0x3FFFFFFF; } return hash % ix_max; }   typedef struct sDictWord* DictWord; struct sDictWord { const char* word; DictWord next; };   typedef struct sHashEntry* HashEntry; struct sHashEntry { const char* key; HashEntry next; DictWord words; HashEntry link; short wordCount; };   #define HT_SIZE 8192   HashEntry hashTable[HT_SIZE];   HashEntry mostPerms = NULL;   int buildAnagrams(FILE* fin) { char buffer[40]; char bufr2[40]; char* hkey; int hix; HashEntry he, *hep; DictWord we; int maxPC = 2; int numWords = 0;   while (fgets(buffer, 40, fin)) { for (hkey = buffer; *hkey && (*hkey != '\n'); hkey++); *hkey = 0; hkey = sortedWord(buffer, bufr2); hix = Str_Hash(hkey, HT_SIZE); he = hashTable[hix]; hep = &hashTable[hix]; while (he && strcmp(he->key, hkey)) { hep = &he->next; he = he->next; } if (! he) { he = (HashEntry)malloc(sizeof(struct sHashEntry)); he->next = NULL; he->key = strdup(hkey); he->wordCount = 0; he->words = NULL; he->link = NULL; *hep = he; } we = (DictWord)malloc(sizeof(struct sDictWord)); we->word = strdup(buffer); we->next = he->words; he->words = we; he->wordCount++; if (maxPC < he->wordCount) { maxPC = he->wordCount; mostPerms = he; he->link = NULL; } else if (maxPC == he->wordCount) { he->link = mostPerms; mostPerms = he; } numWords++; } printf("%d words in dictionary max ana=%d\n", numWords, maxPC); return maxPC; }   void main() { HashEntry he; DictWord we; FILE* f1;   f1 = fopen("unixdict.txt", "r"); buildAnagrams(f1); fclose(f1);   f1 = fopen("anaout.txt", "w");   for (he = mostPerms; he; he = he->link) { fprintf(f1, "%d: ", he->wordCount); for (we = he->words; we; we = we->next) { fprintf(f1, "%s, ", we->word); } fprintf(f1, "\n"); } fclose(f1); } END DYNC
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
#Visual_Basic_.NET
Visual Basic .NET
Module Module1   Function Delta_Bearing(b1 As Decimal, b2 As Decimal) As Decimal Dim d As Decimal = 0   ' Convert bearing to W.C.B While b1 < 0 b1 += 360 End While While b1 > 360 b1 -= 360 End While   While b2 < 0 b2 += 360 End While While b2 > 0 b2 -= 360 End While   ' Calculate delta bearing d = (b2 - b1) Mod 360 ' Convert result to Q.B If d > 180 Then d -= 360 ElseIf d < -180 Then d += 360 End If   Return d End Function   Sub Main() ' Calculate standard test cases Console.WriteLine(Delta_Bearing(20, 45)) Console.WriteLine(Delta_Bearing(-45, 45)) Console.WriteLine(Delta_Bearing(-85, 90)) Console.WriteLine(Delta_Bearing(-95, 90)) Console.WriteLine(Delta_Bearing(-45, 125)) Console.WriteLine(Delta_Bearing(-45, 145)) Console.WriteLine(Delta_Bearing(29.4803, -88.6381)) Console.WriteLine(Delta_Bearing(-78.3251, -159.036))   ' Calculate optional test cases Console.WriteLine(Delta_Bearing(-70099.742338109383, 29840.674378767231)) Console.WriteLine(Delta_Bearing(-165313.6666297357, 33693.9894517456)) Console.WriteLine(Delta_Bearing(1174.8380510598456, -154146.66490124757)) Console.WriteLine(Delta_Bearing(60175.773067955459, 42213.071923543728)) End Sub   End Module
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
#Ursala
Ursala
#import std   anagrams = |=tK33lrDSL2SL ~=&& ==+ ~~ -<&   deranged = filter not zip; any ==   #cast %sW   main = leql$^&l deranged anagrams unixdict_dot_txt
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.
#R
R
fib2 <- function(n) { (n >= 0) || stop("bad argument") ( function(n) if (n <= 1) 1 else Recall(n-1)+Recall(n-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.
#PowerShell
PowerShell
  function Get-ProperDivisorSum ( [int]$N ) { $Sum = 1 If ( $N -gt 3 ) { $SqrtN = [math]::Sqrt( $N ) ForEach ( $Divisor1 in 2..$SqrtN ) { $Divisor2 = $N / $Divisor1 If ( $Divisor2 -is [int] ) { $Sum += $Divisor1 + $Divisor2 } } If ( $SqrtN -is [int] ) { $Sum -= $SqrtN } } return $Sum }   function Get-AmicablePairs ( $N = 300 ) { ForEach ( $X in 1..$N ) { $Sum = Get-ProperDivisorSum $X If ( $Sum -gt $X -and $X -eq ( Get-ProperDivisorSum $Sum ) ) { "$X, $Sum" } } }   Get-AmicablePairs 20000  
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.
#SequenceL
SequenceL
import <Utilities/Sequence.sl>; import <Utilities/Conversion.sl>; import <Utilities/Math.sl>;   //region Types   Point ::= (x: int(0), y: int(0)); Color ::= (red: int(0), green: int(0), blue: int(0)); Image ::= (kind: char(1), iColor: Color(0), vert1: Point(0), vert2: Point(0), vert3: Point(0), center: Point(0), radius: int(0), height: int(0), width: int(0), message: char(1), source: char(1)); Click ::= (clicked: bool(0), clPoint: Point(0)); Input ::= (iClick: Click(0), keys: char(1));   //endregion     //region Helpers====================================================================== //region Constructor-Functions------------------------------------------------- point(a(0), b(0)) := (x: a, y: b); color(r(0), g(0), b(0)) := (red: r, green: g, blue: b); segment(e1(0), e2(0), c(0)) := (kind: "segment", vert1: e1, vert2: e2, iColor: c); disc(ce(0), rad(0), c(0)) := (kind: "disc", center: ce, radius: rad, iColor: c); //endregion----------------------------------------------------------------------   //region Colors---------------------------------------------------------------- dBlack := color(0, 0, 0); dYellow := color(255, 255, 0); //endregion---------------------------------------------------------------------- //endregion=============================================================================     //=================Easel=Functions=============================================   State ::= (angle: float(0), angleVelocity: float(0), angleAccel: float(0));   initialState := (angle: pi/2, angleVelocity: 0.0, angleAccel: 0.0);   dt := 0.3; length := 450;   anchor := point(500, 750);   newState(I(0), S(0)) := let newAngle := S.angle + newAngleVelocity * dt; newAngleVelocity := S.angleVelocity + newAngleAccel * dt; newAngleAccel := -9.81 / length * sin(S.angle); in (angle: newAngle, angleVelocity: newAngleVelocity, angleAccel: newAngleAccel);   sounds(I(0), S(0)) := ["ding"] when I.iClick.clicked else [];   images(S(0)) := let pendulum := pendulumLocation(S.angle); in [segment(anchor, pendulum, dBlack), disc(pendulum, 30, dYellow), disc(anchor, 5, dBlack)];   pendulumLocation(angle) := let x := anchor.x + round(sin(angle) * length); y := anchor.y - round(cos(angle) * length); in point(x, y);   //=============End=Easel=Functions=============================================
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.
#Nim
Nim
import sugar, strutils   proc amb(comp: proc(a, b: string): bool, options: seq[seq[string]], prev: string = ""): seq[string] =   if options.len == 0: return @[]   for opt in options[0]: # If this is the base call, prev is nil and we need to continue. if prev.len != 0 and not comp(prev, opt): continue   # Take care of the case where we have no options left. if options.len == 1: return @[opt]   # Traverse into the tree. let res = amb(comp, options[1..options.high], opt)   # If it was a failure, try the next one. if res.len > 0: return opt & res # We have a match.   return @[]   const sets = @[@["the", "that", "a"], @["frog", "elephant", "thing"], @["walked", "treaded", "grows"], @["slowly", "quickly"]]   let result = amb((s, t: string) => (s[s.high] == t[0]), sets) if result.len == 0: echo "No matches found!" else: echo result.join " "
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.
#Forth
Forth
: accumulator create ( n -- ) , does> ( n -- acc+n ) tuck +! @ ;   0 accumulator foo   1 foo . \ 1 2 foo . \ 3 3 foo . \ 6
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.
#Fortran
Fortran
#define foo(type,g,nn) \ typex function g(i);\ typex i,s,n;\ data s,n/0,nn/;\ s=s+i;\ g=s+n;\ end   foo(real,x,1) foo(integer,y,3)   program acc real x, temp integer y, itemp temp = x(5.0) print *, x(2.3) itemp = y(5) print *, y(2) stop end
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.
#ALGOL_68
ALGOL 68
PROC test ackermann = VOID: BEGIN PROC ackermann = (INT m, n)INT: BEGIN IF m = 0 THEN n + 1 ELIF n = 0 THEN ackermann (m - 1, 1) ELSE ackermann (m - 1, ackermann (m, n - 1)) FI END # ackermann #;   FOR m FROM 0 TO 3 DO FOR n FROM 0 TO 6 DO print(ackermann (m, n)) OD; new line(stand out) OD END # test ackermann #; test ackermann
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
#Befunge
Befunge
p0"2":*8*>::2/\:2/\28*:*:**+>::28*:*:*/\28*:*:*%%#v_\:28*:*:*%v>00p:0`\0\`-1v ++\1-:1`#^_$:28*:*:*/\28*vv_^#<<<!%*:*:*82:-1\-1\<<<\+**:*:*82<+>*:*:**\2-!#+ v"There are "0\g00+1%*:*:<>28*:*:*/\28*:*:*/:0\`28*:*:**+-:!00g^^82!:g01\p01< >:#,_\." ,tneicifed">:#,_\." dna ,tcefrep">:#,_\.55+".srebmun tnadnuba">:#,_@
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
#C.23
C#
using System; class ColumnAlignerProgram { delegate string Justification(string s, int width);   static string[] AlignColumns(string[] lines, Justification justification) { const char Separator = '$'; // build input table and calculate columns count string[][] table = new string[lines.Length][]; int columns = 0; for (int i = 0; i < lines.Length; i++) { string[] row = lines[i].TrimEnd(Separator).Split(Separator); if (columns < row.Length) columns = row.Length; table[i] = row; } // create formatted table string[][] formattedTable = new string[table.Length][]; for (int i = 0; i < formattedTable.Length; i++) { formattedTable[i] = new string[columns]; } for (int j = 0; j < columns; j++) { // get max column width int columnWidth = 0; for (int i = 0; i < table.Length; i++) { if (j < table[i].Length && columnWidth < table[i][j].Length) columnWidth = table[i][j].Length; } // justify column cells for (int i = 0; i < formattedTable.Length; i++) { if (j < table[i].Length) formattedTable[i][j] = justification(table[i][j], columnWidth); else formattedTable[i][j] = new String(' ', columnWidth); } } // create result string[] result = new string[formattedTable.Length]; for (int i = 0; i < result.Length; i++) { result[i] = String.Join(" ", formattedTable[i]); } return result; }   static string JustifyLeft(string s, int width) { return s.PadRight(width); } static string JustifyRight(string s, int width) { return s.PadLeft(width); } static string JustifyCenter(string s, int width) { return s.PadLeft((width + s.Length) / 2).PadRight(width); }   static void Main() { string[] input = { "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.", };   foreach (string line in AlignColumns(input, JustifyCenter)) { Console.WriteLine(line); } } }
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.
#ooRexx
ooRexx
  integrater = .integrater~new(.routines~sine) -- start the integrater function call syssleep 2 integrater~input = .routines~zero -- update the integrater function call syssleep .5   say integrater~output integrater~stop -- terminate the updater thread   ::class integrater ::method init expose stopped start v last_v last_t k use strict arg k stopped = .false start = .datetime~new -- initial time stamp v = 0 last_v = 0 last_t = 0 self~input = k self~start   -- spin off a new thread and start updating. Note, this method is unguarded -- to allow other threads to make calls ::method start unguarded expose stopped   reply -- this spins this method invocation off onto a new thread   do while \stopped call sysSleep .1 self~update -- perform the update operation end   -- turn off the thread. Since this is unguarded, -- it can be called any time, any where ::method stop unguarded expose stopped stopped = .true   -- perform the update. Since this is a guarded method, the object -- start is protected. ::method update expose start v last_v t last_t k   numeric digits 20 -- give a lot of precision   current = .datetime~new t = (current - start)~microseconds new_v = k~call(t) -- call the input function v += (last_v + new_v) * (t - last_t) / 2 last_t = t last_v = new_v say new value is v   -- a write-only attribute setter (this is GUARDED) ::attribute input SET expose k last_t last_v self~update -- update current values use strict arg k -- update the call function to the provided value last_t = 0 last_v = k~call(0) -- and update to the zero value   -- the output function...returns current calculated value ::attribute output GET expose v return v   ::routine zero return 0   ::routine sine use arg t return rxcalcsin(rxcalcpi() * t)   ::requires rxmath library    
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.
#OxygenBasic
OxygenBasic
  double MainTime   '=============== class RingMaster '=============== ' indexbase 1 sys List[512] 'limit of 512 objects per ringmaster sys max,acts ' method Register(sys meth,obj) as sys sys i for i=1 to max step 2 if list[i]=0 then exit for 'vacant slot next if i>=max then max+=2 List[i]<=meth,obj return i 'token for deregistration etc end method ' method Deregister(sys *i) if i then List[i]<=0,0 : i=0 end method ' method Clear() max=0 end method ' method Act() 'called by the timer sys i,q for i=1 to max step 2 q=List[i] if q then call q List[i+1] 'anon object end if next acts++ end method ' end class     '================= class ActiveObject '================= ' double s,freq,t1,t2,v1,v2 sys nfun,acts,RingToken RingMaster *Master ' method fun0() as double end method ' method fun1() as double return sin(2*pi()*freq*MainTime) end method ' method func() as double select case nfun case 0 : return fun0() case 1 : return fun1() end select 'error? end method ' method TimeBasedDuties() t1=t2 v1=v2 t2=MainTime v2=func s=s+(v2+v1)*(t2-t1)*0.5 'add slice to integral acts++ end method ' method RegisterWith(RingMaster*r) @Master=@r if @Master then RingToken=Master.register @TimeBasedDuties,@this end if end method ' method Deregister() if @Master then Master.Deregister RingToken 'this is set to null end if end method ' method Output() as double return s end method ' method Input(double fr=0,fun=0) if fr then freq=fr nfun=fun end method   method ClearIntegral() s=0 end method ' end class     'SETUP TIMING SYSTEM '===================   extern library "kernel32.dll" declare QueryPerformanceCounter (quad*c) declare QueryPerformanceFrequency(quad*f) declare Sleep(sys milliseconds) end extern ' quad scount,tcount,freq QueryPerformanceFrequency freq double tscale=1/freq double t1,t2 QueryPerformanceCounter scount   macro PrecisionTime(time) QueryPerformanceCounter tcount time=(tcount-scount)*tscale end macro     '==== 'TEST '====   double integral double tevent1,tevent2 RingMaster Rudolpho ActiveObject A ' A.RegisterWith Rudolpho A.input (fr=0.5, fun=1) 'start with the freqency function (1) ' 'SET EVENT TIMES '===============   tEvent1=2.0 'seconds tEvent2=2.5 'seconds ' PrecisionTime t1 'mark initial time MainTime=t1 ' ' 'EVENT LOOP '========== ' do PrecisionTime t2 MainTime=t2 if t2-t1>=0.020 'seconds interval Rudolpho.Act 'service all active objects t1=t2 end if ' if tEvent1>=0 and MainTime>=tEvent1 A.input (fun=0) 'switch to null function (0) tEvent1=-1 'disable this event from happening again end if if MainTime>=tEvent2 integral=A.output() exit do 'end of session end if ' sleep 5 'hand control to OS for a while end do   print str(integral,4)   Rudolpho.clear
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
#PowerShell
PowerShell
function Get-NextAliquot ( [int]$X ) { If ( $X -gt 1 ) { $NextAliquot = 0 (1..($X/2)).Where{ $x % $_ -eq 0 }.ForEach{ $NextAliquot += $_ }.Where{ $_ } return $NextAliquot } }   function Get-AliquotSequence ( [int]$K, [int]$N ) { $X = $K $X (1..($N-1)).ForEach{ $X = Get-NextAliquot $X; $X } }   function Classify-AlliquotSequence ( [int[]]$Sequence ) { $K = $Sequence[0] $LastN = $Sequence.Count If ( $Sequence[-1] -eq 0 ) { return "terminating" } If ( $Sequence[-1] -eq 1 ) { return "terminating" } If ( $Sequence[1] -eq $K ) { return "perfect" } If ( $Sequence[2] -eq $K ) { return "amicable" } If ( $Sequence[3..($Sequence.Count-1)] -contains $K ) { return "sociable" } If ( $Sequence[-1] -eq $Sequence[-2] ) { return "aspiring" } If ( $Sequence.Count -gt ( $Sequence | Select -Unique ).Count ) { return "cyclic" } return "non-terminating and non-repeating through N = $($Sequence.Count)" }   (1..10).ForEach{ [string]$_ + " is " + ( Classify-AlliquotSequence -Sequence ( Get-AliquotSequence -K $_ -N 16 ) ) }   ( 11, 12, 28, 496, 220, 1184, 790, 909, 562, 1064, 1488 ).ForEach{ [string]$_ + " is " + ( Classify-AlliquotSequence -Sequence ( Get-AliquotSequence -K $_ -N 16 ) ) }
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.
#jq
jq
# add_pairs is a helper function for optpascal/0 # Input: an OptPascal array # Output: the next OptPascal array (obtained by adding adjacent items, # but if the last two items are unequal, then their sum is repeated) def add_pairs: if length <= 1 then . elif length == 2 then (.[0] + .[1]) as $S | if (.[0] == .[1]) then [$S] else [$S,$S] end else [.[0] + .[1]] + (.[1:]|add_pairs) end;   # Input: an OptPascal row # Output: the next OptPascalRow def next_optpascal: [1] + add_pairs;   # generate a stream of OptPascal arrays, beginning with [] def optpascals: [] | recurse(next_optpascal);   # generate a stream of Pascal arrays def pascals: # pascalize takes as input an OptPascal array and produces # the corresponding Pascal array; # if the input ends in a pair, then peel it off before reversing it. def pascalize: . + ((if .[-2] == .[-1] then .[0:-2] else .[0:-1] end) | reverse);   optpascals | pascalize;   # Input: integer n # Output: the n-th Pascal row def pascal: nth(.; pascals);   def optpascal: nth(.; optpascals);
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.
#Python
Python
def is_prime(n: int) -> bool: if n <= 3: return n > 1 if n % 2 == 0 or n % 3 == 0: return False i = 5 while i ** 2 <= n: if n % i == 0 or n % (i + 2) == 0: return False i += 6 return True   def digit_sum(n: int) -> int: sum = 0 while n > 0: sum += n % 10 n //= 10 return sum   def main() -> None: additive_primes = 0 for i in range(2, 500): if is_prime(i) and is_prime(digit_sum(i)): additive_primes += 1 print(i, end=" ") print(f"\nFound {additive_primes} additive primes less than 500")   if __name__ == "__main__": main()
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
#Phixmonti
Phixmonti
/# Rosetta Code problem: http://rosettacode.org/wiki/Almost_prime by Galileo, 06/2022 #/   include ..\Utilitys.pmt   def test tps over mod not enddef   def kprime? >ps >ps 0 ( 2 tps ) for test while tps over / int ps> drop >ps swap 1 + swap test endwhile drop endfor ps> drop ps> == enddef   5 for >ps 2 ( ) len 10 < while over tps kprime? if over 0 put endif swap 1 + swap len 10 < endwhile nip ps> drop endfor   pstack
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
#Picat
Picat
go => N = 10, Ps = primes(100).take(N), println(1=Ps), T = Ps, foreach(K in 2..5) T := mul_take(Ps,T,N), println(K=T) end, nl, foreach(K in 6..25) T := mul_take(Ps,T,N), println(K=T) end, nl.   % take first N values of L1 x L2 mul_take(L1,L2,N) = [I*J : I in L1, J in L2, I<=J].sort_remove_dups().take(N).   take(L,N) = [L[I] : I in 1..N].
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
#Factor
Factor
"resource:unixdict.txt" utf8 file-lines [ [ natural-sort >string ] keep ] { } map>assoc sort-keys [ [ first ] compare +eq+ = ] monotonic-split dup 0 [ length max ] reduce '[ length _ = ] filter [ values ] map .
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
#Vlang
Vlang
import math type Bearing = f64   const test_cases = [ [Bearing(20), 45], [Bearing(-45), 45], [Bearing(-85), 90], [Bearing(-95), 90], [Bearing(-45), 125], [Bearing(-45), 145], [Bearing(29.4803), -88.6381], [Bearing(-78.3251), -159.036], ]   fn main() { for tc in test_cases { println(tc[1].sub(tc[0])) println(angle_difference(tc[1],tc[0])) } }   fn (b2 Bearing) sub(b1 Bearing) Bearing { d := b2 - b1 match true { d < -180 { return d + 360 } d > 180 { return d - 360 } else { return d } } } fn angle_difference(b2 Bearing, b1 Bearing) Bearing { return math.mod(math.mod(b2-b1, 360)+360+180, 360) - 180 }
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
#Wren
Wren
var subtract = Fn.new { |b1, b2| var d = (b2 - b1) % 360 if (d < -180) d = d + 360 if (d >= 180) d = d - 360 return (d * 10000).round / 10000 // to 4dp }   var pairs = [ [ 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] ]   System.print("Differences (to 4dp) between these bearings:") for (pair in pairs) { var p0 = pair[0] var p1 = pair[1] var diff = subtract.call(p0, p1) var offset = (p0 < 0) ? " " : " " System.print("%(offset)%(p0) and %(p1) -> %(diff)") }
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
#VBA
VBA
Sub Main_DerangedAnagrams() Dim ListeWords() As String, Book As String, i As Long, j As Long, tempLen As Integer, MaxLen As Integer, tempStr As String, IsDeranged As Boolean, count As Integer, bAnag As Boolean Dim t As Single t = Timer Book = Read_File("C:\Users\" & Environ("Username") & "\Desktop\unixdict.txt") ListeWords = Split(Book, vbNewLine) For i = LBound(ListeWords) To UBound(ListeWords) - 1 For j = i + 1 To UBound(ListeWords) If Len(ListeWords(i)) = Len(ListeWords(j)) Then tempLen = 0 IsDeranged = False bAnag = IsAnagram(ListeWords(i), ListeWords(j), IsDeranged, tempLen) If IsDeranged Then count = count + 1 If tempLen > MaxLen Then MaxLen = tempLen tempStr = ListeWords(i) & ", " & ListeWords(j) End If End If End If Next j Next i Debug.Print "There is : " & count & " deranged anagram, in unixdict.txt." Debug.Print "The longest is : " & tempStr Debug.Print "Lenght  : " & MaxLen Debug.Print "Time to compute : " & Timer - t & " sec." End Sub Private Function Read_File(Fic As String) As String Dim Nb As Integer Nb = FreeFile Open Fic For Input As #Nb Read_File = Input(LOF(Nb), #Nb) Close #Nb End Function Function IsAnagram(str1 As String, str2 As String, DerangedAnagram As Boolean, Lenght As Integer) As Boolean Dim i As Integer str1 = Trim(UCase(str1)) str2 = Trim(UCase(str2)) For i = 1 To Len(str1) If Len(Replace(str1, Mid$(str1, i, 1), vbNullString)) <> Len(Replace(str2, Mid$(str1, i, 1), vbNullString)) Then Exit Function End If If Mid$(str1, i, 1) = Mid$(str2, i, 1) Then Exit Function End If Next i IsAnagram = True DerangedAnagram = True Lenght = Len(str1) End Function
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.
#Racket
Racket
  #lang racket   ;; Natural -> Natural ;; Calculate factorial (define (fact n) (define (fact-helper n acc) (if (= n 0) acc (fact-helper (sub1 n) (* n acc)))) (unless (exact-nonnegative-integer? n) (raise-argument-error 'fact "natural" n)) (fact-helper n 1))   ;; Unit tests, works in v5.3 and newer (module+ test (require rackunit) (check-equal? (fact 0) 1) (check-equal? (fact 5) 120))  
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.
#Prolog
Prolog
divisor(N, Divisor) :- UpperBound is round(sqrt(N)), between(1, UpperBound, D), 0 is N mod D, ( Divisor = D ; LargerDivisor is N/D, LargerDivisor =\= D, Divisor = LargerDivisor ).   proper_divisor(N, D) :- divisor(N, D), D =\= N.   assoc_num_divsSum_in_range(Low, High, Assoc) :- findall( Num-DivSum, ( between(Low, High, Num), aggregate_all( sum(D), proper_divisor(Num, D), DivSum )), Pairs ), list_to_assoc(Pairs, Assoc).   get_amicable_pair(Assoc, M-N) :- gen_assoc(M, Assoc, N), M < N, get_assoc(N, Assoc, M).   amicable_pairs_under_20000(Pairs) :- assoc_num_divsSum_in_range(1,20000, Assoc), findall(P, get_amicable_pair(Assoc, P), Pairs).
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.
#Sidef
Sidef
require('Tk')   var root = %s<MainWindow>.new('-title' => 'Pendulum Animation') var canvas = root.Canvas('-width' => 320, '-height' => 200)   canvas.createLine( 0, 25, 320, 25, '-tags' => <plate>, '-width' => 2, '-fill' => :grey50) canvas.createOval(155, 20, 165, 30, '-tags' => <pivot outline>, '-fill' => :grey50) canvas.createLine( 1, 1, 1, 1, '-tags' => <rod width>, '-width' => 3, '-fill' => :black) canvas.createOval( 1, 1, 2, 2, '-tags' => <bob outline>, '-fill' => :yellow)   canvas.raise(:pivot) canvas.pack('-fill' => :both, '-expand' => 1) var(θ = 45, Δθ = 0, length = 150, homeX = 160, homeY = 25)   func show_pendulum() { var angle = θ.deg2rad var x = (homeX + length*sin(angle)) var y = (homeY + length*cos(angle)) canvas.coords(:rod, homeX, homeY, x, y) canvas.coords(:bob, x - 15, y - 15, x + 15, y + 15) }   func recompute_angle() { var scaling = 3000/(length**2)   # first estimate var firstΔΔθ = (-sin(θ.deg2rad) * scaling) var midΔθ = (Δθ + firstΔΔθ) var midθ = ((Δθ + midΔθ)/2 + θ)   # second estimate var midΔΔθ = (-sin(midθ.deg2rad) * scaling) midΔθ = ((firstΔΔθ + midΔΔθ)/2 + Δθ) midθ = ((Δθ + midΔθ)/2 + θ)   # again, first midΔΔθ = (-sin(midθ.deg2rad) * scaling) var lastΔθ = (midΔθ + midΔΔθ) var lastθ = ((midΔθ + lastΔθ)/2 + midθ)   # again, second var lastΔΔθ = (-sin(lastθ.deg2rad) * scaling) lastΔθ = ((midΔΔθ + lastΔΔθ)/2 + midΔθ) lastθ = ((midΔθ + lastΔθ)/2 + midθ)   # Now put the values back in our globals Δθ = lastΔθ θ = lastθ }   func animate(Ref id) { recompute_angle() show_pendulum() *id = root.after(15 => { animate(id) }) }   show_pendulum() var after_id = root.after(500 => { animate(\after_id) })   canvas.bind('<Destroy>' => { after_id.cancel }) %S<Tk>.MainLoop()
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.
#OCaml
OCaml
let set_1 = ["the"; "that"; "a"] let set_2 = ["frog"; "elephant"; "thing"] let set_3 = ["walked"; "treaded"; "grows"] let set_4 = ["slowly"; "quickly"]   let combs ll = let rec aux acc = function | [] -> (List.map List.rev acc) | hd::tl -> let acc = List.fold_left (fun _ac l -> List.fold_left (fun _ac v -> (v::l)::_ac) _ac hd ) [] acc in aux acc tl in aux [[]] ll   let last s = s.[pred(String.length s)] let joined a b = (last a = b.[0])   let rec test = function | a::b::tl -> (joined a b) && (test (b::tl)) | _ -> true   let print_set set = List.iter (Printf.printf " %s") set; print_newline(); ;;   let () = let sets = combs [set_1; set_2; set_3; set_4] in let sets = List.filter test sets in List.iter print_set sets; ;;
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.
#FreeBASIC
FreeBASIC
' FB 1.05.0 Win64   ' uses overloaded methods to deal with the integer/float aspect (long and single are both 4 bytes) Type Bar Public: Declare Constructor(As Long) Declare Constructor(As Single) Declare Function g(As Long) As Long Declare Function g(As Single) As Single Private: As Single sum_ '' can't be altered by external code End Type   Constructor Bar(i As Long) sum_ = i End Constructor   Constructor Bar(s As Single) sum_ = s End Constructor   Function Bar.g(i As Long) As Long sum_ += i Return sum_ '' would round down to a Long if non-integral Singles had been added previously End Function   Function Bar.g(s As Single) As Single sum_ += s Return sum_ End Function   Function foo Overload(i As Long) As Bar '' returns a Bar object rather than a pointer to Bar.g Dim b As Bar = Bar(i) Return b End Function   Function foo Overload(s As Single) As Bar '' overload of foo to deal with Single argument Dim b As Bar = Bar(s) Return b End Function   Dim x As Bar = foo(1) '' assigns Bar object to x x.g(5) '' calls the Long overload of g on the Bar object foo(3) '' creates a separate Bar object which is unused print x.g(2.3) '' calls the Single overload of g on the Bar object and should print 1 + 5 + 2.3 = 8.3   Print Print "Press any key to quit" Sleep
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.
#ALGOL_W
ALGOL W
begin integer procedure ackermann( integer value m,n ) ; if m=0 then n+1 else if n=0 then ackermann(m-1,1) else ackermann(m-1,ackermann(m,n-1)); for m := 0 until 3 do begin write( ackermann( m, 0 ) ); for n := 1 until 6 do writeon( ackermann( m, n ) ); end for_m end.
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
#Bracmat
Bracmat
( clk$:?t0 & ( multiples = prime multiplicity .  !arg:(?prime.?multiplicity) & !multiplicity:0 & 1 |  !prime^!multiplicity*(.!multiplicity) + multiples$(!prime.-1+!multiplicity) ) & ( P = primeFactors prime exp poly S .  !arg^1/67:?primeFactors & ( !primeFactors:?^1/67&0 | 1:?poly & whl ' ( !primeFactors:%?prime^?exp*?primeFactors & !poly*multiples$(!prime.67*!exp):?poly ) & -1+!poly+1:?poly & 1:?S & (  !poly  :  ? + (#%@?s*?&!S+!s:?S&~) + ? | 1/2*!S ) ) ) & 0:?deficient:?perfect:?abundant & 0:?n & whl ' ( 1+!n:~>20000:?n & P$!n  : ( <!n&1+!deficient:?deficient | !n&1+!perfect:?perfect | >!n&1+!abundant:?abundant ) ) & out$(deficient !deficient perfect !perfect abundant !abundant) & clk$:?t1 & out$(flt$(!t1+-1*!t0,2) sec) & clk$:?t2 & ( P = f h S . 0:?f & 0:?S & whl ' ( 1+!f:?f & !f^2:~>!n & (  !arg*!f^-1:~/:?g & !S+!f:?S & ( !g:~!f&!S+!g:?S | ) | ) ) & 1/2*!S ) & 0:?deficient:?perfect:?abundant & 0:?n & whl ' ( 1+!n:~>20000:?n & P$!n  : ( <!n&1+!deficient:?deficient | !n&1+!perfect:?perfect | >!n&1+!abundant:?abundant ) ) & out$(deficient !deficient perfect !perfect abundant !abundant) & clk$:?t3 & out$(flt$(!t3+-1*!t2,2) sec) );
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
#C.2B.2B
C++
  (ns rosettacode.align-columns (:require [clojure.contrib.string :as str]))   (def data "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.")   (def table (map #(str/split #"\$" %) (str/split-lines data)))   (defn col-width [n table] (reduce max (map #(try (count (nth % n)) (catch Exception _ 0)) table))) (defn spaces [n] (str/repeat n " ")) (defn add-padding "if the string is too big turncate it, else return a string with padding" [string width justification] (if (>= (count string) width) (str/take width string) (let [pad-len (int (- width (count string))) ;we don't want rationals half-pad-len (int (/ pad-len 2))] (case justification  :right (str (spaces pad-len) string)  :left (str string (spaces pad-len))  :center (str (spaces half-pad-len) string (spaces (- pad-len half-pad-len)))))))   (defn aligned-table "get the width of each column, then generate a new table with propper padding for eath item" ([table justification] (let [col-widths (map #(+ 2 (col-width % table)) (range (count(first table))))] (map (fn [row] (map #(add-padding %1 %2 justification) row col-widths)) table))))   (defn print-table [table] (do (println) (print (str/join "" (flatten (interleave table (repeat "\n")))))))   (print-table (aligned-table table :center))  
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.
#Oz
Oz
declare fun {Const X} fun {$ _} X end end   fun {Now} {Int.toFloat {Property.get 'time.total'}} / 1000.0 end   class Integrator from Time.repeat attr k:{Const 0.0} s:0.0 t1 k_t1 t2 k_t2   meth init(SampleIntervalMS) t1 := {Now} k_t1 := {@k @t1} {self setRepAll(action:Update delay:SampleIntervalMS)} thread {self go} end end   meth input(K) k := K end   meth output($) @s end   meth Update t2 := {Now} k_t2 := {@k @t2} s := @s + (@k_t1 + @k_t2) * (@t2 - @t1) / 2.0 t1 := @t2 k_t1 := @k_t2 end end   Pi = 3.14159265 F = 0.5   I = {New Integrator init(10)} in {I input(fun {$ T} {Sin 2.0 * Pi * F * T} end)}   {Delay 2000} %% ms   {I input({Const 0.0})}   {Delay 500} %% ms   {Show {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
#Prolog
Prolog
% See https://en.wikipedia.org/wiki/Divisor_function divisor_sum(N, Total):- divisor_sum_prime(N, 2, 2, Total1, 1, N1), divisor_sum(N1, 3, Total, Total1).   divisor_sum(1, _, Total, Total):- !. divisor_sum(N, Prime, Total, Running_total):- Prime * Prime =< N, !, divisor_sum_prime(N, Prime, Prime, P, 1, M), Next_prime is Prime + 2, Running_total1 is P * Running_total, divisor_sum(M, Next_prime, Total, Running_total1). divisor_sum(N, _, Total, Running_total):- Total is (N + 1) * Running_total.   divisor_sum_prime(N, Prime, Power, Total, Running_total, M):- 0 is N mod Prime, !, Running_total1 is Running_total + Power, Power1 is Power * Prime, N1 is N // Prime, divisor_sum_prime(N1, Prime, Power1, Total, Running_total1, M). divisor_sum_prime(N, _, _, Total, Total, N).   % See https://en.wikipedia.org/wiki/Aliquot_sequence aliquot_sequence(N, Limit, Sequence, Class):- aliquot_sequence(N, Limit, [N], Sequence, Class).   aliquot_sequence(_, 0, _, [], 'non-terminating'):-!. aliquot_sequence(_, _, [0|_], [0], terminating):-!. aliquot_sequence(N, _, [N, N|_], [], perfect):-!. aliquot_sequence(N, _, [N, _, N|_], [N], amicable):-!. aliquot_sequence(N, _, [N|S], [N], sociable):- memberchk(N, S), !. aliquot_sequence(_, _, [Term, Term|_], [], aspiring):-!. aliquot_sequence(_, _, [Term|S], [Term], cyclic):- memberchk(Term, S), !. aliquot_sequence(N, Limit, [Term|S], [Term|Rest], Class):- divisor_sum(Term, Sum), Term1 is Sum - Term, L1 is Limit - 1, aliquot_sequence(N, L1, [Term1, Term|S], Rest, Class).   write_aliquot_sequence(N, Sequence, Class):- writef('%w: %w, sequence:', [N, Class]), write_aliquot_sequence(Sequence).   write_aliquot_sequence([]):- nl, !. write_aliquot_sequence([Term|Rest]):- writef(' %w', [Term]), write_aliquot_sequence(Rest).   main:- between(1, 10, N), aliquot_sequence(N, 16, Sequence, Class), write_aliquot_sequence(N, Sequence, Class), fail. main:- member(N, [11, 12, 28, 496, 220, 1184, 12496, 1264460, 790, 909, 562, 1064, 1488]), aliquot_sequence(N, 16, Sequence, Class), write_aliquot_sequence(N, Sequence, Class), fail. main.
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.
#Julia
Julia
  function polycoefs(n::Int64) pc = typeof(n)[] if n < 0 return pc end sgn = one(n) for k in n:-1:0 push!(pc, sgn*binomial(n, k)) sgn = -sgn end return pc 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.
#Quackery
Quackery
500 eratosthenes   [] 500 times [ i^ isprime if [ i^ 10 digitsum isprime if [ i^ join ] ] ] dup echo cr cr size echo say " additive primes found."
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.
#Racket
Racket
#lang racket   (require math/number-theory)   (define (sum-of-digits n (σ 0)) (if (zero? n) σ (let-values (((q r) (quotient/remainder n 10))) (sum-of-digits q (+ σ r)))))   (define (additive-prime? n) (and (prime? n) (prime? (sum-of-digits n))))   (define additive-primes<500 (filter additive-prime? (range 1 500))) (printf "There are ~a additive primes < 500~%" (length additive-primes<500)) (printf "They are: ~a~%" additive-primes<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.
#Raku
Raku
unit sub MAIN ($limit = 500); say "{+$_} additive primes < $limit:\n{$_».fmt("%" ~ $limit.chars ~ "d").batch(10).join("\n")}", with ^$limit .grep: { .is-prime and .comb.sum.is-prime }
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
#PL.2FI
PL/I
almost_prime: procedure options(main); kprime: procedure(nn, k) returns(bit); declare (n, nn, k, p, f) fixed; f = 0; n = nn; do p=2 repeat(p+1) while(f<k & p*p <= n); do n=n repeat(n/p) while(mod(n,p) = 0); f = f+1; end; end; return(f + (n>1) = k); end kprime;   declare (i, c, k) fixed; do k=1 to 5; put edit('k = ',k,':') (A,F(1),A); c = 0; do i=2 repeat(i+1) while(c<10); if kprime(i,k) then do; put edit(i) (F(4)); c = c+1; end; end; put skip; end; end almost_prime;
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
#FreeBASIC
FreeBASIC
' FB 1.05.0 Win64   Type IndexedWord As String word As Integer index End Type   ' selection sort, quick enough for sorting small number of letters Sub sortWord(s As String) Dim As Integer i, j, m, n = Len(s) For i = 0 To n - 2 m = i For j = i + 1 To n - 1 If s[j] < s[m] Then m = j Next j If m <> i Then Swap s[i], s[m] Next i End Sub   ' selection sort, quick enough for sorting small array of IndexedWord instances by index Sub sortIndexedWord(iw() As IndexedWord) Dim As Integer i, j, m, n = UBound(iw) For i = 1 To n - 1 m = i For j = i + 1 To n If iw(j).index < iw(m).index Then m = j Next j If m <> i Then Swap iw(i), iw(m) Next i End Sub   ' quicksort for sorting whole dictionary of IndexedWord instances by sorted word Sub quicksort(a() As IndexedWord, first As Integer, last As Integer) Dim As Integer length = last - first + 1 If length < 2 Then Return Dim pivot As String = a(first + length\ 2).word Dim lft As Integer = first Dim rgt As Integer = last While lft <= rgt While a(lft).word < pivot lft +=1 Wend While a(rgt).word > pivot rgt -= 1 Wend If lft <= rgt Then Swap a(lft), a(rgt) lft += 1 rgt -= 1 End If Wend quicksort(a(), first, rgt) quicksort(a(), lft, last) End Sub   Dim t As Double = timer Dim As String w() '' array to hold actual words Open "undict.txt" For Input As #1 Dim count As Integer = 0 While Not Eof(1) count +=1 Redim Preserve w(1 To count) Line Input #1, w(count) Wend Close #1   Dim As IndexedWord iw(1 To count) '' array to hold sorted words and their index into w() Dim word As String For i As Integer = 1 To count word = w(i) sortWord(word) iw(i).word = word iw(i).index = i Next quickSort iw(), 1, count '' sort the IndexedWord array by sorted word   Dim As Integer startIndex = 1, length = 1, maxLength = 1, ub = 1 Dim As Integer maxIndex(1 To ub) maxIndex(ub) = 1 word = iw(1).word   For i As Integer = 2 To count If word = iw(i).word Then length += 1 Else If length > maxLength Then maxLength = length Erase maxIndex ub = 1 Redim maxIndex(1 To ub) maxIndex(ub) = startIndex ElseIf length = maxLength Then ub += 1 Redim Preserve maxIndex(1 To ub) maxIndex(ub) = startIndex End If startIndex = i length = 1 word = iw(i).word End If Next   If length > maxLength Then maxLength = length Erase maxIndex Redim maxIndex(1 To 1) maxIndex(1) = startIndex ElseIf length = maxLength Then ub += 1 Redim Preserve maxIndex(1 To ub) maxIndex(ub) = startIndex End If   Print Str(count); " words in the dictionary" Print "The anagram set(s) with the greatest number of words (namely"; maxLength; ") is:" Print Dim iws(1 To maxLength) As IndexedWord '' array to hold each anagram set For i As Integer = 1 To UBound(maxIndex) For j As Integer = maxIndex(i) To maxIndex(i) + maxLength - 1 iws(j - maxIndex(i) + 1) = iw(j) Next j sortIndexedWord iws() '' sort anagram set before displaying it For j As Integer = 1 To maxLength Print w(iws(j).index); " "; Next j Print Next i   Print Print "Took "; Print Using "#.###"; timer - t; Print " seconds on i3 @ 2.13 GHz"   Print Print "Press any key to quit" Sleep
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
#XBS
XBS
settype Bearing = {Angle:number} class Bearing { private method construct(Angle:number=0) self.Angle=(((Angle%360)+540)%360)-180; method ToString():string send tostring(math.nround(self.Angle,4))+"°"; private method __sub(b2:Bearing):Bearing{ send new Bearing(self.Angle-b2.Angle); } }   const BearingAngles:[[number]] = [ [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] ];   foreach(v of BearingAngles){ set b1:Bearing=new Bearing(v[0]); set b2:Bearing=new Bearing(v[1]); log(b2::ToString()+" - "+b1::ToString()+" = "+(b2-b1)::ToString()); }
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
#Vlang
Vlang
import os   fn deranged(a string, b string) bool { if a.len != b.len { return false } for i in 0..a.len { if a[i] == b[i] { return false } } return true } fn main(){ words := os.read_lines('unixdict.txt')?   mut m := map[string][]string{} mut best_len, mut w1, mut w2 := 0, '',''   for w in words { // don't bother: too short to beat current record if w.len <= best_len { continue }   // save strings in map, with sorted string as key mut letters := w.split('') letters.sort() k := letters.join("")   if k !in m { m[k] = [w] continue }   for c in m[k] { if deranged(w, c) { best_len, w1, w2 = w.len, c, w break } }   m[k] << w }   println('$w1 $w2: Length $best_len') }
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.
#Raku
Raku
sub fib($n) { die "Naughty fib" if $n < 0; return { $_ < 2 ?? $_ !! &?BLOCK($_-1) + &?BLOCK($_-2); }($n); }   say fib(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.
#PureBasic
PureBasic
  EnableExplicit   Procedure.i SumProperDivisors(Number) If Number < 2 : ProcedureReturn 0 : EndIf Protected i, sum = 0 For i = 1 To Number / 2 If Number % i = 0 sum + i EndIf Next ProcedureReturn sum EndProcedure   Define n, f Define Dim sum(19999)   If OpenConsole() For n = 1 To 19999 sum(n) = SumProperDivisors(n) Next PrintN("The pairs of amicable numbers below 20,000 are : ") PrintN("") For n = 1 To 19998 f = sum(n) If f <= n Or f < 1 Or f > 19999 : Continue : EndIf If f = sum(n) And n = sum(f) PrintN(RSet(Str(n),5) + " and " + RSet(Str(sum(n)), 5)) EndIf Next PrintN("") PrintN("Press any key to close the console") Repeat: Delay(10) : Until Inkey() <> "" CloseConsole() EndIf  
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.
#smart_BASIC
smart BASIC
'Pendulum 'By Dutchman ' --- constants g=9.81 ' accelleration of gravity l=1 ' length of pendulum GET SCREEN SIZE sw,sh pivotx=sw/2 pivoty=150 ' --- initialise graphics GRAPHICS DRAW COLOR 1,0,0 FILL COLOR 0,0,1 DRAW SIZE 2 ' --- initialise pendulum theta=1 ' initial displacement in radians speed=0 ' --- loop DO bobx=pivotx+100*l*SIN(theta) boby=pivoty-100*l*COS(theta) GOSUB Plot PAUSE 0.01 accel=g*SIN(theta)/l/100 speed=speed+accel theta=theta+speed UNTIL 0 END ' --- subroutine Plot: REFRESH OFF GRAPHICS CLEAR 1,1,0.5 DRAW LINE pivotx,pivoty TO bobx,boby FILL CIRCLE bobx,boby SIZE 10 REFRESH ON RETURN  
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.
#OpenEdge.2FProgress
OpenEdge/Progress
DEF VAR cset AS CHAR EXTENT 4 INIT [ "the,that,a", "frog,elephant,thing", "walked,treaded,grows", "slowly,quickly" ].   FUNCTION getAmb RETURNS CHARACTER ( i_cwords AS CHAR, i_iset AS INT ):   DEF VAR cresult AS CHAR. DEF VAR ii AS INT. DEF VAR cword AS CHAR.   DO ii = 1 TO NUM-ENTRIES( cset [ i_iset ] ) WHILE NUM-ENTRIES( cresult, " " ) < EXTENT( cset ):   cword = ENTRY( ii, cset[ i_iset ] ). IF i_cwords = "" OR SUBSTRING( i_cwords, LENGTH( i_cwords ), 1 ) = SUBSTRING( cword, 1, 1 ) THEN DO: IF i_iset = EXTENT ( cset ) THEN cresult = i_cwords + " " + cword. ELSE cresult = getAmb( i_cwords + " " + cword, i_iset + 1 ). END.   END.   RETURN cresult.   END FUNCTION. /* getAmb */     MESSAGE getAmb( "", 1 ) VIEW-AS ALERT-BOX.
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.
#Go
Go
package main   import "fmt"   func accumulator(sum interface{}) func(interface{}) interface{} { return func(nv interface{}) interface{} { switch s := sum.(type) { case int: switch n := nv.(type) { case int: sum = s + n case float64: sum = float64(s) + n } case float64: switch n := nv.(type) { case int: sum = s + float64(n) case float64: sum = s + n } default: sum = nv } return sum } }   func main() { x := accumulator(1) x(5) accumulator(3) fmt.Println(x(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.
#APL
APL
ackermann←{ 0=1⊃⍵:1+2⊃⍵ 0=2⊃⍵:∇(¯1+1⊃⍵)1 ∇(¯1+1⊃⍵),∇(1⊃⍵),¯1+2⊃⍵ }
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
#C
C
  #include<stdio.h> #define de 0 #define pe 1 #define ab 2   int main(){ int sum = 0, i, j; int try_max = 0; //1 is deficient by default and can add it deficient list int count_list[3] = {1,0,0}; for(i=2; i <= 20000; i++){ //Set maximum to check for proper division try_max = i/2; //1 is in all proper division number sum = 1; for(j=2; j<try_max; j++){ //Check for proper division if (i % j) continue; //Pass if not proper division //Set new maximum for divisibility check try_max = i/j; //Add j to sum sum += j; if (j != try_max) sum += try_max; } //Categorize summation if (sum < i){ count_list[de]++; continue; } if (sum > i){ count_list[ab]++; continue; } count_list[pe]++; } printf("\nThere are %d deficient," ,count_list[de]); printf(" %d perfect," ,count_list[pe]); printf(" %d abundant numbers between 1 and 20000.\n" ,count_list[ab]); return 0; }  
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
#Clojure
Clojure
  (ns rosettacode.align-columns (:require [clojure.contrib.string :as str]))   (def data "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.")   (def table (map #(str/split #"\$" %) (str/split-lines data)))   (defn col-width [n table] (reduce max (map #(try (count (nth % n)) (catch Exception _ 0)) table))) (defn spaces [n] (str/repeat n " ")) (defn add-padding "if the string is too big turncate it, else return a string with padding" [string width justification] (if (>= (count string) width) (str/take width string) (let [pad-len (int (- width (count string))) ;we don't want rationals half-pad-len (int (/ pad-len 2))] (case justification  :right (str (spaces pad-len) string)  :left (str string (spaces pad-len))  :center (str (spaces half-pad-len) string (spaces (- pad-len half-pad-len)))))))   (defn aligned-table "get the width of each column, then generate a new table with propper padding for eath item" ([table justification] (let [col-widths (map #(+ 2 (col-width % table)) (range (count(first table))))] (map (fn [row] (map #(add-padding %1 %2 justification) row col-widths)) table))))   (defn print-table [table] (do (println) (print (str/join "" (flatten (interleave table (repeat "\n")))))))   (print-table (aligned-table table :center))  
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.
#Perl
Perl
#!/usr/bin/perl   use strict; use 5.10.0;   package Integrator; use threads; use threads::shared;   sub new { my $cls = shift; my $obj = bless { t => 0, sum => 0, ref $cls ? %$cls : (), stop => 0, tid => 0, func => shift, }, ref $cls || $cls;   share($obj->{sum}); share($obj->{stop});   $obj->{tid} = async { my $upd = 0.1; # update every 0.1 second while (!$obj->{stop}) { { my $f = $obj->{func}; my $t = $obj->{t};   $obj->{sum} += ($f->($t) + $f->($t + $upd))* $upd/ 2; $obj->{t} += $upd; } select(undef, undef, undef, $upd); } # say "stopping $obj"; }; $obj }   sub output { shift->{sum} }   sub delete { my $obj = shift; $obj->{stop} = 1; $obj->{tid}->join; }   sub setinput { # This is surprisingly difficult because of the perl sharing model. # Func refs can't be shared, thus can't be replaced by another thread. # Have to create a whole new object... there must be a better way. my $obj = shift; $obj->delete; $obj->new(shift); }   package main;   my $x = Integrator->new(sub { sin(atan2(1, 1) * 8 * .5 * shift) });   sleep(2); say "sin after 2 seconds: ", $x->output;   $x = $x->setinput(sub {0});   select(undef, undef, undef, .5); say "0 after .5 seconds: ", $x->output;   $x->delete;
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
#Python
Python
from proper_divisors import proper_divs from functools import lru_cache     @lru_cache() def pdsum(n): return sum(proper_divs(n))     def aliquot(n, maxlen=16, maxterm=2**47): if n == 0: return 'terminating', [0] s, slen, new = [n], 1, n while slen <= maxlen and new < maxterm: new = pdsum(s[-1]) if new in s: if s[0] == new: if slen == 1: return 'perfect', s elif slen == 2: return 'amicable', s else: return 'sociable of length %i' % slen, s elif s[-1] == new: return 'aspiring', s else: return 'cyclic back to %i' % new, s elif new == 0: return 'terminating', s + [0] else: s.append(new) slen += 1 else: return 'non-terminating', s   if __name__ == '__main__': for n in range(1, 11): print('%s: %r' % aliquot(n)) print() for n in [11, 12, 28, 496, 220, 1184, 12496, 1264460, 790, 909, 562, 1064, 1488, 15355717786080]: print('%s: %r' % aliquot(n))
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.
#Kotlin
Kotlin
// version 1.1   fun binomial(n: Int, k: Int): Long = when { n < 0 || k < 0 -> throw IllegalArgumentException("negative numbers not allowed") k == 0 -> 1L k == n -> 1L else -> { var prod = 1L var div = 1L for (i in 1..k) { prod *= (n + 1 - i) div *= i if (prod % div == 0L) { prod /= div div = 1L } } prod } }   fun isPrime(n: Int): Boolean { if (n < 2) return false return (1 until n).none { binomial(n, it) % n.toLong() != 0L } }   fun main(args: Array<String>) { var coeff: Long var sign: Int var op: String for (n in 0..9) { print("(x - 1)^$n = ") sign = 1 for (k in n downTo 0) { coeff = binomial(n, k) op = if (sign == 1) " + " else " - " when (k) { n -> print("x^$n") 0 -> println("${op}1") else -> print("$op${coeff}x^$k") } if (n == 0) println() sign *= -1 } } // generate primes under 62 var p = 2 val primes = mutableListOf<Int>() do { if (isPrime(p)) primes.add(p) if (p != 2) p += 2 else p = 3 } while (p < 62) println("\nThe prime numbers under 62 are:") println(primes) }
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.
#Red
Red
  cross-sum: function [n][out: 0 foreach m form n [out: out + to-integer to-string m]] additive-primes: function [n][collect [foreach p ps: primes n [if find ps cross-sum p [keep p]]]]   length? probe new-line/skip additive-primes 500 true 10 [ 2 3 5 7 11 23 29 41 43 47 61 67 83 89 101 113 131 137 139 151 157 173 179 191 193 197 199 223 227 229 241 263 269 281 283 311 313 317 331 337 353 359 373 379 397 401 409 421 443 449 461 463 467 487 ] == 54  
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.
#REXX
REXX
/*REXX program counts/displays the number of additive primes under a specified number N.*/ parse arg n cols . /*get optional number of primes to find*/ if n=='' | n=="," then n= 500 /*Not specified? Then assume default.*/ if cols=='' | cols=="," then cols= 10 /* " " " " " */ call genP n /*generate all primes under N. */ w= 10 /*width of a number in any column. */ title= " additive primes that are < " commas(n) if cols>0 then say ' index │'center(title, 1 + cols*(w+1) ) if cols>0 then say '───────┼'center("" , 1 + cols*(w+1), '─') found= 0; idx= 1 /*initialize # of additive primes & IDX*/ $= /*a list of additive primes (so far). */ do j=1 for #; p= @.j /*obtain the Jth prime. */ _= sumDigs(p); if \!._ then iterate /*is sum of J's digs a prime? No, skip.*/ /* ◄■■■■■■■■ a filter. */ found= found + 1 /*bump the count of additive primes. */ if cols<0 then iterate /*Build the list (to be shown later)? */ c= commas(p) /*maybe add commas to the number. */ $= $ right(c, max(w, length(c) ) ) /*add additive prime──►list, allow big#*/ if found//cols\==0 then iterate /*have we populated a line of output? */ say center(idx, 7)'│' substr($, 2); $= /*display what we have so far (cols). */ idx= idx + cols /*bump the index count for the output*/ end /*j*/   if $\=='' then say center(idx, 7)"│" substr($, 2) /*possible display residual output.*/ if cols>0 then say '───────┴'center("" , 1 + cols*(w+1), '─') say say 'found ' commas(found) title exit 0 /*stick a fork in it, we're all done. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ commas: parse arg ?; do jc=length(?)-3 to 1 by -3; ?=insert(',', ?, jc); end; return ? sumDigs: parse arg x 1 s 2; do k=2 for length(x)-1; s= s + substr(x,k,1); end; return s /*──────────────────────────────────────────────────────────────────────────────────────*/ genP: parse arg n; @.1= 2; @.2= 3; @.3= 5; @.4= 7; @.5= 11; @.6= 13  !.= 0;  !.2= 1;  !.3= 1;  !.5= 1;  !.7= 1;  !.11= 1;  !.13= 1 #= 6; sq.#= @.# ** 2 /*the number of primes; prime squared.*/ do j=@.#+2 by 2 for max(0, n%2-@.#%2-1) /*find odd primes from here on. */ parse var j '' -1 _ /*obtain the last digit of the J var.*/ if _==5 then iterate; if j// 3==0 then iterate /*J ÷ by 5? J ÷ by 3? */ if j// 7==0 then iterate; if j//11==0 then iterate /*" " " 7? " " " 11? */ /* [↓] divide by the primes. ___ */ do k=6 while sq.k<=j /*divide J by other primes ≤ √ J */ if j//@.k==0 then iterate j /*÷ by prev. prime? ¬prime ___ */ end /*k*/ /* [↑] only divide up to √ J */ #= # + 1; @.#= j; sq.#= j*j;  !.j= 1 /*bump prime count; assign prime & flag*/ end /*j*/; return
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
#PL.2FM
PL/M
100H: BDOS: PROCEDURE (FN, ARG); DECLARE FN BYTE, ARG ADDRESS; GO TO 5; END BDOS; EXIT: PROCEDURE; CALL BDOS(0,0); END EXIT; PRINT: PROCEDURE (S); DECLARE S ADDRESS; CALL BDOS(9,S); END PRINT;   PRINT$NUMBER: PROCEDURE (N); DECLARE S (4) BYTE INITIAL ('...$'); DECLARE P ADDRESS, (N, C BASED P) BYTE; P = .S(3); DIGIT: P = P - 1; C = N MOD 10 + '0'; N = N / 10; IF N > 0 THEN GO TO DIGIT; CALL PRINT(P); END PRINT$NUMBER;   KPRIME: PROCEDURE (N, K) BYTE; DECLARE (N, K, P, F) BYTE; F = 0; P = 2; DO WHILE F < K AND P*P <= N; DO WHILE N MOD P = 0; N = N/P; F = F+1; END; P = P+1; END; IF N > 1 THEN F = F + 1; RETURN F = K; END KPRIME;   DECLARE (I, C, K) BYTE; DO K=1 TO 5; CALL PRINT(.'K = $'); CALL PRINT$NUMBER(K); CALL PRINT(.':$');   C = 0; I = 2; DO WHILE C < 10; IF KPRIME(I, K) THEN DO; CALL PRINT(.' $'); CALL PRINT$NUMBER(I); C = C+1; END; I = I+1; END; CALL PRINT(.(13,10,'$')); END; CALL EXIT; EOF
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
#Phix
Phix
sequence res = columnize({tagset(5)}) -- ie {{1},{2},{3},{4},{5}} integer n = 2, found = 0 while found<50 do integer l = length(prime_factors(n,true)) if l<=5 and length(res[l])<=10 then res[l] &= n found += 1 end if n += 1 end while string fmt = "k = %d: "&join(repeat("%4d",10))&"\n" for i=1 to 5 do printf(1,fmt,res[i]) end for
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
#Frink
Frink
  d = new dict for w = lines["http://wiki.puzzlers.org/pub/wordlists/unixdict.txt"] { sorted = sort[charList[w]] d.addToList[sorted, w] }   most = sort[toArray[d], {|a,b| length[b@1] <=> length[a@1]}] longest = length[most@0@1]   i = 0 while length[most@i@1] == longest { println[most@i@1] i = i + 1 }  
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
#XPL0
XPL0
real B1, B2, Ang; [Text(0, " Bearing 1 Bearing 2 Difference"); loop [B1:= RlIn(1); B2:= RlIn(1); Ang:= B2 - B1; while Ang > 180. do Ang:= Ang - 360.; while Ang < -180. do Ang:= Ang + 360.; CrLf(0); RlOut(0, B1); ChOut(0, 9); RlOut(0, B2); ChOut(0, 9); RlOut(0, Ang); ]; ]
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
#Yabasic
Yabasic
// Rosetta Code problem: http://rosettacode.org/wiki/Angle_difference_between_two_bearings // by Jjuanhdez, 06/2022   print "Input in -180 to +180 range:" getDifference(20.0, 45.0) getDifference(-45.0, 45.0) getDifference(-85.0, 90.0) getDifference(-95.0, 90.0) getDifference(-45.0, 125.0) getDifference(-45.0, 145.0) getDifference(-45.0, 125.0) getDifference(-45.0, 145.0) getDifference(29.4803, -88.6381) getDifference(-78.3251, -159.036) print "\nInput in wider range:" getDifference(-70099.74233810938, 29840.67437876723) getDifference(-165313.6666297357, 33693.9894517456) getDifference(1174.8380510598456, -154146.66490124757) end   sub getDifference(b1, b2) r = mod((b2 - b1), 360.0) if r >= 180.0 r = r - 360.0 print r end sub
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
#Wren
Wren
import "io" for File import "/sort" for Sort   // assumes w1 and w2 are anagrams of each other var isDeranged = Fn.new { |w1, w2| for (i in 0...w1.count) { if (w1[i] == w2[i]) return false } return true }   var words = File.read("unixdict.txt").split("\n").map { |w| w.trim() } var wordMap = {} for (word in words) { var letters = word.toList Sort.insertion(letters) var sortedWord = letters.join() if (wordMap.containsKey(sortedWord)) { wordMap[sortedWord].add(word) } else { wordMap[sortedWord] = [word] } }   var deranged = [] for (key in wordMap.keys) { var ana = wordMap[key] var count = ana.count if (count > 1) { for (i in 0...count-1) { for (j in i + 1...count) { if (isDeranged.call(ana[i], ana[j])) deranged.add([ana[i], ana[j]]) } } } }   var most = deranged.reduce(0) { |max, words| (words[0].count > max) ? words[0].count : max } for (words in deranged) { if (words[0].count == most) System.print([words[0], words[1]]) }
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.
#REBOL
REBOL
  fib: func [n /f][ do f: func [m] [ either m < 2 [m][(f m - 1) + f 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.
#Python
Python
from proper_divisors import proper_divs   def amicable(rangemax=20000): n2divsum = {n: sum(proper_divs(n)) for n in range(1, rangemax + 1)} for num, divsum in n2divsum.items(): if num < divsum and divsum <= rangemax and n2divsum[divsum] == num: yield num, divsum   if __name__ == '__main__': for num, divsum in amicable(): print('Amicable pair: %i and %i With proper divisors:\n  %r\n  %r'  % (num, divsum, sorted(proper_divs(num)), sorted(proper_divs(divsum))))
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.
#Tcl
Tcl
package require Tcl 8.5 package require Tk   # Make the graphical entities pack [canvas .c -width 320 -height 200] -fill both -expand 1 .c create line 0 25 320 25 -width 2 -fill grey50 -tags plate .c create line 1 1 1 1 -tags rod -width 3 -fill black .c create oval 1 1 2 2 -tags bob -fill yellow -outline black .c create oval 155 20 165 30 -fill grey50 -outline {} -tags pivot   # Set some vars set points {} set Theta 45.0 set dTheta 0.0 set pi 3.1415926535897933 set length 150 set homeX 160   # How to respond to a changing in size of the window proc resized {width} { global homeX .c coords plate 0 25 $width 25 set homeX [expr {$width / 2}] .c coords pivot [expr {$homeX-5}] 20 [expr {$homeX+5}] 30 showPendulum }   # How to actually arrange the pendulum, mapping the model to the display proc showPendulum {} { global Theta dTheta pi length homeX set angle [expr {$Theta * $pi/180}] set x [expr {$homeX + $length*sin($angle)}] set y [expr {25 + $length*cos($angle)}] .c coords rod $homeX 25 $x $y .c coords bob [expr {$x-15}] [expr {$y-15}] [expr {$x+15}] [expr {$y+15}] }   # The dynamic part of the display proc recomputeAngle {} { global Theta dTheta pi length set scaling [expr {3000.0/$length**2}]   # first estimate set firstDDTheta [expr {-sin($Theta * $pi/180)*$scaling}] set midDTheta [expr {$dTheta + $firstDDTheta}] set midTheta [expr {$Theta + ($dTheta + $midDTheta)/2}] # second estimate set midDDTheta [expr {-sin($midTheta * $pi/180)*$scaling}] set midDTheta [expr {$dTheta + ($firstDDTheta + $midDDTheta)/2}] set midTheta [expr {$Theta + ($dTheta + $midDTheta)/2}] # Now we do a double-estimate approach for getting the final value # first estimate set midDDTheta [expr {-sin($midTheta * $pi/180)*$scaling}] set lastDTheta [expr {$midDTheta + $midDDTheta}] set lastTheta [expr {$midTheta + ($midDTheta + $lastDTheta)/2}] # second estimate set lastDDTheta [expr {-sin($lastTheta * $pi/180)*$scaling}] set lastDTheta [expr {$midDTheta + ($midDDTheta + $lastDDTheta)/2}] set lastTheta [expr {$midTheta + ($midDTheta + $lastDTheta)/2}] # Now put the values back in our globals set dTheta $lastDTheta set Theta $lastTheta }   # Run the animation by updating the physical model then the display proc animate {} { global animation   recomputeAngle showPendulum   # Reschedule set animation [after 15 animate] } set animation [after 500 animate]; # Extra initial delay is visually pleasing   # Callback to handle resizing of the canvas bind .c <Configure> {resized %w} # Callback to stop the animation cleanly when the GUI goes away bind .c <Destroy> {after cancel $animation}
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.
#Oz
Oz
declare   fun {Amb Xs} case Xs of nil then fail [] [X] then X [] X|Xr then choice X [] {Amb Xr} end end end   fun {Example} W1 = {Amb ["the" "that" "a"]} W2 = {Amb ["frog" "elephant" "thing"]} W3 = {Amb ["walked" "treaded" "grows"]} W4 = {Amb ["slowly" "quickly"]} in {List.last W1 W2.1} {List.last W2 W3.1} {List.last W3 W4.1} W1#" "#W2#" "#W3#" "#W4 end   in   {ForAll {SearchAll Example} System.showInfo}
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.
#Golo
Golo
#!/usr/bin/env golosh ---- An accumulator factory example for Rosetta Code. This one uses the box function to create an AtomicReference. ---- module rosetta.AccumulatorFactory   function accumulator = |n| { let number = box(n) return |i| -> number: accumulateAndGet(i, |a, b| -> a + b) }   function main = |args| { let acc = accumulator(3) println(acc(1)) println(acc(1.1)) println(acc(10)) println(acc(100.101)) }
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.
#Groovy
Groovy
def accumulator = { Number n -> def value = n; { it = 0 -> value += it} }