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/Algebraic_data_types
Algebraic data types
Some languages offer direct support for algebraic data types and pattern matching on them. While this of course can always be simulated with manual tagging and conditionals, it allows for terse code which is easy to read, and can represent the algorithm directly. Task As an example, implement insertion in a red-black-tree. A red-black-tree is a binary tree where each internal node has a color attribute red or black. Moreover, no red node can have a red child, and every path from the root to an empty node must contain the same number of black nodes. As a consequence, the tree is balanced, and must be re-balanced after an insertion. Reference Red-Black Trees in a Functional Setting
#Bracmat
Bracmat
( ( balance = a x b y c zd .  !arg  : ( B . ( ( R . ((R.?a,?x,?b),?y,?c) | (?a,?x,(R.?b,?y,?c)) ) , ?zd ) | ( ?a , ?x , ( R . ((R.?b,?y,?c),?zd) | (?b,?y,(R.?c,?zd)) ) ) ) & (R.(B.!a,!x,!b),!y,(B.!c,!zd)) | !arg ) & ( ins = C X tree a m z .  !arg:(?X.?tree) & !tree:(?C.?a,?m,?z) & (  !X:<!m & balance$(!C.ins$(!X.!a),!m,!z) |  !X:>!m & balance$(!C.!a,!m,ins$(!X.!z)) | !tree ) | (R.,!X,) ) & ( insert = X tree .  !arg:(?X.?tree) & ins$(!X.!tree):(?.?X) & (B.!X) ) & ( insertMany = L R tree .  !arg:(%?L_%?R.?tree) & insertMany$(!L.!tree):?tree & insertMany$(!R.!tree) | insert$!arg ) );
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
#AWK
AWK
  # syntax: GAWK -f ALMOST_PRIME.AWK BEGIN { for (k=1; k<=5; k++) { printf("%d:",k) c = 0 i = 1 while (c < 10) { if (kprime(++i,k)) { printf(" %d",i) c++ } } printf("\n") } exit(0) } function kprime(n,k, f,p) { for (p=2; f<k && p*p<=n; p++) { while (n % p == 0) { n /= p f++ } } return(f + (n > 1) == k) }  
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
#ABAP
ABAP
report zz_anagrams no standard page heading. define update_progress. call function 'SAPGUI_PROGRESS_INDICATOR' exporting text = &1. end-of-definition.   " Selection screen segment allowing the person to choose which file will act as input. selection-screen begin of block file_choice. parameters p_file type string lower case. selection-screen end of block file_choice.   " When the user requests help with input, run the routine to allow them to navigate the presentation server. at selection-screen on value-request for p_file. perform getfile using p_file.   at selection-screen output. %_p_file_%_app_%-text = 'Input File: '.   start-of-selection. data: gt_data type table of string.   " Read the specified file from the presentation server into memory. perform readfile using p_file changing gt_data. " After the file has been read into memory, loop through it line-by-line and make anagrams. perform anagrams using gt_data.   " Subroutine for generating a list of anagrams. " The supplied input is a table, with each entry corresponding to a word. form anagrams using it_data like gt_data. types begin of ty_map. types key type string. types value type string. types end of ty_map.   data: lv_char type c, lv_len type i, lv_string type string, ls_entry type ty_map, lt_anagrams type standard table of ty_map, lt_c_tab type table of string.   field-symbols: <fs_raw> type string. " Loop through each word in the table, and make an associative array. loop at gt_data assigning <fs_raw>. " First, we need to re-order the word alphabetically. This generated a key. All anagrams will use this same key. " Add each character to a table, which we will then sort alphabetically. lv_len = strlen( <fs_raw> ). refresh lt_c_tab. do lv_len times. lv_len = sy-index - 1. append <fs_raw>+lv_len(1) to lt_c_tab. enddo. sort lt_c_tab as text. " Now append the characters to a string and add it as a key into the map. clear lv_string. loop at lt_c_tab into lv_char. concatenate lv_char lv_string into lv_string respecting blanks. endloop. ls_entry-key = lv_string. ls_entry-value = <fs_raw>. append ls_entry to lt_anagrams. endloop. " After we're done processing, output a list of the anagrams. clear lv_string. loop at lt_anagrams into ls_entry. " Is it part of the same key --> Output in the same line, else a new entry. if lv_string = ls_entry-key. write: ', ', ls_entry-value. else. if sy-tabix <> 1. write: ']'. endif. write: / '[', ls_entry-value. endif. lv_string = ls_entry-key. endloop. " Close last entry. write ']'. endform.   " Read a specified file from the presentation server. form readfile using i_file type string changing it_raw like gt_data. data: l_datat type string, l_msg(2048), l_lines(10).   " Read the file into memory. update_progress 'Reading file...'. call method cl_gui_frontend_services=>gui_upload exporting filename = i_file changing data_tab = it_raw exceptions others = 1. " Output error if the file could not be uploaded. if sy-subrc <> 0. write : / 'Error reading the supplied file!'. return. endif. endform.
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
#J
J
relativeBearing=: (180 -~ 360 | 180 + -~)/"1
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
#Lasso
Lasso
local( anagrams = map, words = include_url('http://www.puzzlers.org/pub/wordlists/unixdict.txt') -> split('\n'), key, max = 0, wordsize, findings = array, derangedtest = { // this code snippet is not executed until the variable is invoked. It will return true if the compared words are a deranged anagram local( w1 = #1, w2 = #2, testresult = true )   loop(#w1 -> size) => { #w1 -> get(loop_count) == #w2 -> get(loop_count) ? #testresult = false } return #testresult } )   // find all anagrams with word in #words do { #key = #word -> split('') -> sort& -> join('') not(#anagrams >> #key) ? #anagrams -> insert(#key = array) #anagrams -> find(#key) -> insert(#word) }   // step thru each set of anagrams to find deranged ones with ana in #anagrams let ana_size = #ana -> size where #ana_size > 1 do { #wordsize = #ana -> first -> size   if(#wordsize >= #max) => {   loop(#ana_size - 1) => { if(#derangedtest -> detach & invoke(#ana -> get(loop_count), #ana -> get(loop_count + 1))) => { // we only care to save the found deranged anagram if it is longer than the previous longest one if(#wordsize > #max) => { #findings = array(#ana -> get(loop_count) + ', ' + #ana -> get(loop_count + 1)) else #findings -> insert(#ana -> get(loop_count) + ', ' + #ana -> get(loop_count + 1)) } #max = #wordsize } }   } }   #findings -> join('<br />\n')
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.
#J
J
fibN=: (-&2 +&$: -&1)^:(1&<) M."0
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.
#F.23
F#
  [2..20000 - 1] |> List.map (fun n-> n, ([1..n/2] |> List.filter (fun x->n % x = 0) |> List.sum)) |> List.map (fun (a,b) ->if a<b then (a,b) else (b,a)) |> List.groupBy id |> List.map snd |> List.filter (List.length >> ((=) 2)) |> List.map List.head |> List.iter (printfn "%A")  
http://rosettacode.org/wiki/Animation
Animation
Animation is integral to many parts of GUIs, including both the fancy effects when things change used in window managers, and of course games.   The core of any animation system is a scheme for periodically changing the display while still remaining responsive to the user.   This task demonstrates this. Task Create a window containing the string "Hello World! " (the trailing space is significant). Make the text appear to be rotating right by periodically removing one letter from the end of the string and attaching it to the front. When the user clicks on the (windowed) text, it should reverse its direction.
#Oz
Oz
functor import Application QTk at 'x-oz://system/wp/QTk.ozf' define proc {Start} Label Window = {CreateWindow ?Label} Animation = {New LabelAnimation init(Label delay:125)} in {Window show} {Animation go} end   fun {CreateWindow ?Label} Courier = {QTk.newFont font(family:courier size:14)} GUI = td( title:"Basic Animation" label(text:"Hello World! " handle:Label font:Courier) action:proc {$} {Application.exit 0} end ) in {QTk.build GUI} end   class LabelAnimation from Time.repeat attr activeShifter:ShiftRight otherShifter:ShiftLeft feat label   meth init(Label delay:Delay<=100) self.label = Label {self setRepAll(action:Animate delay:Delay)} {Label bind(event:"<Button-1>" action:self#Revert)} end   meth Animate OldText = {self.label get(text:$)} NewText = {@activeShifter OldText} in {self.label set(text:NewText)} end   meth Revert otherShifter := (activeShifter := @otherShifter) end end   fun {ShiftRight Xs} {List.last Xs}|{List.take Xs {Length Xs}-1} end   fun {ShiftLeft Xs} {Append Xs.2 [Xs.1]} end   {Start} 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.
#HicEst
HicEst
REAL :: msec=10, Lrod=1, dBob=0.03, g=9.81, Theta(2), dTheta(2) BobMargins = ALIAS(ls, rs, ts, bs) ! box margins to draw the bob     Theta = (1, 0) ! initial angle and velocity start_t = TIME()   DO i = 1, 1E100 ! "forever" end_t = TIME() ! to integrate in real-time sections: DIFFEQ(Callback="pendulum", T=end_t, Y=Theta, DY=dTheta, T0=start_t) xBob = (SIN(Theta(1)) + 1) / 2 yBob = COS(Theta(1)) - dBob   ! create or clear window and draw pendulum bob at (xBob, yBob): WINDOW(WIN=wh, LeftSpace=0, RightSpace=0, TopSpace=0, BottomSpace=0, Up=999) BobMargins = (xBob-dBob, 1-xBob-dBob, yBob-dBob, 1-yBob-dBob) WINDOW(WIN=wh, LeftSpace=ls, RightSpace=rs, TopSpace=ts, BottomSpace=bs) WRITE(WIN=wh, DeCoRation='EL=4, BC=4') ! flooded red ellipse as bob   ! draw the rod hanging from the center of the window: WINDOW(WIN=wh, LeftSpace=0.5, TopSpace=0, RightSpace=rs+dBob) WRITE(WIN=wh, DeCoRation='LI=0 0; 1 1, FC=4.02') ! red pendulum rod   SYSTEM(WAIT=msec) start_t = end_t ENDDO   END   SUBROUTINE pendulum ! Theta" = - (g/Lrod) * SIN(Theta) dTheta(1) = Theta(2) ! Theta' = Theta(2) substitution dTheta(2) = -g/Lrod*SIN(Theta(1)) ! Theta" = Theta(2)' = -g/Lrod*SIN(Theta(1)) END
http://rosettacode.org/wiki/Almkvist-Giullera_formula_for_pi
Almkvist-Giullera formula for pi
The Almkvist-Giullera formula for calculating   1/π2   is based on the Calabi-Yau differential equations of order 4 and 5,   which were originally used to describe certain manifolds in string theory. The formula is: 1/π2 = (25/3) ∑0∞ ((6n)! / (n!6))(532n2 + 126n + 9) / 10002n+1 This formula can be used to calculate the constant   π-2,   and thus to calculate   π. Note that, because the product of all terms but the power of 1000 can be calculated as an integer, the terms in the series can be separated into a large integer term: (25) (6n)! (532n2 + 126n + 9) / (3(n!)6)     (***) multiplied by a negative integer power of 10: 10-(6n + 3) Task Print the integer portions (the starred formula, which is without the power of 1000 divisor) of the first 10 terms of the series. Use the complete formula to calculate and print π to 70 decimal digits of precision. Reference  Gert Almkvist and Jesús Guillera, Ramanujan-like series for 1/π2 and string theory, Experimental Mathematics, 21 (2012), page 2, formula 1.
#Quackery
Quackery
[ $ "bigrat.qky" loadfile ] now!   [ 1 swap times [ i^ 1+ * ] ] is ! ( n --> n )   [ dup dup 2 ** 532 * over 126 * + 9 + swap 6 * ! * 32 * swap ! 6 ** 3 * / ] is intterm ( n --> n )   [ dup intterm 10 rot 6 * 3 + ** reduce ] is vterm ( n --> n/d )   10 times [ i^ intterm echo cr ] cr   0 n->v 53 times [ i^ vterm v+ ] 1/v 70 vsqrt drop 70 point$ echo$ cr
http://rosettacode.org/wiki/Almkvist-Giullera_formula_for_pi
Almkvist-Giullera formula for pi
The Almkvist-Giullera formula for calculating   1/π2   is based on the Calabi-Yau differential equations of order 4 and 5,   which were originally used to describe certain manifolds in string theory. The formula is: 1/π2 = (25/3) ∑0∞ ((6n)! / (n!6))(532n2 + 126n + 9) / 10002n+1 This formula can be used to calculate the constant   π-2,   and thus to calculate   π. Note that, because the product of all terms but the power of 1000 can be calculated as an integer, the terms in the series can be separated into a large integer term: (25) (6n)! (532n2 + 126n + 9) / (3(n!)6)     (***) multiplied by a negative integer power of 10: 10-(6n + 3) Task Print the integer portions (the starred formula, which is without the power of 1000 divisor) of the first 10 terms of the series. Use the complete formula to calculate and print π to 70 decimal digits of precision. Reference  Gert Almkvist and Jesús Guillera, Ramanujan-like series for 1/π2 and string theory, Experimental Mathematics, 21 (2012), page 2, formula 1.
#Raku
Raku
# 20201013 Raku programming solution   use BigRoot; use Rat::Precise; use experimental :cached;   BigRoot.precision = 75 ; my $Precision = 70 ; my $AGcache = 0 ;   sub postfix:<!>(Int $n --> Int) is cached { [*] 1 .. $n }   sub Integral(Int $n --> Int) is cached { (2⁵*(6*$n)! * (532*$n² + 126*$n + 9)) div (3*($n!)⁶) }   sub A-G(Int $n --> FatRat) is cached { # Almkvist-Giullera Integral($n).FatRat / (10**(6*$n + 3)).FatRat }   sub Pi(Int $n --> Str) { (1/(BigRoot.newton's-sqrt: $AGcache += A-G $n)).precise($Precision) }   say "First 10 integer portions : "; say $_, "\t", Integral $_ for ^10;   my $target = Pi my $Nth = 0;   loop { $target eq ( my $next = Pi ++$Nth ) ?? ( last ) !! $target = $next }   say "π to $Precision decimal places is :\n$target"
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.
#Ada
Ada
with Ada.Strings.Unbounded; use Ada.Strings.Unbounded; with Ada.Text_IO; use Ada.Text_IO;   procedure Test_Amb is type Alternatives is array (Positive range <>) of Unbounded_String;   type Amb (Count : Positive) is record This : Positive := 1; Left : access Amb; List : Alternatives (1..Count); end record;   function Image (L : Amb) return String is begin return To_String (L.List (L.This)); end Image;   function "/" (L, R : String) return Amb is Result : Amb (2); begin Append (Result.List (1), L); Append (Result.List (2), R); return Result; end "/";   function "/" (L : Amb; R : String) return Amb is Result : Amb (L.Count + 1); begin Result.List (1..L.Count) := L.List ; Append (Result.List (Result.Count), R); return Result; end "/";   function "=" (L, R : Amb) return Boolean is Left : Unbounded_String renames L.List (L.This); begin return Element (Left, Length (Left)) = Element (R.List (R.This), 1); end "=";   procedure Failure (L : in out Amb) is begin loop if L.This < L.Count then L.This := L.This + 1; else L.This := 1; Failure (L.Left.all); end if; exit when L.Left = null or else L.Left.all = L; end loop; end Failure;   procedure Join (L : access Amb; R : in out Amb) is begin R.Left := L; while L.all /= R loop Failure (R); end loop; end Join;   W_1 : aliased Amb := "the" / "that" / "a"; W_2 : aliased Amb := "frog" / "elephant" / "thing"; W_3 : aliased Amb := "walked" / "treaded" / "grows"; W_4 : aliased Amb := "slowly" / "quickly"; begin Join (W_1'Access, W_2); Join (W_2'Access, W_3); Join (W_3'Access, W_4); Put_Line (Image (W_1) & ' ' & Image (W_2) & ' ' & Image (W_3) & ' ' & Image (W_4)); end Test_Amb;
http://rosettacode.org/wiki/Algebraic_data_types
Algebraic data types
Some languages offer direct support for algebraic data types and pattern matching on them. While this of course can always be simulated with manual tagging and conditionals, it allows for terse code which is easy to read, and can represent the algorithm directly. Task As an example, implement insertion in a red-black-tree. A red-black-tree is a binary tree where each internal node has a color attribute red or black. Moreover, no red node can have a red child, and every path from the root to an empty node must contain the same number of black nodes. As a consequence, the tree is balanced, and must be re-balanced after an insertion. Reference Red-Black Trees in a Functional Setting
#C.2B.2B
C++
enum Color { R, B }; template<Color, class, auto, class> struct T; struct E;   template<Color col, class a, auto x, class b> struct balance { using type = T<col, a, x, b>; }; template<class a, auto x, class b, auto y, class c, auto z, class d> struct balance<B, T<R, T<R, a, x, b>, y, c>, z, d> { using type = T<R, T<B, a, x, b>, y, T<B, c, z, d>>; }; template<class a, auto x, class b, auto y, class c, auto z, class d> struct balance<B, T<R, a, x, T<R, b, y, c>>, z, d> { using type = T<R, T<B, a, x, b>, y, T<B, c, z, d>>; }; template<class a, auto x, class b, auto y, class c, auto z, class d> struct balance<B, a, x, T<R, T<R, b, y, c>, z, d>> { using type = T<R, T<B, a, x, b>, y, T<B, c, z, d>>; }; template<class a, auto x, class b, auto y, class c, auto z, class d> struct balance<B, a, x, T<R, b, y, T<R, c, z, d>>> { using type = T<R, T<B, a, x, b>, y, T<B, c, z, d>>; };   template<auto x, class s> struct insert { template<class, class = void> struct ins; template<class _> struct ins<E, _> { using type = T<R, E, x, E>; }; template<Color col, class a, auto y, class b> struct ins<T<col, a, y, b>> { template<int, class = void> struct cond; template<class _> struct cond<-1, _> : balance<col, typename ins<a>::type, y, b> {}; template<class _> struct cond<1, _> : balance<col, a, y, typename ins<b>::type> {}; template<class _> struct cond<0, _> { using type = T<col, a, y, b>; }; using type = typename cond<x < y ? -1 : y < x ? 1 : 0>::type; }; template<class> struct repaint; template<Color col, class a, auto y, class b> struct repaint<T<col, a, y, b>> { using type = T<B, a, y, b>; }; using type = typename repaint<typename ins<s>::type>::type; }; template<auto x, class s> using insert_t = typename insert<x, s>::type;   template<class> void print(); int main() { print<insert_t<1, insert_t<2, insert_t<0, insert_t<4, E>>>>>(); }
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
#BASIC
BASIC
10 DEFINT A-Z 20 FOR K=1 TO 5 30 PRINT USING "K = #:";K; 40 I=2: C=0 50 F=0: P=2: N=I 60 IF F >= K OR P*P > N THEN 100 70 IF N MOD P = 0 THEN N = N/P: F = F+1: GOTO 70 80 P = P+1 90 GOTO 60 100 IF N > 1 THEN F = F+1 110 IF F = K THEN C = C+1: PRINT USING " ###";I; 120 I = I+1 130 IF C < 10 THEN 50 140 PRINT 150 NEXT K
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
#BASIC256
BASIC256
function kPrime(n, k) f = 0 for i = 2 to n while n mod i = 0 if f = k then return False f += 1 n /= i end while next i return f = k end function   for k = 1 to 5 print "k = "; k; " :"; i = 2 c = 0 while c < 10 if kPrime(i, k) then print rjust (string(i), 4); c += 1 end if i += 1 end while print next k end
http://rosettacode.org/wiki/Anagrams
Anagrams
When two or more words are composed of the same characters, but in a different order, they are called anagrams. Task[edit] Using the word list at   http://wiki.puzzlers.org/pub/wordlists/unixdict.txt, find the sets of words that share the same characters that contain the most words in them. Related tasks Word plays Ordered words Palindrome detection Semordnilap Anagrams Anagrams/Deranged anagrams Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#Ada
Ada
with Ada.Text_IO; use Ada.Text_IO;   with Ada.Containers.Indefinite_Ordered_Maps; with Ada.Containers.Indefinite_Ordered_Sets;   procedure Words_Of_Equal_Characters is package Set_Of_Words is new Ada.Containers.Indefinite_Ordered_Sets (String); use Ada.Containers, Set_Of_Words; package Anagrams is new Ada.Containers.Indefinite_Ordered_Maps (String, Set); use Anagrams;   File  : File_Type; Result : Map; Max  : Count_Type := 1;   procedure Put (Position : Anagrams.Cursor) is First : Boolean := True; List  : Set renames Element (Position); procedure Put (Position : Set_Of_Words.Cursor) is begin if First then First := False; else Put (','); end if; Put (Element (Position)); end Put; begin if List.Length = Max then Iterate (List, Put'Access); New_Line; end if; end Put;   begin Open (File, In_File, "unixdict.txt"); loop declare Word : constant String  := Get_Line (File); Key  : String (Word'Range) := (others => Character'Last); List : Set; Position : Anagrams.Cursor; begin for I in Word'Range loop for J in Word'Range loop if Key (J) > Word (I) then Key (J + 1..I) := Key (J..I - 1); Key (J) := Word (I); exit; end if; end loop; end loop; Position := Find (Result, Key); if Has_Element (Position) then List := Element (Position); Insert (List, Word); Replace_Element (Result, Position, List); else Insert (List, Word); Include (Result, Key, List); end if; Max := Count_Type'Max (Max, Length (List)); end; end loop; exception when End_Error => Iterate (Result, Put'Access); Close (File); end Words_Of_Equal_Characters;
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
#Java
Java
public class AngleDifference {   public static double getDifference(double b1, double b2) { double r = (b2 - b1) % 360.0; if (r < -180.0) r += 360.0; if (r >= 180.0) r -= 360.0; return r; }   public static void main(String[] args) { System.out.println("Input in -180 to +180 range"); System.out.println(getDifference(20.0, 45.0)); System.out.println(getDifference(-45.0, 45.0)); System.out.println(getDifference(-85.0, 90.0)); System.out.println(getDifference(-95.0, 90.0)); System.out.println(getDifference(-45.0, 125.0)); System.out.println(getDifference(-45.0, 145.0)); System.out.println(getDifference(-45.0, 125.0)); System.out.println(getDifference(-45.0, 145.0)); System.out.println(getDifference(29.4803, -88.6381)); System.out.println(getDifference(-78.3251, -159.036));   System.out.println("Input in wider range"); System.out.println(getDifference(-70099.74233810938, 29840.67437876723)); System.out.println(getDifference(-165313.6666297357, 33693.9894517456)); System.out.println(getDifference(1174.8380510598456, -154146.66490124757)); System.out.println(getDifference(60175.77306795546, 42213.07192354373)); } }
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
#Liberty_BASIC
Liberty BASIC
print "Loading dictionary file." open "unixdict.txt" for input as #1 a$=input$(#1,lof(#1)) close #1   dim theWord$(30000) dim ssWord$(30000)   c10$ = chr$(10) i = 1 print "Creating array of words." while instr(a$,c10$,i) <> 0 j = instr(a$,c10$,i) ln = j - i again = 1 sWord$ = mid$(a$,i,j-i) n = n + 1 theWord$(n) = sWord$   while again = 1 again = 0 for kk = 1 to len(sWord$) - 1 if mid$(sWord$,kk,1) > mid$(sWord$,kk +1,1) then sWord$ = left$(sWord$,kk-1);mid$(sWord$,kk+1,1);mid$(sWord$,kk,1);mid$(sWord$,kk+2) again = 1 end if next kk wend ssWord$(n) = sWord$ i = j + 1 wend print "Checking for deranged anagrams." for i = 1 to n if len(theWord$(i)) > maxLen then for j = 1 to n if ssWord$(i) = ssWord$(j) and i <> j then cnt = 0 for k = 1 to len(theWord$(i)) if mid$(theWord$(i),k,1) = mid$(theWord$(j),k,1) then cnt = cnt + 1 next k if cnt = 0 then maxLen = len(theWord$(i)) maxPtrI = i maxPtrJ = j end if end if next j end if next i   print theWord$(maxPtrI);" => ";theWord$(maxPtrJ) end
http://rosettacode.org/wiki/Anonymous_recursion
Anonymous recursion
While implementing a recursive function, it often happens that we must resort to a separate   helper function   to handle the actual recursion. This is usually the case when directly calling the current function would waste too many resources (stack space, execution time), causing unwanted side-effects,   and/or the function doesn't have the right arguments and/or return values. So we end up inventing some silly name like   foo2   or   foo_helper.   I have always found it painful to come up with a proper name, and see some disadvantages:   You have to think up a name, which then pollutes the namespace   Function is created which is called from nowhere else   The program flow in the source code is interrupted Some languages allow you to embed recursion directly in-place.   This might work via a label, a local gosub instruction, or some special keyword. Anonymous recursion can also be accomplished using the   Y combinator. Task If possible, demonstrate this by writing the recursive version of the fibonacci function   (see Fibonacci sequence)   which checks for a negative argument before doing the actual recursion.
#Java
Java
public static long fib(int n) { if (n < 0) throw new IllegalArgumentException("n can not be a negative number");   return new Object() { private long fibInner(int n) { return (n < 2) ? n : (fibInner(n - 1) + fibInner(n - 2)); } }.fibInner(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.
#Factor
Factor
  USING: grouping math.primes.factors math.ranges ;   : pdivs ( n -- seq ) divisors but-last ; : dsum ( n -- sum ) pdivs sum ; : dsum= ( n m -- ? ) dsum = ; : both-dsum= ( n m -- ? ) [ dsum= ] [ swap dsum= ] 2bi and ; : amicable? ( n m -- ? ) [ both-dsum= ] [ = not ] 2bi and ; : drange ( -- seq ) 2 20000 [a,b) ; : dsums ( -- seq ) drange [ dsum ] map ; : is-am?-seq ( -- seq ) dsums drange [ amicable? ] 2map ; : am-nums ( -- seq ) t is-am?-seq indices ; : am-nums-c ( -- seq ) am-nums [ 2 + ] map ; : am-pairs ( -- seq ) am-nums-c 2 group ; : print-am ( -- ) am-pairs [ >array . ] each ;   print-am  
http://rosettacode.org/wiki/Animation
Animation
Animation is integral to many parts of GUIs, including both the fancy effects when things change used in window managers, and of course games.   The core of any animation system is a scheme for periodically changing the display while still remaining responsive to the user.   This task demonstrates this. Task Create a window containing the string "Hello World! " (the trailing space is significant). Make the text appear to be rotating right by periodically removing one letter from the end of the string and attaching it to the front. When the user clicks on the (windowed) text, it should reverse its direction.
#Pascal
Pascal
program HelloWorldAnimatedGUI;   uses {$IFDEF UNIX} {$IFDEF UseCThreads} cthreads, {$ENDIF} {$ENDIF} Interfaces, // this includes the LCL widgetset Forms, Classes, Controls, StdCtrls, ExtCtrls;   type { TFrmHelloWorldAnim } TFrmHelloWorldAnim = class(TForm) constructor CreateNew(AOwner: TComponent; Num: integer = 0); override; procedure lblTextAnimateClick(Sender: TObject); procedure tmrAnimateTimer(Sender: TObject); private { private declarations } lblTextAnimate: TLabel; tmrAnimate: TTimer; FDirection: boolean; public { public declarations } end;   var FrmHelloWorldAnim: TFrmHelloWorldAnim;   { TFrmHelloWorldAnim }   constructor TFrmHelloWorldAnim.CreateNew(AOwner: TComponent; Num: integer); begin inherited CreateNew(AOwner, Num); Height := 50; lblTextAnimate := TLabel.Create(self); with lblTextAnimate do begin Caption := 'Hello World! '; Align := alClient; Alignment := taCenter; font.Name := 'Courier New'; font.size := 20; OnClick := @lblTextAnimateClick; Parent := self; end; tmrAnimate := TTimer.Create(self); with tmrAnimate do begin Interval := 100; OnTimer := @tmrAnimateTimer; end; end;   procedure TFrmHelloWorldAnim.lblTextAnimateClick(Sender: TObject); begin FDirection := not FDirection; end;   procedure TFrmHelloWorldAnim.tmrAnimateTimer(Sender: TObject); begin if FDirection then lblTextAnimate.Caption := copy(lblTextAnimate.Caption, length(lblTextAnimate.Caption), 1) + copy(lblTextAnimate.Caption, 1, length(lblTextAnimate.Caption) - 1) else lblTextAnimate.Caption := copy(lblTextAnimate.Caption, 2, length(lblTextAnimate.Caption) - 1) + copy(lblTextAnimate.Caption, 1, 1); end;   begin RequireDerivedFormResource := False; Application.Initialize; Application.CreateForm(TFrmHelloWorldAnim, FrmHelloWorldAnim); Application.Run; 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.
#Icon_and_Unicon
Icon and Unicon
  import gui $include "guih.icn"   # some constants to define the display and pendulum $define HEIGHT 400 $define WIDTH 500 $define STRING_LENGTH 200 $define HOME_X 250 $define HOME_Y 21 $define SIZE 30 $define START_ANGLE 80   class WindowApp : Dialog ()   # draw the pendulum on given context_window, at position (x,y) method draw_pendulum (x, y) # reference to current screen area to draw on cw := Clone(self.cwin)   # clear screen WAttrib (cw, "bg=grey") EraseRectangle (cw, 0, 0, WIDTH, HEIGHT)   # draw the display WAttrib (cw, "fg=dark gray") DrawLine (cw, 10, 20, WIDTH-20, 20) WAttrib (cw, "fg=black") DrawLine (cw, HOME_X, HOME_Y, x, y) FillCircle (cw, x, y, SIZE+2) WAttrib (cw, "fg=yellow") FillCircle (cw, x, y, SIZE)   # free reference to screen area Uncouple (cw) end   # find the average of given two arguments method avg (a, b) return (a + b) / 2 end   # this method gets called by the ticker # it computes the next position of the pendulum and # requests a redraw method tick () static x, y static theta := START_ANGLE static d_theta := 0 # update x,y of pendulum scaling := 3000.0 / (STRING_LENGTH * STRING_LENGTH) # -- first estimate first_dd_theta := -(sin (dtor (theta)) * scaling) mid_d_theta := d_theta + first_dd_theta mid_theta := theta + avg (d_theta, mid_d_theta) # -- second estimate mid_dd_theta := - (sin (dtor (mid_theta)) * 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 (dtor (mid_theta_2)) * 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 (dtor (last_theta)) * 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) # -- update stored angles d_theta := last_d_theta_2 theta := last_theta_2 # -- update x, y pendulum_angle := dtor (theta) x := HOME_X + STRING_LENGTH * sin (pendulum_angle) y := HOME_Y + STRING_LENGTH * cos (pendulum_angle)   # draw pendulum draw_pendulum (x, y) end   # set up the window method component_setup () # some cosmetic settings for the window attrib("size="||WIDTH||","||HEIGHT, "bg=light gray", "label=Pendulum") # make sure we respond to window close event connect (self, "dispose", CLOSE_BUTTON_EVENT) # start the ticker, to update the display periodically self.set_ticker (20) end end   procedure main () w := WindowApp () w.show_modal () end  
http://rosettacode.org/wiki/Almkvist-Giullera_formula_for_pi
Almkvist-Giullera formula for pi
The Almkvist-Giullera formula for calculating   1/π2   is based on the Calabi-Yau differential equations of order 4 and 5,   which were originally used to describe certain manifolds in string theory. The formula is: 1/π2 = (25/3) ∑0∞ ((6n)! / (n!6))(532n2 + 126n + 9) / 10002n+1 This formula can be used to calculate the constant   π-2,   and thus to calculate   π. Note that, because the product of all terms but the power of 1000 can be calculated as an integer, the terms in the series can be separated into a large integer term: (25) (6n)! (532n2 + 126n + 9) / (3(n!)6)     (***) multiplied by a negative integer power of 10: 10-(6n + 3) Task Print the integer portions (the starred formula, which is without the power of 1000 divisor) of the first 10 terms of the series. Use the complete formula to calculate and print π to 70 decimal digits of precision. Reference  Gert Almkvist and Jesús Guillera, Ramanujan-like series for 1/π2 and string theory, Experimental Mathematics, 21 (2012), page 2, formula 1.
#REXX
REXX
/*REXX program uses the Almkvist─Giullera formula for 1 / (pi**2) [or pi ** -2]. */ numeric digits length( pi() ) + length(.); w= 102 say $( , 3) $( , w%2) $('power', 5) $( , w) say $('N', 3) $('integer term', w%2) $('of 10', 5) $('Nth term', w) say $( , 3, "─") $( , w%2, "─") $( , 5, "─") $( , w, "─") s= 0 /*initialize S (the sum) to zero. */ do n=0 until old=s; old= s /*use the "older" value of S for OLD.*/ a= 2**5 *  !(6*n) * (532 * n**2 + 126*n + 9) / (3 * !(n)**6) z= 10 ** (- (6*n + 3) ) s= s + a * z if n>10 then do; do 3*(n==11); say ' .'; end; iterate; end say $(n, 3) right(a, w%2) $(powX(z), 5) right( lowE( format(a*z, 1, w-6, 2, 0)), w) end /*n*/ say say 'The calculation of pi took ' n " iterations with " digits() , " decimal digits precision using" subword( sourceLine(1), 4, 3). say numeric digits length( pi() ) - length(.); d= digits() - length(.); @= ' ↓↓↓ ' say center(@ 'calculated pi to ' d " fractional decimal digits (below) is "@, d+4, '─') say ' 'sqrt(1/s); say say ' 'pi(); @= ' ↑↑↑ ' say center(@ 'the true pi to ' d " fractional decimal digits (above) is" @, d+4, '─') exit 0 /*stick a fork in it, we're all done. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ $: procedure; parse arg text,width,fill; return center(text, width, left(fill, 1) ) !: procedure; parse arg x; !=1;; do j=2 to x;  != !*j; end; return ! lowE: procedure; parse arg x; return translate(x, 'e', "E") powX: procedure; parse arg p; return right( format( p, 1, 3, 2, 0), 3) + 0 /*──────────────────────────────────────────────────────────────────────────────────────*/ pi: pi=3.141592653589793238462643383279502884197169399375105820974944592307816406286208, ||9986280348253421170679821480865132823066470938446095505822317253594081284811174503 return pi /*──────────────────────────────────────────────────────────────────────────────────────*/ sqrt: procedure; parse arg x; if x=0 then return 0; d=digits(); numeric digits; h=d+6 m.=9; numeric form; parse value format(x,2,1,,0) 'E0' with g 'E' _ .; g=g*.5'e'_ % 2 do j=0 while h>9; m.j= h; h= h % 2 + 1; end /*j*/ do k=j+5 to 0 by -1; numeric digits m.k; g= (g + x/g) * .5; end /*k*/ numeric digits d; return g/1
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.
#ALGOL_68
ALGOL 68
MODE PAGE = FLEX[0]STRING; MODE YIELDPAGE = PROC(PAGE)VOID; MODE ITERPAGE = PROC(YIELDPAGE)VOID;   OP INITITERPAGE = (PAGE self)ITERPAGE: (YIELDPAGE yield)VOID: # scope violation # FOR i TO UPB self DO yield(self[i]) OD;   OP + = (ITERPAGE for strings, PAGE b)ITERPAGE: (YIELDPAGE yield)VOID: # scope violation # for strings((PAGE amb)VOID:( [UPB amb + 1]STRING joined; joined[:UPB amb] := amb; STRING last string := amb[UPB amb]; CHAR last char := last string[UPB last string]; FOR i TO UPB b DO IF last char = b[i][1] THEN joined[UPB joined] := b[i]; yield(joined) FI OD ));   OP + = (PAGE a, PAGE b)ITERPAGE: INITITERPAGE a + b;   ITERPAGE gen amb := PAGE("the", "that", "a") + PAGE("frog", "elephant", "thing") + PAGE("walked", "treaded", "grows") + PAGE("slowly", "quickly");   PAGE sep; #FOR PAGE amb IN # gen amb( # ) DO # ## (PAGE amb)VOID: print((amb[1]+" "+amb[2]+" "+amb[3]+" "+amb[4], new line)) #OD# )
http://rosettacode.org/wiki/Algebraic_data_types
Algebraic data types
Some languages offer direct support for algebraic data types and pattern matching on them. While this of course can always be simulated with manual tagging and conditionals, it allows for terse code which is easy to read, and can represent the algorithm directly. Task As an example, implement insertion in a red-black-tree. A red-black-tree is a binary tree where each internal node has a color attribute red or black. Moreover, no red node can have a red child, and every path from the root to an empty node must contain the same number of black nodes. As a consequence, the tree is balanced, and must be re-balanced after an insertion. Reference Red-Black Trees in a Functional Setting
#C.23
C#
using System;   class Tree { public static void Main() { Tree tree = Tree.E; for (int i = 1; i <= 16; i++) { tree = tree.Insert(i); } tree.Print(); }   private const bool B = false, R = true; public static readonly Tree E = new Tree(B, null, 0, null);   private Tree(bool c, Tree? l, int v, Tree? r) => (IsRed, Left, Value, Right) = (c, l ?? this, v, r ?? this);   public bool IsRed { get; private set; } public int Value { get; } public Tree Left { get; } public Tree Right { get; }   public static implicit operator Tree((bool c, Tree l, int v, Tree r) t) => new Tree(t.c, t.l, t.v, t.r); public void Deconstruct(out bool c, out Tree l, out int v, out Tree r) => (c, l, v, r) = (IsRed, Left, Value, Right); public override string ToString() => this == E ? "[]" : $"[{(IsRed ? 'R' : 'B')}{Value}]"; public Tree Insert(int x) => Ins(x).MakeBlack(); private Tree MakeBlack() { IsRed = false; return this; }   public void Print(int indent = 0) { if (this != E) Right.Print(indent + 1); Console.WriteLine(new string(' ', indent * 4) + ToString()); if (this != E) Left.Print(indent + 1); }   private Tree Ins(int x) => Math.Sign(x.CompareTo(Value)) switch { _ when this == E => (R, E, x, E), -1 => new Tree(IsRed, Left.Ins(x) , Value, Right).Balance(), 1 => new Tree(IsRed, Left , Value, Right.Ins(x)).Balance(), _ => this };   private Tree Balance() => this switch { (B, (R, (R, var a, var x, var b), var y, var c), var z, var d) => (R, (B, a, x, b), y, (B, c, z, d)), (B, (R, var a, var x, (R, var b, var y, var c)), var z, var d) => (R, (B, a, x, b), y, (B, c, z, d)), (B, var a, var x, (R, (R, var b, var y, var c), var z, var d)) => (R, (B, a, x, b), y, (B, c, z, d)), (B, var a, var x, (R, var b, var y, (R, var c, var z, var d))) => (R, (B, a, x, b), y, (B, c, z, d)), _ => this }; }
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
#BCPL
BCPL
get "libhdr"   let kprime(n, k) = valof $( let f, p = 0, 2 while f<k & p*p<=n do $( while n rem p = 0 do $( n := n/p f := f+1 $) p := p+1 $) if n > 1 then f := f + 1 resultis f = k $)   let start() be $( for k=1 to 5 do $( let i, c = 2, 0 writef("k = %N:", k) while c < 10 do $( if kprime(i, k) then $( writed(i, 4) c := c+1 $) i := i+1 $) wrch('*N') $) $)
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
#Befunge
Befunge
1>::48*"= k",,,,02p.":",01v |^ v0!`\*:g40:<p402p300:+1< K| >2g03g`*#v_ 1`03g+02g->| F@>/03g1+03p>vpv+1\.:,*48 < P#|!\g40%g40:<4>:9`>#v_\1^| |^>#!1#`+#50#:^#+1,+5>#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
#ALGOL_68
ALGOL 68
# find longest list(s) of words that are anagrams in a list of words # # use the associative array in the Associate array/iteration task # PR read "aArray.a68" PR   # returns the number of occurances of ch in text # PROC count = ( STRING text, CHAR ch )INT: BEGIN INT result := 0; FOR c FROM LWB text TO UPB text DO IF text[ c ] = ch THEN result +:= 1 FI OD; result END # count # ;   # returns text with the characters sorted into ascending order # PROC char sort = ( STRING text )STRING: BEGIN STRING sorted := text; FOR end pos FROM UPB sorted - 1 BY -1 TO LWB sorted WHILE BOOL swapped := FALSE; FOR pos FROM LWB sorted TO end pos DO IF sorted[ pos ] > sorted[ pos + 1 ] THEN CHAR t := sorted[ pos ]; sorted[ pos ] := sorted[ pos + 1 ]; sorted[ pos + 1 ] := t; swapped := TRUE FI OD; swapped DO SKIP OD; sorted END # char sort # ;   # read the list of words and store in an associative array #   CHAR separator = "|"; # character that will separate the anagrams #   IF FILE input file; STRING file name = "unixdict.txt"; open( input file, file name, stand in channel ) /= 0 THEN # failed to open the file # print( ( "Unable to open """ + file name + """", newline ) ) ELSE # file opened OK # BOOL at eof := FALSE; # set the EOF handler for the file # on logical file end( input file, ( REF FILE f )BOOL: BEGIN # note that we reached EOF on the # # latest read # at eof := TRUE; # return TRUE so processing can continue # TRUE END ); REF AARRAY words := INIT LOC AARRAY; STRING word; WHILE NOT at eof DO STRING word; get( input file, ( word, newline ) ); words // char sort( word ) +:= separator + word OD; # close the file # close( input file );   # find the maximum number of anagrams #   INT max anagrams := 0;   REF AAELEMENT e := FIRST words; WHILE e ISNT nil element DO IF INT anagrams := count( value OF e, separator ); anagrams > max anagrams THEN max anagrams := anagrams FI; e := NEXT words OD;   print( ( "Maximum number of anagrams: ", whole( max anagrams, -4 ), newline ) ); # show the anagrams with the maximum number # e := FIRST words; WHILE e ISNT nil element DO IF INT anagrams := count( value OF e, separator ); anagrams = max anagrams THEN print( ( ( value OF e )[ ( LWB value OF e ) + 1: ], newline ) ) FI; e := NEXT words OD FI
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
#JavaScript
JavaScript
function relativeBearing(b1Rad, b2Rad) { b1y = Math.cos(b1Rad); b1x = Math.sin(b1Rad); b2y = Math.cos(b2Rad); b2x = Math.sin(b2Rad); crossp = b1y * b2x - b2y * b1x; dotp = b1x * b2x + b1y * b2y; if(crossp > 0.) return Math.acos(dotp); return -Math.acos(dotp); }   function test() { var deg2rad = 3.14159265/180.0; var rad2deg = 180.0/3.14159265; return "Input in -180 to +180 range\n" +relativeBearing(20.0*deg2rad, 45.0*deg2rad)*rad2deg+"\n" +relativeBearing(-45.0*deg2rad, 45.0*deg2rad)*rad2deg+"\n" +relativeBearing(-85.0*deg2rad, 90.0*deg2rad)*rad2deg+"\n" +relativeBearing(-95.0*deg2rad, 90.0*deg2rad)*rad2deg+"\n" +relativeBearing(-45.0*deg2rad, 125.0*deg2rad)*rad2deg+"\n" +relativeBearing(-45.0*deg2rad, 145.0*deg2rad)*rad2deg+"\n"   +relativeBearing(29.4803*deg2rad, -88.6381*deg2rad)*rad2deg+"\n" +relativeBearing(-78.3251*deg2rad, -159.036*deg2rad)*rad2deg+"\n"   + "Input in wider range\n" +relativeBearing(-70099.74233810938*deg2rad, 29840.67437876723*deg2rad)*rad2deg+"\n" +relativeBearing(-165313.6666297357*deg2rad, 33693.9894517456*deg2rad)*rad2deg+"\n" +relativeBearing(1174.8380510598456*deg2rad, -154146.66490124757*deg2rad)*rad2deg+"\n" +relativeBearing(60175.77306795546*deg2rad, 42213.07192354373*deg2rad)*rad2deg+"\n";   }
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
#Lua
Lua
string.tacnoc = function(str) -- 'inverse' of table.concat local arr={} for ch in str:gmatch(".") do arr[#arr+1]=ch end return arr end   local function deranged(s1, s2) if s1==s2 then return false end local t1, t2 = s1:tacnoc(), s2:tacnoc() for i,v in ipairs(t1) do if t2[i]==v then return false end end return true end   local dict = {} local f = io.open("unixdict.txt", "r") for word in f:lines() do local ltrs = word:tacnoc() table.sort(ltrs) local hash = table.concat(ltrs) dict[hash] = dict[hash] or {} table.insert(dict[hash], word) end   local answer = { word="", anag="", len=0 } for _,list in pairs(dict) do if #list>1 and #list[1]>answer.len then for _,word in ipairs(list) do for _,anag in ipairs(list) do if deranged(word, anag) then answer.word, answer.anag, answer.len = word, anag, #word end end end end end print(answer.word, answer.anag, answer.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.
#JavaScript
JavaScript
function fibo(n) { if (n < 0) { throw "Argument cannot be negative"; }   return (function(n) { return (n < 2) ? 1 : arguments.callee(n-1) + arguments.callee(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.
#Forth
Forth
: proper-divisors ( n -- 1..n ) dup 2 / 1+ 1 ?do dup i mod 0= if i swap then loop drop ;   : divisors-sum ( 1..n -- n ) dup 1 = if exit then begin over + swap 1 = until ;   : pair ( n -- n ) dup 1 = if exit then proper-divisors divisors-sum ;   : ?paired ( n -- t | f ) dup pair 2dup pair = >r < r> and ;   : amicable-list 1+ 1 do i ?paired if cr i . i pair . then loop ;   20000 amicable-list
http://rosettacode.org/wiki/Animation
Animation
Animation is integral to many parts of GUIs, including both the fancy effects when things change used in window managers, and of course games.   The core of any animation system is a scheme for periodically changing the display while still remaining responsive to the user.   This task demonstrates this. Task Create a window containing the string "Hello World! " (the trailing space is significant). Make the text appear to be rotating right by periodically removing one letter from the end of the string and attaching it to the front. When the user clicks on the (windowed) text, it should reverse its direction.
#Perl
Perl
use Tk; use Time::HiRes qw(sleep);   my $msg = 'Hello World! '; my $first = '.+'; my $second = '.';   my $mw = Tk::MainWindow->new(-title => 'Animated side-scroller',-bg=>"white"); $mw->geometry ("400x150+0+0");   $mw->optionAdd('*Label.font', 'Courier 24 bold' );   my $scroller = $mw->Label(-text => "$msg")->grid(-row=>0,-column=>0); $mw->bind('all'=> '<Key-Escape>' => sub {exit;}); $mw->bind("<Button>" => sub { ($second,$first) = ($first,$second) });   $scroller->after(1, \&display ); MainLoop;   sub display { while () { sleep 0.25; $msg =~ s/($first)($second)/$2$1/; $scroller->configure(-text=>"$msg"); $mw->update(); } }
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.
#J
J
require 'gl2 trig' coinsert 'jgl2'   DT =: %30 NB. seconds ANGLE=: 0.45p1 NB. radians L =: 1 NB. metres G =: 9.80665 NB. ms_2 VEL =: 0 NB. ms_1   PEND=: noun define pc pend;pn "Pendulum"; xywh 0 0 320 200;cc isi isigraph rightmove bottommove; pas 0 0;pcenter; rem form end; )   pend_run =: verb def ' wd PEND,'';pshow;timer '',":DT * 1000 ' pend_close =: verb def ' wd ''timer 0; pclose'' ' pend_isi_paint=: verb def ' drawPendulum ANGLE '   sys_timer_z_=: verb define recalcAngle '' wd 'psel pend; setinvalid isi' )   recalcAngle=: verb define accel=. - (G % L) * sin ANGLE VEL =: VEL + accel * DT ANGLE=: ANGLE + VEL * DT )   drawPendulum=: verb define width=. {. glqwh'' ps=. (-: width) , 40 pe=. ps + 280 <.@* (cos , sin) 0.5p1 + y NB. adjust orientation glbrush glrgb 91 91 91 gllines ps , pe glellipse (,~ ps - -:) 40 15 glellipse (,~ pe - -:) 20 20 glrect 0 0 ,width, 40 )   pend_run'' NB. run animation
http://rosettacode.org/wiki/Almkvist-Giullera_formula_for_pi
Almkvist-Giullera formula for pi
The Almkvist-Giullera formula for calculating   1/π2   is based on the Calabi-Yau differential equations of order 4 and 5,   which were originally used to describe certain manifolds in string theory. The formula is: 1/π2 = (25/3) ∑0∞ ((6n)! / (n!6))(532n2 + 126n + 9) / 10002n+1 This formula can be used to calculate the constant   π-2,   and thus to calculate   π. Note that, because the product of all terms but the power of 1000 can be calculated as an integer, the terms in the series can be separated into a large integer term: (25) (6n)! (532n2 + 126n + 9) / (3(n!)6)     (***) multiplied by a negative integer power of 10: 10-(6n + 3) Task Print the integer portions (the starred formula, which is without the power of 1000 divisor) of the first 10 terms of the series. Use the complete formula to calculate and print π to 70 decimal digits of precision. Reference  Gert Almkvist and Jesús Guillera, Ramanujan-like series for 1/π2 and string theory, Experimental Mathematics, 21 (2012), page 2, formula 1.
#Sidef
Sidef
func almkvist_giullera(n) { (32 * (14*n * (38*n + 9) + 9) * (6*n)!) / (3 * n!**6) }   func almkvist_giullera_pi(prec = 70) {   local Num!PREC = (4*(prec+1)).numify   var sum = 0 var target = -1   for n in (0..Inf) { sum += (almkvist_giullera(n) / (10**(6*n + 3))) var curr = (sum**-.5).as_dec return target if (target == curr) target = curr } }   say 'First 10 integer portions: '   10.of {|n| say "#{n} #{almkvist_giullera(n)}" }   with(70) {|n| say "π to #{n} decimal places is:" say almkvist_giullera_pi(n) }
http://rosettacode.org/wiki/Almkvist-Giullera_formula_for_pi
Almkvist-Giullera formula for pi
The Almkvist-Giullera formula for calculating   1/π2   is based on the Calabi-Yau differential equations of order 4 and 5,   which were originally used to describe certain manifolds in string theory. The formula is: 1/π2 = (25/3) ∑0∞ ((6n)! / (n!6))(532n2 + 126n + 9) / 10002n+1 This formula can be used to calculate the constant   π-2,   and thus to calculate   π. Note that, because the product of all terms but the power of 1000 can be calculated as an integer, the terms in the series can be separated into a large integer term: (25) (6n)! (532n2 + 126n + 9) / (3(n!)6)     (***) multiplied by a negative integer power of 10: 10-(6n + 3) Task Print the integer portions (the starred formula, which is without the power of 1000 divisor) of the first 10 terms of the series. Use the complete formula to calculate and print π to 70 decimal digits of precision. Reference  Gert Almkvist and Jesús Guillera, Ramanujan-like series for 1/π2 and string theory, Experimental Mathematics, 21 (2012), page 2, formula 1.
#Visual_Basic_.NET
Visual Basic .NET
Imports System, BI = System.Numerics.BigInteger, System.Console   Module Module1   Function isqrt(ByVal x As BI) As BI Dim t As BI, q As BI = 1, r As BI = 0 While q <= x : q <<= 2 : End While While q > 1 : q >>= 2 : t = x - r - q : r >>= 1 If t >= 0 Then x = t : r += q End While : Return r End Function   Function dump(ByVal digs As Integer, ByVal Optional show As Boolean = False) As String digs += 1 Dim z As Integer, gb As Integer = 1, dg As Integer = digs + gb Dim te As BI, t1 As BI = 1, t2 As BI = 9, t3 As BI = 1, su As BI = 0, t As BI = BI.Pow(10, If(dg <= 60, 0, dg - 60)), d As BI = -1, fn As BI = 1 For n As BI = 0 To dg - 1 If n > 0 Then t3 = t3 * BI.Pow(n, 6) te = t1 * t2 / t3 : z = dg - 1 - CInt(n) * 6 If z > 0 Then te = te * BI.Pow(10, z) Else te = te / BI.Pow(10, -z) If show AndAlso n < 10 Then WriteLine("{0,2} {1,62}", n, te * 32 / 3 / t) su += te : If te < 10 Then digs -= 1 If show Then WriteLine(vbLf & "{0} iterations required for {1} digits " & _ "after the decimal point." & vbLf, n, digs) Exit For End If For j As BI = n * 6 + 1 To n * 6 + 6 t1 = t1 * j : Next d += 2 : t2 += 126 + 532 * d Next Dim s As String = String.Format("{0}", isqrt(BI.Pow(10, dg * 2 + 3) _ / su / 32 * 3 * BI.Pow(CType(10, BI), dg + 5))) Return s(0) & "." & s.Substring(1, digs) End Function   Sub Main(ByVal args As String()) WriteLine(dump(70, true)) End Sub   End Module
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.
#ATS
ATS
  (* ****** ****** *) // #include "share/atspre_staload.hats" #include "share/HATS/atspre_staload_libats_ML.hats" // (* ****** ****** *) // staload "libats/ML/SATS/monad_list.sats" staload _ = "libats/ML/DATS/monad_list.dats" // (* ****** ****** *) // datatype words = | Sing of stringGt(0) | Comb of (words, words) // (* ****** ****** *) // extern fun words_get_beg(words): char extern fun words_get_end(words): char // (* ****** ****** *) // implement words_get_beg(w0) = ( case+ w0 of | Sing(cs) => cs[0] | Comb(w1, w2) => words_get_beg(w1) ) // implement words_get_end(w0) = ( case+ w0 of | Sing(cs) => cs[pred(length(cs))] | Comb(w1, w2) => words_get_end(w2) ) // (* ****** ****** *) // fun words_comb ( w1: words, w2: words ) : list0(words) = if (words_get_end(w1)=words_get_beg(w2)) then list0_sing(Comb(w1, w2)) else list0_nil() // (* ****** ****** *) // extern fun fprint_words: fprint_type(words) // overload fprint with fprint_words // implement fprint_words(out, ws) = ( case+ ws of | Sing(w) => fprint(out, w) | Comb(w1, w2) => fprint!(out, w1, ' ', w2) ) // implement fprint_val<words> = fprint_words // (* ****** ****** *) // typedef a = stringGt(0) and b = words // val ws1 = $list{a}("this", "that", "a") val ws1 = list_map_fun<a><b>(ws1, lam(x) => Sing(x)) val ws1 = monad_list_list(list0_of_list_vt(ws1)) // val ws2 = $list{a}("frog", "elephant", "thing") val ws2 = list_map_fun<a><b>(ws2, lam(x) => Sing(x)) val ws2 = monad_list_list(list0_of_list_vt(ws2)) // val ws3 = $list{a}("walked", "treaded", "grows") val ws3 = list_map_fun<a><b>(ws3, lam(x) => Sing(x)) val ws3 = monad_list_list(list0_of_list_vt(ws3)) // val ws4 = $list{a}("slowly", "quickly") val ws4 = list_map_fun<a><b>(ws4, lam(x) => Sing(x)) val ws4 = monad_list_list(list0_of_list_vt(ws4)) // (* ****** ****** *) // val ws12 = monad_bind2<b,b><b> (ws1, ws2, lam (w1, w2) => monad_list_list(words_comb(w1, w2))) val ws123 = monad_bind2<b,b><b> (ws12, ws3, lam (w12, w3) => monad_list_list(words_comb(w12, w3))) val ws1234 = monad_bind2<b,b><b> (ws123, ws4, lam (w123, w4) => monad_list_list(words_comb(w123, w4))) // (* ****** ****** *)   implement main0 () = { val () = fprintln! (stdout_ref, "ws1234 = ", ws1234) }   (* ****** ****** *)  
http://rosettacode.org/wiki/Address_of_a_variable
Address of a variable
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation | Comparison | Matching Memory Operations Pointers & references | Addresses Task Demonstrate how to get the address of a variable and how to set the address of a variable.
#360_Assembly
360 Assembly
LA R3,I load address of I ... I DS F
http://rosettacode.org/wiki/Algebraic_data_types
Algebraic data types
Some languages offer direct support for algebraic data types and pattern matching on them. While this of course can always be simulated with manual tagging and conditionals, it allows for terse code which is easy to read, and can represent the algorithm directly. Task As an example, implement insertion in a red-black-tree. A red-black-tree is a binary tree where each internal node has a color attribute red or black. Moreover, no red node can have a red child, and every path from the root to an empty node must contain the same number of black nodes. As a consequence, the tree is balanced, and must be re-balanced after an insertion. Reference Red-Black Trees in a Functional Setting
#Clojure
Clojure
(mapc #'use-package '(#:toadstool #:toadstool-system)) (defstruct (red-black-tree (:constructor tree (color left val right))) color left val right)   (defcomponent tree (operator macro-mixin)) (defexpand tree (color left val right) `(class red-black-tree red-black-tree-color ,color red-black-tree-left ,left red-black-tree-val ,val red-black-tree-right ,right)) (pushnew 'tree *used-components*)   (defun balance (color left val right) (toad-ecase (color left val right) (('black (tree 'red (tree 'red a x b) y c) z d) (tree 'red (tree 'black a x b) y (tree 'black c z d))) (('black (tree 'red a x (tree 'red b y c)) z d) (tree 'red (tree 'black a x b) y (tree 'black c z d))) (('black a x (tree 'red (tree 'red b y c) z d)) (tree 'red (tree 'black a x b) y (tree 'black c z d))) (('black a x (tree 'red b y (tree 'red c z d))) (tree 'red (tree 'black a x b) y (tree 'black c z d))) ((color a x b) (tree color a x b))))   (defun %insert (x s) (toad-ecase1 s (nil (tree 'red nil x nil)) ((tree color a y b) (cond ((< x y) (balance color (%insert x a) y b)) ((> x y) (balance color a y (%insert x b))) (t s)))))   (defun insert (x s) (toad-ecase1 (%insert x s) ((tree t a y b) (tree 'black a y b))))
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
#C
C
#include <stdio.h>   int kprime(int n, int k) { int p, f = 0; for (p = 2; f < k && p*p <= n; p++) while (0 == n % p) n /= p, f++;   return f + (n > 1) == k; }   int main(void) { int i, c, k;   for (k = 1; k <= 5; k++) { printf("k = %d:", k);   for (i = 2, c = 0; c < 10; i++) if (kprime(i, k)) { printf(" %d", i); c++; }   putchar('\n'); }   return 0; }
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
#APL
APL
  anagrams←{ tie←⍵ ⎕NTIE 0 dict←⎕NREAD tie 80(⎕NSIZE tie)0 boxes←((⎕UCS 10)≠dict)⊆dict ana←(({⍵[⍋⍵]}¨boxes)({⍵}⌸)boxes) ({~' '∊¨(⊃/¯1↑[2]⍵)}ana)⌿ana ⋄ ⎕NUNTIE }  
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
#Jsish
Jsish
/* Angle difference between bearings, in Jsish */ function angleDifference(bearing1:number, bearing2:number):number { var angle = (bearing2 - bearing1) % 360; if (angle < -180) angle += 360; if (angle >= 180) angle -= 360; return angle; }   if (Interp.conf('unitTest')) { var dataSet = [[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]]; printf(" Bearing 1 Bearing 2 Difference\n"); for (var i = 0; i < dataSet.length; i++) { printf("%17S° %17S° %17S°\n", dataSet[i][0], dataSet[i][1], angleDifference(dataSet[i][0], dataSet[i][1]) ); } }   /* =!EXPECTSTART!= Bearing 1 Bearing 2 Difference 20° 45° 25° -45° 45° 90° -85° 90° 175° -95° 90° -175° -45° 125° 170° -45° 145° -170° 29.4803° -88.6381° -118.1184° -78.3251° -159.036° -80.7109° -70099.7423381094° 29840.6743787672° -139.583283123386° -165313.666629736° 33693.9894517456° -72.3439185186871° 1174.83805105985° -154146.664901248° -161.502952307404° 60175.7730679555° 42213.0719235437° 37.2988555882694° =!EXPECTEND!= */
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
#Maple
Maple
with(StringTools): dict:=Split([HTTP:-Get("www.puzzlers.org/pub/wordlists/unixdict.txt")][2]): L:=[seq(select(t->HammingDistance(t,w)=length(w),[Anagrams(w,dict)])[],w=dict)]: len:=length(ListTools:-FindMaximalElement(L,(a,b)->length(a)<length(b))): select(w->length(w)=len,L)[];
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.
#Joy
Joy
fib == [small] [] [pred dup pred] [+] binrec;
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.
#Fortran
Fortran
Perfect!! 6 Perfect!! 28 Amicable! 220 284 Perfect!! 496 Amicable! 1184 1210 Amicable! 2620 2924 Amicable! 5020 5564 Amicable! 6232 6368 Perfect!! 8128 Amicable! 10744 10856 Amicable! 12285 14595 Amicable! 17296 18416
http://rosettacode.org/wiki/Animation
Animation
Animation is integral to many parts of GUIs, including both the fancy effects when things change used in window managers, and of course games.   The core of any animation system is a scheme for periodically changing the display while still remaining responsive to the user.   This task demonstrates this. Task Create a window containing the string "Hello World! " (the trailing space is significant). Make the text appear to be rotating right by periodically removing one letter from the end of the string and attaching it to the front. When the user clicks on the (windowed) text, it should reverse its direction.
#Phix
Phix
-- demo\rosetta\Animation.exw with javascript_semantics include pGUI.e string hw = "Hello World! " bool direction = true Ihandle label function button_cb(Ihandle /*ih*/, integer /*button*/, pressed, /*x*/, /*y*/, atom /*pStatus*/) if pressed then direction = not direction end if return IUP_CONTINUE end function function timer_cb(Ihandle /*ih*/) hw = iff(direction ? hw[$] & hw[1..-2] : hw[2..$] & hw[1]) IupSetAttribute(label,"TITLE",hw) return IUP_IGNORE end function procedure main() IupOpen() label = IupLabel(hw,`FONT="Verdana, 18"`) IupSetCallback(label, "BUTTON_CB", Icallback("button_cb")) Ihandle dlg = IupDialog(label,"TITLE=Animation, DIALOGFRAME=YES, CHILDOFFSET=70x40, SIZE=200x80") IupShow(dlg) Ihandle hTimer = IupTimer(Icallback("timer_cb"), 160) if platform()!=JS then IupMainLoop() IupClose() end if end procedure main()
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.
#Java
Java
import java.awt.*; import javax.swing.*;   public class Pendulum extends JPanel implements Runnable {   private double angle = Math.PI / 2; private int length;   public Pendulum(int length) { this.length = length; setDoubleBuffered(true); }   @Override public void paint(Graphics g) { g.setColor(Color.WHITE); g.fillRect(0, 0, getWidth(), getHeight()); g.setColor(Color.BLACK); int anchorX = getWidth() / 2, anchorY = getHeight() / 4; int ballX = anchorX + (int) (Math.sin(angle) * length); int ballY = anchorY + (int) (Math.cos(angle) * length); g.drawLine(anchorX, anchorY, ballX, ballY); g.fillOval(anchorX - 3, anchorY - 4, 7, 7); g.fillOval(ballX - 7, ballY - 7, 14, 14); }   public void run() { double angleAccel, angleVelocity = 0, dt = 0.1; while (true) { angleAccel = -9.81 / length * Math.sin(angle); angleVelocity += angleAccel * dt; angle += angleVelocity * dt; repaint(); try { Thread.sleep(15); } catch (InterruptedException ex) {} } }   @Override public Dimension getPreferredSize() { return new Dimension(2 * length + 50, length / 2 * 3); }   public static void main(String[] args) { JFrame f = new JFrame("Pendulum"); Pendulum p = new Pendulum(200); f.add(p); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); f.pack(); f.setVisible(true); new Thread(p).start(); } }
http://rosettacode.org/wiki/Almkvist-Giullera_formula_for_pi
Almkvist-Giullera formula for pi
The Almkvist-Giullera formula for calculating   1/π2   is based on the Calabi-Yau differential equations of order 4 and 5,   which were originally used to describe certain manifolds in string theory. The formula is: 1/π2 = (25/3) ∑0∞ ((6n)! / (n!6))(532n2 + 126n + 9) / 10002n+1 This formula can be used to calculate the constant   π-2,   and thus to calculate   π. Note that, because the product of all terms but the power of 1000 can be calculated as an integer, the terms in the series can be separated into a large integer term: (25) (6n)! (532n2 + 126n + 9) / (3(n!)6)     (***) multiplied by a negative integer power of 10: 10-(6n + 3) Task Print the integer portions (the starred formula, which is without the power of 1000 divisor) of the first 10 terms of the series. Use the complete formula to calculate and print π to 70 decimal digits of precision. Reference  Gert Almkvist and Jesús Guillera, Ramanujan-like series for 1/π2 and string theory, Experimental Mathematics, 21 (2012), page 2, formula 1.
#Wren
Wren
import "/big" for BigInt, BigRat import "/fmt" for Fmt   var factorial = Fn.new { |n| if (n < 2) return BigInt.one var fact = BigInt.one for (i in 2..n) fact = fact * i return fact }   var almkvistGiullera = Fn.new { |n, print| var t1 = factorial.call(6*n) * 32 var t2 = 532*n*n + 126*n + 9 var t3 = factorial.call(n).pow(6)*3 var ip = t1 * t2 / t3 var pw = 6*n + 3 var tm = BigRat.new(ip, BigInt.ten.pow(pw)) if (print) { Fmt.print("$d $44i $3d $-35s", n, ip, -pw, tm.toDecimal(33)) } else { return tm } }   System.print("N Integer Portion Pow Nth Term (33 dp)") System.print("-" * 89) for (n in 0..9) { almkvistGiullera.call(n, true) }   var sum = BigRat.zero var prev = BigRat.zero var prec = BigRat.new(BigInt.one, BigInt.ten.pow(70)) var n = 0 while(true) { var term = almkvistGiullera.call(n, false) sum = sum + term if ((sum-prev).abs < prec) break prev = sum n = n + 1 } var pi = BigRat.one/sum.sqrt(70) System.print("\nPi to 70 decimal places is:") System.print(pi.toDecimal(70))
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.
#AutoHotkey
AutoHotkey
set1 := "the that a" set2 := "frog elephant thing" set3 := "walked treaded grows" set4 := "slowly quickly"   MsgBox % amb( "", set1, set2, set3, set4 ) ; this takes a total of 17 iterations to complete   amb( char = "", set1 = "", set2 = "", set3 = "", set4 = "" ) { ; original call to amb must leave char param blank Loop, Parse, set1, %A_Space% If (char = (idxchar := SubStr(A_LoopField, 1, 1)) && set2 = "" || (char = idxchar || char = "") && ((retval:= amb(SubStr(A_LoopField, 0, 1), set2, set3, set4)) != "")) Return A_LoopField " " retval Return "" }
http://rosettacode.org/wiki/Address_of_a_variable
Address of a variable
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation | Comparison | Matching Memory Operations Pointers & references | Addresses Task Demonstrate how to get the address of a variable and how to set the address of a variable.
#6502_Assembly
6502 Assembly
;;;;;;; zero page RAM memory addresses CursorX equ $00 CursorY equ $01 temp equ $02 ;;;;;;; memory-mapped hardware registers BorderColor equ $D020   Joystick1 equ $DC01 Joystick2 equ $DC00
http://rosettacode.org/wiki/Address_of_a_variable
Address of a variable
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation | Comparison | Matching Memory Operations Pointers & references | Addresses Task Demonstrate how to get the address of a variable and how to set the address of a variable.
#68000_Assembly
68000 Assembly
UserRam equ $100000 Cursor_X equ UserRam ;$100000, byte length Cursor_Y equ UserRam+1 ;$100001, byte length SixteenBitData equ UserRam+2 ;$100002, word length (VASM doesn't allow labels to begin with numbers.) ThirtyTwoBitData equ UserRam+4 ;$100004, long length   ;GET THE ADDRESS   LEA ThirtyTwoBitData,A0 ;load $100004 into A0.
http://rosettacode.org/wiki/Address_of_a_variable
Address of a variable
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation | Comparison | Matching Memory Operations Pointers & references | Addresses Task Demonstrate how to get the address of a variable and how to set the address of a variable.
#8086_Assembly
8086 Assembly
.model small .stack 1024 .data UserRam 256 DUP (0) ;define the next 256 bytes as user RAM, initialize them all to zero.   .code   mov ax, seg UserRam ;load into AX the segment where UserRam is stored. mov es, ax ;load that value into the Extra Segment register   mov ax, offset UserRam ;load into AX the address of UserRam mov di, ax ;load that value into the destination index register
http://rosettacode.org/wiki/Algebraic_data_types
Algebraic data types
Some languages offer direct support for algebraic data types and pattern matching on them. While this of course can always be simulated with manual tagging and conditionals, it allows for terse code which is easy to read, and can represent the algorithm directly. Task As an example, implement insertion in a red-black-tree. A red-black-tree is a binary tree where each internal node has a color attribute red or black. Moreover, no red node can have a red child, and every path from the root to an empty node must contain the same number of black nodes. As a consequence, the tree is balanced, and must be re-balanced after an insertion. Reference Red-Black Trees in a Functional Setting
#Common_Lisp
Common Lisp
(mapc #'use-package '(#:toadstool #:toadstool-system)) (defstruct (red-black-tree (:constructor tree (color left val right))) color left val right)   (defcomponent tree (operator macro-mixin)) (defexpand tree (color left val right) `(class red-black-tree red-black-tree-color ,color red-black-tree-left ,left red-black-tree-val ,val red-black-tree-right ,right)) (pushnew 'tree *used-components*)   (defun balance (color left val right) (toad-ecase (color left val right) (('black (tree 'red (tree 'red a x b) y c) z d) (tree 'red (tree 'black a x b) y (tree 'black c z d))) (('black (tree 'red a x (tree 'red b y c)) z d) (tree 'red (tree 'black a x b) y (tree 'black c z d))) (('black a x (tree 'red (tree 'red b y c) z d)) (tree 'red (tree 'black a x b) y (tree 'black c z d))) (('black a x (tree 'red b y (tree 'red c z d))) (tree 'red (tree 'black a x b) y (tree 'black c z d))) ((color a x b) (tree color a x b))))   (defun %insert (x s) (toad-ecase1 s (nil (tree 'red nil x nil)) ((tree color a y b) (cond ((< x y) (balance color (%insert x a) y b)) ((> x y) (balance color a y (%insert x b))) (t s)))))   (defun insert (x s) (toad-ecase1 (%insert x s) ((tree t a y b) (tree 'black a y b))))
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
#C.23
C#
using System; using System.Collections.Generic; using System.Linq;   namespace AlmostPrime { class Program { static void Main(string[] args) { foreach (int k in Enumerable.Range(1, 5)) { KPrime kprime = new KPrime() { K = k }; Console.WriteLine("k = {0}: {1}", k, string.Join<int>(" ", kprime.GetFirstN(10))); } } }   class KPrime { public int K { get; set; }   public bool IsKPrime(int number) { int primes = 0; for (int p = 2; p * p <= number && primes < K; ++p) { while (number % p == 0 && primes < K) { number /= p; ++primes; } } if (number > 1) { ++primes; } return primes == K; }   public List<int> GetFirstN(int n) { List<int> result = new List<int>(); for (int number = 2; result.Count < n; ++number) { if (IsKPrime(number)) { result.Add(number); } } return result; } } }
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
#AppleScript
AppleScript
use AppleScript version "2.3.1" -- OS X 10.9 (Mavericks) or later — for these 'use' commands! -- Uses the customisable AppleScript-coded sort shown at <https://macscripter.net/viewtopic.php?pid=194430#p194430>. -- It's assumed scripters will know how and where to install it as a library. use sorter : script "Custom Iterative Ternary Merge Sort" use scripting additions   on largestAnagramGroups(listOfWords) script o property wordList : listOfWords property doctoredWords : {} property longestRanges : {} property output : {} end script   ignoring case -- Build another list containing doctored versions of the input words with their characters lexically sorted. set astid to AppleScript's text item delimiters set AppleScript's text item delimiters to "" repeat with thisWord in o's wordList set theseChars to thisWord's characters -- A straight ascending in-place sort here. tell sorter to sort(theseChars, 1, -1, {}) -- Params: (list, start index, end index, customisation spec.). set end of o's doctoredWords to theseChars as text end repeat set AppleScript's text item delimiters to astid   -- Sort the list of doctored words to group them, rearranging the original-word list in parallel. tell sorter to sort(o's doctoredWords, 1, -1, {slave:{o's wordList}})   -- Find the range(s) of the longest run(s) of equal texts in the doctored-word list. set longestRunLength to 1 set i to 1 set currentText to beginning of o's doctoredWords repeat with j from 2 to (count o's doctoredWords) set thisText to item j of o's doctoredWords if (thisText is not currentText) then set thisRunLength to j - i if (thisRunLength > longestRunLength) then set o's longestRanges to {{i, j - 1}} set longestRunLength to thisRunLength else if (thisRunLength = longestRunLength) then set end of o's longestRanges to {i, j - 1} end if set currentText to thisText set i to j end if end repeat set finalRunLength to j - i + 1 if (finalRunLength > longestRunLength) then set o's longestRanges to {{i, j}} else if (finalRunLength = longestRunLength) then set end of o's longestRanges to {i, j} end if   -- Get the group(s) of words occupying the same range(s) in the original-word list. -- The stable parallel sort above will have kept each group's words in the same order with respect to each other. repeat with thisRange in o's longestRanges set {i, j} to thisRange set end of o's output to items i thru j of o's wordList end repeat   -- As a final flourish, sort the list of groups by their first items. script byFirstItem on isGreater(a, b) return (a's beginning > b's beginning) end isGreater end script tell sorter to sort(o's output, 1, -1, {comparer:byFirstItem}) end ignoring   return o's output end largestAnagramGroups   -- The closing values of AppleScript 'run handler' variables not explicity declared local are -- saved back to the script file afterwards — and "unixdict.txt" contains 25,104 words! local wordFile, wordList -- The words in "unixdict.txt" are arranged one per line in alphabetical order. -- Some contain punctuation characters, so they're best extracted as 'paragraphs' rather than as 'words'. set wordFile to ((path to desktop as text) & "unixdict.txt") as «class furl» set wordList to paragraphs of (read wordFile as «class utf8») return largestAnagramGroups(wordList)
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
#jq
jq
# Angles are in degrees; the result is rounded to 4 decimal places: def subtract($b1; $b2): 10000 as $scale | (($scale * ($b2 - $b1)) % (360 * $scale)) | round / $scale | if . < -180 then . + 360 elif . >= 180 then . - 360 else . end;   def 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] ;   "Differences (to 4dp) between these bearings:", ( pairs as [$p0, $p1] | subtract($p0; $p1) as $diff | (if $p0 < 0 then " " else " " end) as $offset | "\($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
#Mathematica_.2F_Wolfram_Language
Mathematica / Wolfram Language
words=First/@Import["http://www.puzzlers.org/pub/wordlists/unixdict.txt","Table"]; anagramDegrangement=Function[{w1,w2}, Module[{c1=ToCharacterCode@w1,c2=ToCharacterCode@w2}, Sort@c1==Sort@c2&&Select[c1-c2,#==0&,1]==={}]]; gs=Select[GatherBy[words,{StringLength@#,Union@ToCharacterCode@#}&],Length@#>=2&]; First@Flatten[Function[ws,Select[Join@@Outer[List,ws,ws,1],anagramDegrangement@@#&]]/@SortBy[gs,-StringLength@First@#&],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.
#jq
jq
0 | recurse(. + 1)
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.
#FreeBASIC
FreeBASIC
  ' FreeBASIC v1.05.0 win64   Function SumProperDivisors(number As Integer) As Integer If number < 2 Then Return 0 Dim sum As Integer = 0 For i As Integer = 1 To number \ 2 If number Mod i = 0 Then sum += i Next Return sum End Function   Dim As Integer n, f Dim As Integer sum(19999)   For n = 1 To 19999 sum(n) = SumProperDivisors(n) Next   Print "The pairs of amicable numbers below 20,000 are :" Print   For n = 1 To 19998 ' f = SumProperDivisors(n) f = sum(n) If f <= n OrElse f < 1 OrElse f > 19999 Then Continue For If f = sum(n) AndAlso n = sum(f) Then Print Using "#####"; n; Print " and "; Using "#####"; sum(n) End If Next   Print Print "Press any key to exit the program" Sleep End  
http://rosettacode.org/wiki/Animation
Animation
Animation is integral to many parts of GUIs, including both the fancy effects when things change used in window managers, and of course games.   The core of any animation system is a scheme for periodically changing the display while still remaining responsive to the user.   This task demonstrates this. Task Create a window containing the string "Hello World! " (the trailing space is significant). Make the text appear to be rotating right by periodically removing one letter from the end of the string and attaching it to the front. When the user clicks on the (windowed) text, it should reverse its direction.
#PicoLisp
PicoLisp
#!/usr/bin/picolisp /usr/lib/picolisp/lib.l   (prin "^[[?9h") # Mouse reporting on   (setq Dir 1 Text (chop "Hello World! "))   (loop (prin (do Dir (rot Text))) (when (= "^[" (key 200)) (key) (key) (when (= " " (key)) # Left button (setq Dir (if (= 1 Dir) 12 1)) ) (key) (key) ) (do (length Text) (prin "^H")) )
http://rosettacode.org/wiki/Animation
Animation
Animation is integral to many parts of GUIs, including both the fancy effects when things change used in window managers, and of course games.   The core of any animation system is a scheme for periodically changing the display while still remaining responsive to the user.   This task demonstrates this. Task Create a window containing the string "Hello World! " (the trailing space is significant). Make the text appear to be rotating right by periodically removing one letter from the end of the string and attaching it to the front. When the user clicks on the (windowed) text, it should reverse its direction.
#Processing
Processing
String txt = "Hello, world! "; boolean dir = true;   void draw(){ background(128); text(txt, 10, height/2); if(frameCount%10==0){ if(dir) { txt = rotate(txt, 1); } else { txt = rotate(txt, txt.length()-1); } } }   void mouseReleased(){ dir = !dir; }   String rotate(String text, int startIdx) { char[] rotated = new char[text.length()]; for (int i = 0; i < text.length(); i++) { rotated[i] = text.charAt((i + startIdx) % text.length()); } return String.valueOf(rotated); }
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.
#JavaScript
JavaScript
<html><head> <title>Pendulum</title> </head><body style="background: gray;">   <canvas id="canvas" width="600" height="600"> <p>Sorry, your browser does not support the &lt;canvas&gt; used to display the pendulum animation.</p> </canvas> <script> function PendulumSim(length_m, gravity_mps2, initialAngle_rad, timestep_ms, callback) { var velocity = 0; var angle = initialAngle_rad; var k = -gravity_mps2/length_m; var timestep_s = timestep_ms / 1000; return setInterval(function () { var acceleration = k * Math.sin(angle); velocity += acceleration * timestep_s; angle += velocity * timestep_s; callback(angle); }, timestep_ms); }   var canvas = document.getElementById('canvas'); var context = canvas.getContext('2d'); var prev=0; var sim = PendulumSim(1, 9.80665, Math.PI*99/100, 10, function (angle) { var rPend = Math.min(canvas.width, canvas.height) * 0.47; var rBall = Math.min(canvas.width, canvas.height) * 0.02; var rBar = Math.min(canvas.width, canvas.height) * 0.005; var ballX = Math.sin(angle) * rPend; var ballY = Math.cos(angle) * rPend;   context.fillStyle = "rgba(255,255,255,0.51)"; context.globalCompositeOperation = "destination-out"; context.fillRect(0, 0, canvas.width, canvas.height);   context.fillStyle = "yellow"; context.strokeStyle = "rgba(0,0,0,"+Math.max(0,1-Math.abs(prev-angle)*10)+")"; context.globalCompositeOperation = "source-over";   context.save(); context.translate(canvas.width/2, canvas.height/2); context.rotate(angle);   context.beginPath(); context.rect(-rBar, -rBar, rBar*2, rPend+rBar*2); context.fill(); context.stroke();   context.beginPath(); context.arc(0, rPend, rBall, 0, Math.PI*2, false); context.fill(); context.stroke(); context.restore(); prev=angle; }); </script>   </body></html>
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.
#BaCon
BaCon
DECLARE (*ambassert)() TYPE NUMBER   FUNCTION amb_recurse$(text$[], nr, total, result$)   LOCAL ctr LOCAL str$, test$   FOR ctr = 1 TO AMOUNT(text$[nr]) str$ = APPEND$(result$, 0, TOKEN$(text$[nr], ctr)) IF nr = total-1 THEN IF ambassert(str$) THEN RETURN str$ ELSE test$ = amb_recurse$(text$, nr+1, total, str$) IF AMOUNT(test$) = total THEN RETURN test$ ENDIF NEXT   RETURN ""   ENDFUNC   FUNCTION ambsel$(VAR data$ SIZE dim)   RETURN IIF$(dim < 2, "ambsel$ needs more than 1 argument", amb_recurse$(data$, 0, dim, ""))   ENDFUNC   FUNCTION this_is_some_constraint(var$)   DOTIMES AMOUNT(var$)-1 IF RIGHT$(TOKEN$(var$, _), 1) != LEFT$(TOKEN$(var$, _+1), 1) THEN RETURN FALSE DONE   RETURN TRUE   ENDFUNC   ' AMBASSERT: pointing to a constraint function ambassert = this_is_some_constraint   ' AMBSEL$: generate result from arguments in delimited string format PRINT ambsel$("the that a", "frog elephant thing", "walked treaded grows", "slowly quickly")
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
#11l
11l
F pdsum(n) R sum((1 .. (n + 1) I/ 2).filter(x -> @n % x == 0 & @n != x))   F aliquot(n, maxlen = 16, maxterm = 2 ^ 30) I n == 0 R (‘terminating’, [0]) V s = [n] V slen = 1 V new = n L slen <= maxlen & new < maxterm new = pdsum(s.last) I new C s I s[0] == new I slen == 1 R (‘perfect’, s) E I slen == 2 R (‘amicable’, s) E R (‘sociable of length #.’.format(slen), s) E I s.last == new R (‘aspiring’, s) E R (‘cyclic back to #.’.format(new), s) E I new == 0 R (‘terminating’, s [+] [0]) E s.append(new) slen++ L.was_no_break R (‘non-terminating’, s)   L(n) 1..10 V (cls, seq) = aliquot(n) print(‘#.: #.’.format(cls, seq)) print() L(n) [11, 12, 28, 496, 220, 1184, 12496, 1264460, 790, 909, 562, 1064, 1488] V (cls, seq) = aliquot(n) print(‘#.: #.’.format(cls, seq))
http://rosettacode.org/wiki/Address_of_a_variable
Address of a variable
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation | Comparison | Matching Memory Operations Pointers & references | Addresses Task Demonstrate how to get the address of a variable and how to set the address of a variable.
#AArch64_Assembly
AArch64 Assembly
  /* ARM assembly AArch64 Raspberry PI 3B */ /* program adrvar.s */ /*************************************/ /* Constantes */ /*************************************/ .equ STDOUT, 1 .equ WRITE, 64 .equ EXIT, 93 /*************************************/ /* Initialized data */ /*************************************/ .data szMessage: .asciz "Hello. \n" // message szRetourLigne: .asciz "\n" qValDeb: .quad 5 // value 5 in array of 8 bytes /*************************************/ /* No Initialized data */ /*************************************/ .bss qValeur: .skip 8 // reserve 8 bytes in memory /*************************************/ /* Program code */ /*************************************/ .text .global main main: ldr x0,=szMessage // adresse of message short program bl affichageMess // call function // or ldr x0,qAdrszMessage // adresse of message big program (size code > 4K) bl affichageMess // call function   ldr x1,=qValDeb // adresse of variable -> x1 short program ldr x0,[x1] // value of iValdeb -> x0 ldr x1,qAdriValDeb // adresse of variable -> x1 big program ldr x0,[x1] // value of iValdeb -> x0   /* set variables */ ldr x1,=qValeur // adresse of variable -> x1 short program str x0,[x1] // value of x0 -> iValeur ldr x1,qAdriValeur // adresse of variable -> x1 big program str x0,[x1] // value of x0 -> iValeur     /* end of program */ mov x0,0 // return code mov x8,EXIT // request to exit program svc 0 // perform the system call qAdriValDeb: .quad qValDeb qAdriValeur: .quad qValeur qAdrszMessage: .quad szMessage qAdrszRetourLigne: .quad szRetourLigne /******************************************************************/ /* String display with size compute */ /******************************************************************/ /* x0 contains string address (string ended with zero binary) */ affichageMess: stp x0,x1,[sp,-16]! // save registers stp x2,x8,[sp,-16]! // save registers mov x2,0 // size counter 1: // loop start ldrb w1,[x0,x2] // load a byte cbz w1,2f // if zero -> end string add x2,x2,#1 // else increment counter b 1b // and loop 2: // x2 = string size mov x1,x0 // string address mov x0,STDOUT // output Linux standard mov x8,WRITE // code call system "write" svc 0 // call systeme Linux ldp x2,x8,[sp],16 // restaur 2 registres ldp x0,x1,[sp],16 // restaur 2 registres ret // retour adresse lr x30    
http://rosettacode.org/wiki/Address_of_a_variable
Address of a variable
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation | Comparison | Matching Memory Operations Pointers & references | Addresses Task Demonstrate how to get the address of a variable and how to set the address of a variable.
#Action.21
Action!
PROC Main() BYTE v=[123]   PrintF("Value of variable: %B%E",v) PrintF("Address of variable: %H%E",@v) RETURN
http://rosettacode.org/wiki/Address_of_a_variable
Address of a variable
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation | Comparison | Matching Memory Operations Pointers & references | Addresses Task Demonstrate how to get the address of a variable and how to set the address of a variable.
#Ada
Ada
The_Address : System.Address; I : Integer; The_Address := I'Address;
http://rosettacode.org/wiki/Algebraic_data_types
Algebraic data types
Some languages offer direct support for algebraic data types and pattern matching on them. While this of course can always be simulated with manual tagging and conditionals, it allows for terse code which is easy to read, and can represent the algorithm directly. Task As an example, implement insertion in a red-black-tree. A red-black-tree is a binary tree where each internal node has a color attribute red or black. Moreover, no red node can have a red child, and every path from the root to an empty node must contain the same number of black nodes. As a consequence, the tree is balanced, and must be re-balanced after an insertion. Reference Red-Black Trees in a Functional Setting
#E
E
def balance(tree) { return if ( tree =~ term`tree(black, tree(red, tree(red, @a, @x, @b), @y, @c), @z, @d)` || tree =~ term`tree(black, tree(red, @a, @x, tree(red, @b, @y, @c)), @z, @d)` || tree =~ term`tree(black, @a, @x, tree(red, tree(red, @b, @y, @c), @z, @d))` || tree =~ term`tree(black, @a, @x, tree(red, @b, @y, tree(red, @c, @z, @d)))` ) { term`tree(red, tree(black, $a, $x, $b), $y, tree(black, $c, $z, $d))` } else { tree } } def insert(elem, tree) { def ins(tree) { return switch (tree) { match term`empty` { term`tree(red, empty, $elem, empty)` } match term`tree(@color, @a, @y, @b)` { if (elem < y) { balance(term`tree($color, ${ins(a)}, $y, $b)`) } else if (elem > y) { balance(term`tree($color, $a, $y, ${ins(b)})`) } else { tree } } } } def term`tree(@_, @a, @y, @b)` := ins(tree) return term`tree(black, $a, $y, $b)` }
http://rosettacode.org/wiki/Algebraic_data_types
Algebraic data types
Some languages offer direct support for algebraic data types and pattern matching on them. While this of course can always be simulated with manual tagging and conditionals, it allows for terse code which is easy to read, and can represent the algorithm directly. Task As an example, implement insertion in a red-black-tree. A red-black-tree is a binary tree where each internal node has a color attribute red or black. Moreover, no red node can have a red child, and every path from the root to an empty node must contain the same number of black nodes. As a consequence, the tree is balanced, and must be re-balanced after an insertion. Reference Red-Black Trees in a Functional Setting
#EchoLisp
EchoLisp
  ;; code adapted from Racket and Common Lisp ;; Illustrates matching on structures (require 'match) (require 'struct)     (define (N-tostring n) (format "%s %d" (N-color n) (N-value n))) (struct N (color left value right) #:tostring N-tostring)   (define (balance t) (match t [(N '⚫️ (N '🔴 (N '🔴 a x b) y c) z d) (N '🔴 (N '⚫️ a x b) y (N '⚫️ c z d))] [(N '⚫️ (N '🔴 a x (N '🔴 b y c)) z d) (N '🔴 (N '⚫️ a x b) y (N '⚫️ c z d))] [(N '⚫️ a x (N '🔴 (N '🔴 b y c) z d)) (N '🔴 (N '⚫️ a x b) y (N '⚫️ c z d))] [(N '⚫️ a x (N '🔴 b y (N '🔴 c z d))) (N '🔴 (N '⚫️ a x b) y (N '⚫️ c z d))] [else t]))   (define (ins value: x tree: t) (match t ['empty (N '🔴 'empty x 'empty)] [(N c l v r) (cond [(< x v) (balance (N c (ins x l) v r))] [(> x v) (balance (N c l v (ins x r)))] [else t])]))   (define (insert value: x tree: s) (match (ins x s) [(N _ l v r) (N '⚫️ l v r)]))    
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
#C.2B.2B
C++
#include <cstdlib> #include <iostream> #include <sstream> #include <iomanip> #include <list>   bool k_prime(unsigned n, unsigned k) { unsigned f = 0; for (unsigned p = 2; f < k && p * p <= n; p++) while (0 == n % p) { n /= p; f++; } return f + (n > 1 ? 1 : 0) == k; }   std::list<unsigned> primes(unsigned k, unsigned n) { std::list<unsigned> list; for (unsigned i = 2;list.size() < n;i++) if (k_prime(i, k)) list.push_back(i); return list; }   int main(const int argc, const char* argv[]) { using namespace std; for (unsigned k = 1; k <= 5; k++) { ostringstream os(""); const list<unsigned> l = primes(k, 10); for (list<unsigned>::const_iterator i = l.begin(); i != l.end(); i++) os << setw(4) << *i; cout << "k = " << k << ':' << os.str() << endl; }   return EXIT_SUCCESS; }
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
#ARM_Assembly
ARM Assembly
  /* ARM assembly Raspberry PI */ /* program anagram.s */   /* REMARK 1 : this program use routines in a include file see task Include a file language arm assembly for the routine affichageMess conversion10 see at end of this program the instruction include */ /* for constantes see task include a file in arm assembly */ /************************************/ /* Constantes */ /************************************/ .include "../constantes.inc"   .equ MAXI, 40000 .equ BUFFERSIZE, 300000 .equ READ, 3 @ system call .equ OPEN, 5 @ system call .equ CLOSE, 6 @ system call .equ O_RDWR, 0x0002 @ open for reading and writing   /*********************************/ /* Initialized data */ /*********************************/ .data szFileName: .asciz "./listword.txt" szMessErreur: .asciz "FILE ERROR." szCarriageReturn: .asciz "\n" szMessSpace: .asciz " "   ptBuffer1: .int sBuffer1 /*********************************/ /* UnInitialized data */ /*********************************/ .bss ptTabBuffer: .skip 4 * MAXI ptTabAna: .skip 4 * MAXI tbiCptAna: .skip 4 * MAXI iNBword: .skip 4 sBuffer: .skip BUFFERSIZE sBuffer1: .skip BUFFERSIZE   /*********************************/ /* code section */ /*********************************/ .text .global main main: @ entry of program mov r4,#0 @ loop indice ldr r0,iAdrszFileName @ file name mov r1,#O_RDWR @ flags mov r2,#0 @ mode mov r7,#OPEN @ svc 0 cmp r0,#0 @ error open ble 99f mov r8,r0 @ FD save Fd ldr r1,iAdrsBuffer @ buffer address ldr r2,iSizeBuf @ buffersize mov r7, #READ svc 0 cmp r0,#0 @ error read ? blt 99f mov r5,r0 @ save size read bytes ldr r4,iAdrsBuffer @ buffer address ldr r0,iAdrsBuffer @ start word address mov r2,#0 mov r1,#0 @ word length 1: cmp r2,r5 bge 2f ldrb r3,[r4,r2] cmp r3,#0xD @ end word ? addne r1,r1,#1 @ increment word length addne r2,r2,#1 @ increment indice bne 1b @ and loop mov r3,#0 strb r3,[r4,r2] @ store final zero bl anaWord @ sort word letters add r2,r2,#2 @ jump OD and 0A add r0,r4,r2 @ new address begin word mov r1,#0 @ init length b 1b @ and loop   2: mov r3,#0 @ last word strb r3,[r4,r2] bl anaWord   mov r0,r8 @ file Fd mov r7, #CLOSE svc 0 cmp r0,#0 @ error close ? blt 99f   ldr r0,iAdrptTabAna @ address sorted string area mov r1,#0 @ first indice ldr r2,iAdriNBword ldr r2,[r2] @ last indice ldr r3,iAdrptTabBuffer @ address sorted string area bl triRapide @ quick sort ldr r4,iAdrptTabAna @ address sorted string area ldr r7,iAdrptTabBuffer @ address sorted string area ldr r10,iAdrtbiCptAna @ address counter occurences mov r9,r2 @ size word array mov r8,#0 @ indice first occurence ldr r3,[r4,r8,lsl #2] @ load first value mov r2,#1 @ loop indice mov r6,#0 @ counter mov r12,#0 @ counter value max 3: ldr r5,[r4,r2,lsl #2] @ load next value mov r0,r3 mov r1,r5 bl comparStrings cmp r0,#0 @ sorted strings equal ? bne 4f add r6,r6,#1 @ yes increment counter b 5f 4: @ no str r6,[r10,r8,lsl #2] @ store counter in first occurence cmp r6,r12 @ counter > value max movgt r12,r6 @ yes counter -> value max mov r6,#0 @ raz counter mov r8,r2 @ init index first occurence mov r3,r5 @ init value first occurence 5: add r2,r2,#1 @ increment indice cmp r2,r9 @ end word array ? blt 3b @ no -> loop   mov r2,#0 @ raz indice 6: @ display loop ldr r6,[r10,r2,lsl #2] @ load counter cmp r6,r12 @ equal to max value ? bne 8f ldr r0,[r7,r2,lsl #2] @ load address first word bl affichageMess add r3,r2,#1 @ increment new indixe mov r4,#0 @ counter 7: ldr r0,iAdrszMessSpace bl affichageMess ldr r0,[r7,r3,lsl #2] @ load address other word bl affichageMess add r3,r3,#1 @ increment indice add r4,r4,#1 @ increment counter cmp r4,r6 @ max value ? blt 7b @ no loop ldr r0,iAdrszCarriageReturn bl affichageMess 8: add r2,r2,#1 @ increment indice cmp r2,r9 @ maxi ? blt 6b @ no -> loop   b 100f 99: @ display error ldr r1,iAdrszMessErreur bl displayError   100: @ standard end of the program mov r0, #0 @ return code mov r7, #EXIT @ request to exit program svc #0 @ perform the system call iAdrszCarriageReturn: .int szCarriageReturn iAdrszFileName: .int szFileName iAdrszMessErreur: .int szMessErreur iAdrsBuffer: .int sBuffer iSizeBuf: .int BUFFERSIZE iAdrszMessSpace: .int szMessSpace iAdrtbiCptAna: .int tbiCptAna /******************************************************************/ /* analizing word */ /******************************************************************/ /* r0 word address */ /* r1 word length */ anaWord: push {r1-r6,lr} mov r5,r0 mov r6,r1 ldr r1,iAdrptTabBuffer ldr r2,iAdriNBword ldr r3,[r2] str r0,[r1,r3,lsl #2]   ldr r1,iAdrptTabAna ldr r4,iAdrptBuffer1 ldr r0,[r4] add r6,r6,r0 add r6,r6,#1 str r6,[r4] str r0,[r1,r3,lsl #2]   add r3,r3,#1 str r3,[r2] mov r1,r0 mov r0,r5 bl triLetters @ sort word letters mov r2,#0 100: pop {r1-r6,pc} iAdrptTabBuffer: .int ptTabBuffer iAdrptTabAna: .int ptTabAna iAdriNBword: .int iNBword iAdrptBuffer1: .int ptBuffer1 /******************************************************************/ /* sort word letters */ /******************************************************************/ /* r0 address begin word */ /* r1 address recept array */ triLetters: push {r1-r7,lr} mov r2,#0 1: ldrb r3,[r0,r2] @ load letter cmp r3,#0 @ end word ? beq 6f cmp r2,#0 @ first letter ? bne 2f strb r3,[r1,r2] @ yes store in first position add r2,r2,#1 @ increment indice b 1b @ and loop 2: mov r4,#0 3: @ begin loop to search insertion position ldrb r5,[r1,r4] @ load letter cmp r3,r5 @ compare blt 4f @ to low -> insertion add r4,r4,#1 @ increment indice cmp r4,r2 @ compare to letters number in place blt 3b @ search loop strb r3,[r1,r2] @ else store in last position add r2,r2,#1 b 1b @ and loop 4: @ move first letters in one position sub r6,r2,#1 @ start indice 5: ldrb r5,[r1,r6] @ load letter add r7,r6,#1 @ store indice - 1 strb r5,[r1,r7] @ store letter sub r6,r6,#1 @ decrement indice cmp r6,r4 @ end ? bge 5b @ no loop strb r3,[r1,r4] @ else store letter in free position add r2,r2,#1 b 1b @ and loop 6: mov r3,#0 @ final zéro strb r3,[r1,r2] 100: pop {r1-r7,pc} /***************************************************/ /* Appel récursif Tri Rapide quicksort */ /***************************************************/ /* r0 contains the address of table */ /* r1 contains index of first item */ /* r2 contains the number of elements > 0 */ /* r3 contains the address of table 2 */ triRapide: push {r2-r6,lr} @ save registers mov r6,r3 sub r2,#1 @ last item index cmp r1,r2 @ first > last ? bge 100f @ yes -> end mov r4,r0 @ save r0 mov r5,r2 @ save r2 mov r3,r6 bl partition1 @ cutting into 2 parts mov r2,r0 @ index partition mov r0,r4 @ table address bl triRapide @ sort lower part mov r0,r4 @ table address add r1,r2,#1 @ index begin = index partition + 1 add r2,r5,#1 @ number of elements bl triRapide @ sort higter part   100: @ end function pop {r2-r6,lr} @ restaur registers bx lr @ return   /******************************************************************/ /* Partition table elements */ /******************************************************************/ /* r0 contains the address of table */ /* r1 contains index of first item */ /* r2 contains index of last item */ /* r3 contains the address of table 2 */ partition1: push {r1-r12,lr} @ save registers mov r8,r0 @ save address table 2 mov r9,r1 ldr r10,[r8,r2,lsl #2] @ load string address last index mov r4,r9 @ init with first index mov r5,r9 @ init with first index 1: @ begin loop ldr r6,[r8,r5,lsl #2] @ load string address mov r0,r6 mov r1,r10 bl comparStrings cmp r0,#0 ldrlt r7,[r8,r4,lsl #2] @ if < swap value table strlt r6,[r8,r4,lsl #2] strlt r7,[r8,r5,lsl #2] ldrlt r7,[r3,r4,lsl #2] @ swap array 2 ldrlt r12,[r3,r5,lsl #2] strlt r7,[r3,r5,lsl #2] strlt r12,[r3,r4,lsl #2] addlt r4,#1 @ and increment index 1 add r5,#1 @ increment index 2 cmp r5,r2 @ end ? blt 1b @ no -> loop ldr r7,[r8,r4,lsl #2] @ swap value str r10,[r8,r4,lsl #2] str r7,[r8,r2,lsl #2] ldr r7,[r3,r4,lsl #2] @ swap array 2 ldr r12,[r3,r2,lsl #2] str r7,[r3,r2,lsl #2] str r12,[r3,r4,lsl #2]   mov r0,r4 @ return index partition 100: pop {r1-r12,lr} bx lr /************************************/ /* Strings case sensitive comparisons */ /************************************/ /* r0 et r1 contains the address of strings */ /* return 0 in r0 if equals */ /* return -1 if string r0 < string r1 */ /* return 1 if string r0 > string r1 */ comparStrings: push {r1-r4} @ save des registres mov r2,#0 @ counter 1: ldrb r3,[r0,r2] @ byte string 1 ldrb r4,[r1,r2] @ byte string 2 cmp r3,r4 movlt r0,#-1 @ small movgt r0,#1 @ greather bne 100f @ not equals cmp r3,#0 @ 0 end string moveq r0,#0 @ equals beq 100f @ end string add r2,r2,#1 @ else add 1 in counter b 1b @ and loop 100: pop {r1-r4} bx lr   /***************************************************/ /* ROUTINES INCLUDE */ /***************************************************/ .include "../affichage.inc"  
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
#Julia
Julia
using Printf   function angdiff(a, b) r = (b - a) % 360.0 if r ≥ 180.0 r -= 360.0 end   return r end   println("Input in -180 to +180 range:") for (a, b) in [(20.0, 45.0), (-45.0, 45.0), (-85.0, 90.0), (-95.0, 90.0), (-45.0, 125.0), (-45.0, 145.0), (-45.0, 125.0), (-45.0, 145.0), (29.4803, -88.6381), (-78.3251, -159.036)] @printf("% 6.1f - % 6.1f = % 6.1f\n", a, b, angdiff(a, b)) end   println("\nInput in wider range:") for (a, b) in [(-70099.74233810938, 29840.67437876723), (-165313.6666297357, 33693.9894517456), (1174.8380510598456, -154146.66490124757), (60175.77306795546, 42213.07192354373)] @printf("% 9.1f - % 9.1f = % 6.1f\n", a, b, angdiff(a, b)) end
http://rosettacode.org/wiki/Anagrams/Deranged_anagrams
Anagrams/Deranged anagrams
Two or more words are said to be anagrams if they have the same characters, but in a different order. By analogy with derangements we define a deranged anagram as two words with the same characters, but in which the same character does not appear in the same position in both words. Task[edit] Use the word list at unixdict to find and display the longest deranged anagram. Related tasks Permutations/Derangements Best shuffle Word plays Ordered words Palindrome detection Semordnilap Anagrams Anagrams/Deranged anagrams Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#Nim
Nim
import algorithm import tables import times   var anagrams: Table[seq[char], seq[string]] # Mapping sorted_list_of chars -> list of anagrams.   #---------------------------------------------------------------------------------------------------   func deranged(s1, s2: string): bool = ## Return true if "s1" and "s2" are deranged anagrams.   for i, c in s1: if s2[i] == c: return false result = true   #---------------------------------------------------------------------------------------------------   let t0 = getTime()   # Build the anagrams table. for word in lines("unixdict.txt"): anagrams.mgetOrPut(sorted(word), @[]).add(word)   # Find the longest deranged anagrams. var bestLen = 0 var best1, best2: string for (key, list) in anagrams.pairs: if key.len > bestLen: var s1 = list[0] for i in 1..list.high: let s2 = list[i] if deranged(s1, s2): # Found a better pair. best1 = s1 best2 = s2 bestLen = s1.len break   echo "Longest deranged anagram pair: ", best1, " ", best2 echo "Processing time: ", (getTime() - t0).inMilliseconds, " ms."
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.
#Julia
Julia
function fib(n) if n < 0 throw(ArgumentError("negative arguments not allowed")) end aux(m) = m < 2 ? one(m) : aux(m-1) + aux(m-2) aux(n) end
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.
#Frink
Frink
  n = 1 seen = new set   do { n = n + 1 if seen.contains[n] next   sum = sum[allFactors[n, true, false, false]] if sum != n and sum[allFactors[sum, true, false, false]] == n { println["$n, $sum"] seen.put[sum] } } while n <= 20000  
http://rosettacode.org/wiki/Animation
Animation
Animation is integral to many parts of GUIs, including both the fancy effects when things change used in window managers, and of course games.   The core of any animation system is a scheme for periodically changing the display while still remaining responsive to the user.   This task demonstrates this. Task Create a window containing the string "Hello World! " (the trailing space is significant). Make the text appear to be rotating right by periodically removing one letter from the end of the string and attaching it to the front. When the user clicks on the (windowed) text, it should reverse its direction.
#Prolog
Prolog
:- use_module(library(pce)).   animation :- new(D, window('Animation')), new(Label, label(hello, 'Hello world ! ')), send(D, display, Label, point(1,10)), new(@animation, animation(Label)), send(D, recogniser, new(_G, my_click_gesture(left, ''))),   send(D, done_message, and(message(@animation, free), message(@receiver, destroy))), send(D, open), send(@animation?mytimer, start).     :- pce_begin_class(animation(label), object). variable(label, object, both, "Display window"). variable(delta, object, both, "increment of the angle"). variable(mytimer, timer, both, "timer of the animation").   initialise(P, W:object) :-> "Creation of the object":: send(P, label, W), send(P, delta, to_left), send(P, mytimer, new(_, timer(0.5,message(P, anim_message)))).   % method called when the object is destroyed % first the timer is stopped % then all the resources are freed unlink(P) :-> send(P?mytimer, stop), send(P, send_super, unlink).     % message processed by the timer anim_message(P) :-> get(P, label, L), get(L, selection, S), get(P, delta, Delta), compute(Delta, S, S1), new(A, name(S1)), send(L, selection, A).     :- pce_end_class.   :- pce_begin_class(my_click_gesture, click_gesture, "Click in a window").   class_variable(button, button_name, left, "By default click with left button").   terminate(G, Ev:event) :-> send(G, send_super, terminate, Ev), get(@animation, delta, D), ( D = to_left -> D1 = to_right; D1 = to_left), send(@animation, delta, D1).   :- pce_end_class.     % compute next text to be dispalyed compute(to_right, S, S1) :- get(S, size, Len), Len1 is Len - 1, get(S, sub, Len1, Str), get(S, delete_suffix, Str, V), get(Str, append, V, S1).   compute(to_left, S, S1) :- get(S, sub, 0, 1, Str), get(S, delete_prefix, Str, V), get(V, append, Str, S1).  
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.
#Julia
Julia
using Luxor using Colors using BoundaryValueDiffEq   # constants for differential equations and movie const g = 9.81 const L = 1.0 # pendulum length in meters const bobd = 0.10 # pendulum bob diameter in meters const framerate = 50.0 # intended frame rate/sec const t0 = 0.0 # start time (s) const tf = 2.3 # end simulation time (s) const dtframe = 1.0/framerate # time increment per frame const tspan = LinRange(t0, tf, Int(floor(tf*framerate))) # array of time points in animation   const bgcolor = "black" # gif background const leaderhue = (0.80, 0.70, 0.20) # gif swing arm hue light gold const hslcolors = [HSL(col) for col in (distinguishable_colors( Int(floor(tf*framerate)+3),[RGB(1,1,1)])[2:end])] const giffilename = "pendulum.gif" # output file   # differential equations simplependulum(du, u, p, t) = (θ=u[1]; dθ=u[2]; du[1]=dθ; du[2]=-(g/L)*sin(θ)) bc2(residual, u, p, t) = (residual[1] = u[end÷2][1] + pi/2; residual[2] = u[end][1] - pi/2) bvp2 = BVProblem(simplependulum, bc2, [pi/2,pi/2], (tspan[1],tspan[end])) sol2 = solve(bvp2, MIRK4(), dt=dtframe) # use the MIRK4 solver for TwoPointBVProblem   # movie making background backdrop(scene, framenumber) = background(bgcolor)   function frame(scene, framenumber) u1, u2 = sol2.u[framenumber] y, x = L*cos(u1), L*sin(u1) sethue(leaderhue) poly([Point(-4.0, 0.0), Point(4.0, 0.0), Point(160.0x,160.0y)], :fill) sethue(Colors.HSV(framenumber*4.0, 1, 1)) circle(Point(160.0x,160.0y), 160bobd, :fill) text(string("frame $framenumber of $(scene.framerange.stop)"), Point(0.0, -190.0), halign=:center) end   muv = Movie(400, 400, "Pendulum Demo", 1:length(tspan)) animate(muv, [Scene(muv, backdrop), Scene(muv, frame, easingfunction=easeinoutcubic)], creategif=true, pathname=giffilename)  
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.
#Bracmat
Bracmat
( ( Amb = first last list words word solution .  !arg:(?first.?list) & ( !list: |  !list:(.?words) ?list &  !words  :  ?  %( @(?word:!first ? @?last) & Amb$(!last.!list):?solution & !word !solution:?solution )  ? & !solution ) ) & Amb $ ( . (.the that a) (.frog elephant thing) (.walked treaded grows) (.slowly quickly) ) )
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
#AArch64_Assembly
AArch64 Assembly
  /* ARM assembly AARCH64 Raspberry PI 3B or android 64 bits */ /* program aliquotSeq64.s */   /*******************************************/ /* Constantes file */ /*******************************************/ /* for this file see task include a file in language AArch64 assembly*/ .include "../includeConstantesARM64.inc"   .equ MAXINUM, 10 .equ MAXI, 16 .equ NBDIVISORS, 1000   /*******************************************/ /* Initialized data */ /*******************************************/ .data szMessStartPgm: .asciz "Program 64 bits start \n" szMessEndPgm: .asciz "Program normal end.\n" szMessErrorArea: .asciz "\033[31mError : area divisors too small.\033[0m \n" szMessError: .asciz "\033[31m\nError  !!!\033[0m \n" szMessErrGen: .asciz "\033[31mError end program.\033[0m \n" szMessOverflow: .asciz "\033[31mOverflow function isPrime.\033[0m \n"   szCarriageReturn: .asciz "\n" szLibPerf: .asciz "Perfect \n" szLibAmic: .asciz "Amicable \n" szLibSoc: .asciz "Sociable \n" szLibAspi: .asciz "Aspiring \n" szLibCycl: .asciz "Cyclic \n" szLibTerm: .asciz "Terminating \n" szLibNoTerm: .asciz "No terminating\n"   /* datas message display */ szMessResult: .asciz " @ " szMessResHead: .asciz "Number @ :"   .align 4 tbNumber: .quad 11,12,28,496,220,1184,12496,1264460,790,909,562,1064,1488 .equ NBNUMBER, (. - tbNumber ) / 8   /*******************************************/ /* UnInitialized data */ /*******************************************/ .bss .align 4 sZoneConv: .skip 24 tbZoneDecom: .skip 8 * NBDIVISORS // facteur 4 octets tbNumberSucc: .skip 8 * MAXI /*******************************************/ /* code section */ /*******************************************/ .text .global main main: // program start ldr x0,qAdrszMessStartPgm // display start message bl affichageMess   mov x4,#1 1: mov x0,x4 // number bl aliquotClassif // aliquot classification cmp x0,#-1 // error ? beq 99f add x4,x4,#1 cmp x4,#MAXINUM ble 1b   ldr x5,qAdrtbNumber // number array mov x4,#0 2: ldr x0,[x5,x4,lsl #3] // load a number bl aliquotClassif // aliquot classification cmp x0,#-1 // error ? beq 99f add x4,x4,#1 // next number cmp x4,#NBNUMBER // maxi ? blt 2b // no -> loop   ldr x0,qAdrszMessEndPgm // display end message bl affichageMess b 100f 99: // display error message ldr x0,qAdrszMessError bl affichageMess 100: // standard end of the program mov x0, #0 // return code mov x8, #EXIT // request to exit program svc 0 // perform system call qAdrszMessStartPgm: .quad szMessStartPgm qAdrszMessEndPgm: .quad szMessEndPgm qAdrszMessError: .quad szMessError qAdrszCarriageReturn: .quad szCarriageReturn qAdrtbZoneDecom: .quad tbZoneDecom qAdrszMessResult: .quad szMessResult qAdrsZoneConv: .quad sZoneConv qAdrtbNumber: .quad tbNumber /******************************************************************/ /* function aliquot classification */ /******************************************************************/ /* x0 contains number */ aliquotClassif: stp x4,lr,[sp,-16]! // save registres stp x5,x6,[sp,-16]! // save registres stp x7,x8,[sp,-16]! // save registres mov x5,x0 // save number ldr x1,qAdrsZoneConv bl conversion10 // convert ascii string strb wzr,[x1,x0] ldr x0,qAdrszMessResHead ldr x1,qAdrsZoneConv bl strInsertAtCharInc // put in head message bl affichageMess // and display mov x0,x5 // restaur number ldr x7,qAdrtbNumberSucc // number successif array mov x4,#0 // counter number successif 1: mov x6,x0 // previous number ldr x1,qAdrtbZoneDecom bl decompFact // create area of divisors cmp x0,#0 // error ? blt 99f sub x3,x1,x6 // sum mov x0,x3 ldr x1,qAdrsZoneConv bl conversion10 // convert ascii string strb wzr,[x1,x0] ldr x0,qAdrszMessResult ldr x1,qAdrsZoneConv bl strInsertAtCharInc // and put in message bl affichageMess cmp x3,#0 // sum = zero bne 11f ldr x0,qAdrszLibTerm // terminating bl affichageMess b 100f 11: cmp x5,x3 // compare number and sum bne 4f cmp x4,#0 // first loop ? bne 2f ldr x0,qAdrszLibPerf // perfect bl affichageMess b 100f 2: cmp x4,#1 // second loop ? bne 3f ldr x0,qAdrszLibAmic // amicable bl affichageMess b 100f 3: // other loop ldr x0,qAdrszLibSoc // sociable bl affichageMess b 100f   4: cmp x6,x3 // compare sum and (sum - 1) bne 5f ldr x0,qAdrszLibAspi // aspirant bl affichageMess b 100f 5: cmp x3,#1 // if one ,no search in array beq 7f mov x2,#0 // search indice 6: // search number in array ldr x9,[x7,x2,lsl #3] cmp x9,x3 // equal ? beq 8f // yes -> cycling add x2,x2,#1 // increment indice cmp x2,x4 // end ? blt 6b // no -> loop 7: cmp x4,#MAXI blt 10f ldr x0,qAdrszLibNoTerm // no terminating bl affichageMess b 100f 8: // cycling ldr x0,qAdrszLibCycl bl affichageMess b 100f   10: str x3,[x7,x4,lsl #3] // store new sum in array add x4,x4,#1 // increment counter mov x0,x3 // new number = new sum b 1b // and loop   99: // display error ldr x0,qAdrszMessError bl affichageMess mov x0,-1 100: ldp x7,x8,[sp],16 // restaur des 2 registres ldp x5,x6,[sp],16 // restaur des 2 registres ldp x4,lr,[sp],16 // restaur des 2 registres ret qAdrszMessResHead: .quad szMessResHead qAdrszLibPerf: .quad szLibPerf qAdrszLibAmic: .quad szLibAmic qAdrszLibSoc: .quad szLibSoc qAdrszLibCycl: .quad szLibCycl qAdrszLibAspi: .quad szLibAspi qAdrszLibNoTerm: .quad szLibNoTerm qAdrszLibTerm: .quad szLibTerm qAdrtbNumberSucc: .quad tbNumberSucc /******************************************************************/ /* decomposition en facteur */ /******************************************************************/ /* x0 contient le nombre à decomposer */ /* x1 contains factor area address */ decompFact: stp x3,lr,[sp,-16]! // save registres stp x4,x5,[sp,-16]! // save registres stp x6,x7,[sp,-16]! // save registres stp x8,x9,[sp,-16]! // save registres stp x10,x11,[sp,-16]! // save registres mov x5,x1 mov x1,x0 cmp x0,1 beq 100f mov x8,x0 // save number bl isPrime // prime ? cmp x0,#1 beq 98f // yes is prime mov x1,#1 str x1,[x5] // first factor mov x12,#1 // divisors sum mov x4,#1 // indice divisors table mov x1,#2 // first divisor mov x6,#0 // previous divisor mov x7,#0 // number of same divisors 2: mov x0,x8 // dividende udiv x2,x0,x1 // x1 divisor x2 quotient x3 remainder msub x3,x2,x1,x0 cmp x3,#0 bne 5f // if remainder <> zero -> no divisor mov x8,x2 // else quotient -> new dividende cmp x1,x6 // same divisor ? beq 4f // yes mov x7,x4 // number factors in table mov x9,#0 // indice 21: ldr x10,[x5,x9,lsl #3 ] // load one factor mul x10,x1,x10 // multiply str x10,[x5,x7,lsl #3] // and store in the table adds x12,x12,x10 bcs 99f add x7,x7,#1 // and increment counter add x9,x9,#1 cmp x9,x4 blt 21b mov x4,x7 mov x6,x1 // new divisor b 7f 4: // same divisor sub x9,x4,#1 mov x7,x4 41: ldr x10,[x5,x9,lsl #3 ] cmp x10,x1 sub x13,x9,1 csel x9,x13,x9,ne bne 41b sub x9,x4,x9 42: ldr x10,[x5,x9,lsl #3 ] mul x10,x1,x10 str x10,[x5,x7,lsl #3] // and store in the table adds x12,x12,x10 bcs 99f add x7,x7,#1 // and increment counter add x9,x9,#1 cmp x9,x4 blt 42b mov x4,x7 b 7f // and loop   /* not divisor -> increment next divisor */ 5: cmp x1,#2 // if divisor = 2 -> add 1 add x13,x1,#1 // add 1 add x14,x1,#2 // else add 2 csel x1,x13,x14,eq b 2b   /* divisor -> test if new dividende is prime */ 7: mov x3,x1 // save divisor cmp x8,#1 // dividende = 1 ? -> end beq 10f mov x0,x8 // new dividende is prime ? mov x1,#0 bl isPrime // the new dividende is prime ? cmp x0,#1 bne 10f // the new dividende is not prime   cmp x8,x6 // else dividende is same divisor ? beq 9f // yes mov x7,x4 // number factors in table mov x9,#0 // indice 71: ldr x10,[x5,x9,lsl #3 ] // load one factor mul x10,x8,x10 // multiply str x10,[x5,x7,lsl #3] // and store in the table adds x12,x12,x10 bcs 99f add x7,x7,#1 // and increment counter add x9,x9,#1 cmp x9,x4 blt 71b mov x4,x7 mov x7,#0 b 11f 9: sub x9,x4,#1 mov x7,x4 91: ldr x10,[x5,x9,lsl #3 ] cmp x10,x8 sub x13,x9,#1 csel x9,x13,x9,ne bne 91b sub x9,x4,x9 92: ldr x10,[x5,x9,lsl #3 ] mul x10,x8,x10 str x10,[x5,x7,lsl #3] // and store in the table adds x12,x12,x10 bcs 99f // overflow add x7,x7,#1 // and increment counter add x9,x9,#1 cmp x9,x4 blt 92b mov x4,x7 b 11f   10: mov x1,x3 // current divisor = new divisor cmp x1,x8 // current divisor > new dividende ? ble 2b // no -> loop   /* end decomposition */ 11: mov x0,x4 // return number of table items mov x1,x12 // return sum mov x3,#0 str x3,[x5,x4,lsl #3] // store zéro in last table item b 100f     98: add x1,x8,1 mov x0,#0 // return code b 100f 99: ldr x0,qAdrszMessError bl affichageMess mov x0,#-1 // error code b 100f     100: ldp x10,x11,[sp],16 // restaur des 2 registres ldp x8,x9,[sp],16 // restaur des 2 registres ldp x6,x7,[sp],16 // restaur des 2 registres ldp x4,x5,[sp],16 // restaur des 2 registres ldp x3,lr,[sp],16 // restaur des 2 registres ret // retour adresse lr x30 qAdrszMessErrGen: .quad szMessErrGen /***************************************************/ /* Verification si un nombre est premier */ /***************************************************/ /* x0 contient le nombre à verifier */ /* x0 retourne 1 si premier 0 sinon */ isPrime: stp x1,lr,[sp,-16]! // save registres stp x2,x3,[sp,-16]! // save registres mov x2,x0 sub x1,x0,#1 cmp x2,0 beq 99f // retourne zéro cmp x2,2 // pour 1 et 2 retourne 1 ble 2f mov x0,#2 bl moduloPux64 bcs 100f // erreur overflow cmp x0,#1 bne 99f // Pas premier cmp x2,3 beq 2f mov x0,#3 bl moduloPux64 blt 100f // erreur overflow cmp x0,#1 bne 99f   cmp x2,5 beq 2f mov x0,#5 bl moduloPux64 bcs 100f // erreur overflow cmp x0,#1 bne 99f // Pas premier   cmp x2,7 beq 2f mov x0,#7 bl moduloPux64 bcs 100f // erreur overflow cmp x0,#1 bne 99f // Pas premier   cmp x2,11 beq 2f mov x0,#11 bl moduloPux64 bcs 100f // erreur overflow cmp x0,#1 bne 99f // Pas premier   cmp x2,13 beq 2f mov x0,#13 bl moduloPux64 bcs 100f // erreur overflow cmp x0,#1 bne 99f // Pas premier 2: cmn x0,0 // carry à zero pas d'erreur mov x0,1 // premier b 100f 99: cmn x0,0 // carry à zero pas d'erreur mov x0,#0 // Pas premier 100: ldp x2,x3,[sp],16 // restaur des 2 registres ldp x1,lr,[sp],16 // restaur des 2 registres ret // retour adresse lr x30   /**************************************************************/ /********************************************************/ /* Calcul modulo de b puissance e modulo m */ /* Exemple 4 puissance 13 modulo 497 = 445 */ /********************************************************/ /* x0 nombre */ /* x1 exposant */ /* x2 modulo */ moduloPux64: stp x1,lr,[sp,-16]! // save registres stp x3,x4,[sp,-16]! // save registres stp x5,x6,[sp,-16]! // save registres stp x7,x8,[sp,-16]! // save registres stp x9,x10,[sp,-16]! // save registres cbz x0,100f cbz x1,100f mov x8,x0 mov x7,x1 mov x6,1 // resultat udiv x4,x8,x2 msub x9,x4,x2,x8 // contient le reste 1: tst x7,1 beq 2f mul x4,x9,x6 umulh x5,x9,x6 mov x6,x4 mov x0,x6 mov x1,x5 bl divisionReg128U cbnz x1,99f // overflow mov x6,x3 2: mul x8,x9,x9 umulh x5,x9,x9 mov x0,x8 mov x1,x5 bl divisionReg128U cbnz x1,99f // overflow mov x9,x3 lsr x7,x7,1 cbnz x7,1b mov x0,x6 // result cmn x0,0 // carry à zero pas d'erreur b 100f 99: ldr x0,qAdrszMessOverflow bl affichageMess cmp x0,0 // carry à un car erreur mov x0,-1 // code erreur   100: ldp x9,x10,[sp],16 // restaur des 2 registres ldp x7,x8,[sp],16 // restaur des 2 registres ldp x5,x6,[sp],16 // restaur des 2 registres ldp x3,x4,[sp],16 // restaur des 2 registres ldp x1,lr,[sp],16 // restaur des 2 registres ret // retour adresse lr x30 qAdrszMessOverflow: .quad szMessOverflow /***************************************************/ /* division d un nombre de 128 bits par un nombre de 64 bits */ /***************************************************/ /* x0 contient partie basse dividende */ /* x1 contient partie haute dividente */ /* x2 contient le diviseur */ /* x0 retourne partie basse quotient */ /* x1 retourne partie haute quotient */ /* x3 retourne le reste */ divisionReg128U: stp x6,lr,[sp,-16]! // save registres stp x4,x5,[sp,-16]! // save registres mov x5,#0 // raz du reste R mov x3,#128 // compteur de boucle mov x4,#0 // dernier bit 1: lsl x5,x5,#1 // on decale le reste de 1 tst x1,1<<63 // test du bit le plus à gauche lsl x1,x1,#1 // on decale la partie haute du quotient de 1 beq 2f orr x5,x5,#1 // et on le pousse dans le reste R 2: tst x0,1<<63 lsl x0,x0,#1 // puis on decale la partie basse beq 3f orr x1,x1,#1 // et on pousse le bit de gauche dans la partie haute 3: orr x0,x0,x4 // position du dernier bit du quotient mov x4,#0 // raz du bit cmp x5,x2 blt 4f sub x5,x5,x2 // on enleve le diviseur du reste mov x4,#1 // dernier bit à 1 4: // et boucle subs x3,x3,#1 bgt 1b lsl x1,x1,#1 // on decale le quotient de 1 tst x0,1<<63 lsl x0,x0,#1 // puis on decale la partie basse beq 5f orr x1,x1,#1 5: orr x0,x0,x4 // position du dernier bit du quotient mov x3,x5 100: ldp x4,x5,[sp],16 // restaur des 2 registres ldp x6,lr,[sp],16 // restaur des 2 registres ret // retour adresse lr x30   /********************************************************/ /* File Include fonctions */ /********************************************************/ /* for this file see task include a file in language AArch64 assembly */ .include "../includeARM64.inc"  
http://rosettacode.org/wiki/Address_of_a_variable
Address of a variable
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation | Comparison | Matching Memory Operations Pointers & references | Addresses Task Demonstrate how to get the address of a variable and how to set the address of a variable.
#ALGOL_68
ALGOL 68
[4]INT test := (222,444,666,888); REF INT reference := test[3]; REF INT(reference) := reference + 111; print(("test value is now: ",test))
http://rosettacode.org/wiki/Address_of_a_variable
Address of a variable
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation | Comparison | Matching Memory Operations Pointers & references | Addresses Task Demonstrate how to get the address of a variable and how to set the address of a variable.
#Applesoft_BASIC
Applesoft BASIC
N = N : PRINT PEEK (131) + PEEK (132) * 256
http://rosettacode.org/wiki/Address_of_a_variable
Address of a variable
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation | Comparison | Matching Memory Operations Pointers & references | Addresses Task Demonstrate how to get the address of a variable and how to set the address of a variable.
#Argile
Argile
use std, array (: array.arg also defines pointer operators :) let var = 42 let ptr = &var (: value of ptr is address of var :) print var (: prints 42 :) (*ptr)++ (: increments value pointed by ptr :) print var (: prints 43 :)
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.
#11l
11l
F expand_x_1(p) V ex = [BigInt(1)] L(i) 0 .< p ex.append(ex.last * -(p - i) I/ (i + 1)) R reversed(ex)   F aks_test(p) I p < 2 R 0B V ex = expand_x_1(p) ex[0]++ R !any(ex[0 .< (len)-1].map(mult -> mult % @p != 0))   print(‘# p: (x-1)^p for small p’) L(p) 12 print(‘#3: #.’.format(p, enumerate(expand_x_1(p)).map((n, e) -> ‘#.#.#.’.format(‘+’ * (e >= 0), e, I n {(‘x^#.’.format(n))} E ‘’)).join(‘ ’)))   print("\n# small primes using the aks test") print((0..100).filter(p -> aks_test(p)))
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.
#11l
11l
F is_prime(a) I a == 2 R 1B I a < 2 | a % 2 == 0 R 0B L(i) (3 .. Int(sqrt(a))).step(2) I a % i == 0 R 0B R 1B   F digit_sum(=n) V sum = 0 L n > 0 sum += n % 10 n I/= 10 R sum   V additive_primes = 0 L(i) 2..499 I is_prime(i) & is_prime(digit_sum(i)) additive_primes++ print(i, end' ‘ ’) print("\nFound "additive_primes‘ additive primes less than 500’)
http://rosettacode.org/wiki/Algebraic_data_types
Algebraic data types
Some languages offer direct support for algebraic data types and pattern matching on them. While this of course can always be simulated with manual tagging and conditionals, it allows for terse code which is easy to read, and can represent the algorithm directly. Task As an example, implement insertion in a red-black-tree. A red-black-tree is a binary tree where each internal node has a color attribute red or black. Moreover, no red node can have a red child, and every path from the root to an empty node must contain the same number of black nodes. As a consequence, the tree is balanced, and must be re-balanced after an insertion. Reference Red-Black Trees in a Functional Setting
#Elixir
Elixir
defmodule RBtree do def find(nil, _), do: :not_found def find({ key, value, _, _, _ }, key), do: { :found, { key, value } } def find({ key1, _, _, left, _ }, key) when key < key1, do: find(left, key) def find({ key1, _, _, _, right }, key) when key > key1, do: find(right, key)   def new(key, value), do: ins(nil, key, value) |> make_black   def insert(tree, key, value), do: ins(tree, key, value) |> make_black   defp ins(nil, key, value), do: { key, value, :r, nil, nil } defp ins({ key, _, color, left, right }, key, value), do: { key, value, color, left, right } defp ins({ ky, vy, cy, ly, ry }, key, value) when key < ky, do: balance({ ky, vy, cy, ins(ly, key, value), ry }) defp ins({ ky, vy, cy, ly, ry }, key, value) when key > ky, do: balance({ ky, vy, cy, ly, ins(ry, key, value) })   defp make_black({ key, value, _, left, right }), do: { key, value, :b, left, right }   defp balance({ kx, vx, :b, lx, { ky, vy, :r, ly, { kz, vz, :r, lz, rz } } }), do: { ky, vy, :r, { kx, vx, :b, lx, ly }, { kz, vz, :b, lz, rz } } defp balance({ kx, vx, :b, lx, { ky, vy, :r, { kz, vz, :r, lz, rz }, ry } }), do: { kz, vz, :r, { kx, vx, :b, lx, lz }, { ky, vy, :b, rz, ry } } defp balance({ kx, vx, :b, { ky, vy, :r, { kz, vz, :r, lz, rz }, ry }, rx }), do: { ky, vy, :r, { kz, vz, :b, lz, rz }, { kx, vx, :b, ry, rx } } defp balance({ kx, vx, :b, { ky, vy, :r, ly, { kz, vz, :r, lz, rz } }, rx }), do: { kz, vz, :r, { ky, vy, :b, ly, lz }, { kx, vx, :b, rz, rx } } defp balance(t), do: t end   RBtree.new(0,3) |> IO.inspect |> RBtree.insert(1,5) |> IO.inspect |> RBtree.insert(2,-1) |> IO.inspect |> RBtree.insert(3,7) |> IO.inspect |> RBtree.insert(4,-3) |> IO.inspect |> RBtree.insert(5,0) |> IO.inspect |> RBtree.insert(6,-1) |> IO.inspect |> RBtree.insert(7,0) |> IO.inspect |> RBtree.find(4) |> IO.inspect
http://rosettacode.org/wiki/Algebraic_data_types
Algebraic data types
Some languages offer direct support for algebraic data types and pattern matching on them. While this of course can always be simulated with manual tagging and conditionals, it allows for terse code which is easy to read, and can represent the algorithm directly. Task As an example, implement insertion in a red-black-tree. A red-black-tree is a binary tree where each internal node has a color attribute red or black. Moreover, no red node can have a red child, and every path from the root to an empty node must contain the same number of black nodes. As a consequence, the tree is balanced, and must be re-balanced after an insertion. Reference Red-Black Trees in a Functional Setting
#Emacs_Lisp
Emacs Lisp
(defun rbt-balance (tree) (pcase tree (`(B (R (R ,a ,x ,b) ,y ,c) ,z ,d) `(R (B ,a ,x ,b) ,y (B ,c ,z ,d))) (`(B (R ,a ,x (R ,b ,y ,c)) ,z ,d) `(R (B ,a ,x ,b) ,y (B ,c ,z ,d))) (`(B ,a ,x (R (R ,b ,y ,c) ,z ,d)) `(R (B ,a ,x ,b) ,y (B ,c ,z ,d))) (`(B ,a ,x (R ,b ,y (R ,c ,z ,d))) `(R (B ,a ,x ,b) ,y (B ,c ,z ,d))) (_ tree)))   (defun rbt-insert- (x s) (pcase s (`nil `(R nil ,x nil)) (`(,color ,a ,y ,b) (cond ((< x y) (rbt-balance `(,color ,(rbt-insert- x a) ,y ,b))) ((> x y) (rbt-balance `(,color ,a ,y ,(rbt-insert- x b)))) (t s))) (_ (error "Expected tree: %S" s))))   (defun rbt-insert (x s) (pcase (rbt-insert- x s) (`(,_ ,a ,y ,b) `(B ,a ,y ,b)) (_ (error "Internal error: %S" s))))   (let ((s nil)) (dotimes (i 16) (setq s (rbt-insert (1+ i) s))) (pp s))
http://rosettacode.org/wiki/Almost_prime
Almost prime
A   k-Almost-prime   is a natural number   n {\displaystyle n}   that is the product of   k {\displaystyle k}   (possibly identical) primes. Example 1-almost-primes,   where   k = 1 {\displaystyle k=1} ,   are the prime numbers themselves. 2-almost-primes,   where   k = 2 {\displaystyle k=2} ,   are the   semiprimes. Task Write a function/method/subroutine/... that generates k-almost primes and use it to create a table here of the first ten members of k-Almost primes for   1 <= K <= 5 {\displaystyle 1<=K<=5} . Related tasks   Semiprime   Category:Prime Numbers
#Clojure
Clojure
    (ns clojure.examples.almostprime (:gen-class))   (defn divisors [n] " Finds divisors by looping through integers 2, 3,...i.. up to sqrt (n) [note: rather than compute sqrt(), test with i*i <=n] " (let [div (some #(if (= 0 (mod n %)) % nil) (take-while #(<= (* % %) n) (iterate inc 2)))] (if div ; div = nil (if no divisor found else its the divisor) (into [] (concat (divisors div) (divisors (/ n div)))) ; Concat the two divisors of the two divisors [n]))) ; Number is prime so only itself as a divisor   (defn divisors-k [k n] " Finds n numbers with k divisors. Does this by looping through integers 2, 3, ... filtering (passing) ones with k divisors and taking the first n " (->> (iterate inc 2) ; infinite sequence of numbers starting at 2 (map divisors) ; compute divisor of each element of sequence (filter #(= (count %) k)) ; filter to take only elements with k divisors (take n) ; take n elements from filtered sequence (map #(apply * %)))) ; compute number by taking product of divisors   (println (for [k (range 1 6)] (println "k:" k (divisors-k k 10))))   }
http://rosettacode.org/wiki/Anagrams
Anagrams
When two or more words are composed of the same characters, but in a different order, they are called anagrams. Task[edit] Using the word list at   http://wiki.puzzlers.org/pub/wordlists/unixdict.txt, find the sets of words that share the same characters that contain the most words in them. Related tasks Word plays Ordered words Palindrome detection Semordnilap Anagrams Anagrams/Deranged anagrams Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#Arturo
Arturo
wordset: map read.lines relative "unixdict.txt" => strip   anagrams: #[]   loop wordset 'word [ anagram: sort to [:char] word unless key? anagrams anagram -> anagrams\[anagram]: new []   anagrams\[anagram]: anagrams\[anagram] ++ word ]   loop select values anagrams 'x [5 =< size x] 'words -> print join.with:", " words
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
#K
K
  / Angle difference between two angles / angledif.k   angdif: {[b1;b2]; :[(r:(b2-b1)!360.0)<-180.0;r+:360.0;r>180.0;r-:360.0];:r}  
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
#OCaml
OCaml
let sort_chars s = let r = String.copy s in for i = 0 to (String.length r) - 2 do for j = i + 1 to (String.length r) - 1 do if r.[i] > r.[j] then begin let tmp = r.[i] in r.[i] <- r.[j]; r.[j] <- tmp; end done done; (r)   let deranged (s1, s2) = let len1 = String.length s1 and len2 = String.length s2 in if len1 <> len2 then false else try for i = 0 to pred len1 do if s1.[i] = s2.[i] then raise Exit done; true with Exit -> false   let pairs_of_list lst = let rec aux acc = function | [] -> acc | x::xs -> aux (List.fold_left (fun acc y -> (x,y)::acc) acc xs) xs in aux [] lst   let () = let h = Hashtbl.create 3571 in let ic = open_in "unixdict.txt" in try while true do let word = input_line ic in let key = sort_chars word in let l = try Hashtbl.find h key with Not_found -> [] in Hashtbl.replace h key (word::l); done with End_of_file -> close_in ic; let lst = Hashtbl.fold (fun _ lw acc -> if List.length lw < 2 then acc else lw::acc) h [] in let lst = List.fold_left (fun acc anagrams -> let pairs = pairs_of_list anagrams in (List.filter deranged pairs) @ acc ) [] lst in let res, _ = List.fold_left (fun (res, n) (w1, w2) -> let len = String.length w1 in match Pervasives.compare len n with | 0 -> ((w1, w2)::res, n) | 1 -> ([w1, w2], len) | _ -> (res, n) ) ([], 0) lst in List.iter (fun (w1, w2) -> Printf.printf "%s, %s\n" w1 w2) res
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.
#K
K
fib: {:[x<0; "Error Negative Number"; {:[x<2;x;_f[x-2]+_f[x-1]]}x]}
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.
#Futhark
Futhark
  fun divisors(n: int): []int = filter (fn x => n%x == 0) (map (1+) (iota (n/2)))   fun amicable((n: int, nd: int), (m: int, md: int)): bool = n < m && nd == m && md == n   fun getPair (divs: [upper](int, int)) (flat_i: int): ((int,int), (int,int)) = let i = flat_i / upper let j = flat_i % upper in unsafe (divs[i], divs[j])   fun main(upper: int): [][2]int = let range = map (1+) (iota upper) let divs = zip range (map (fn n => reduce (+) 0 (divisors n)) range) let amicable = filter amicable (map (getPair divs) (iota (upper*upper))) in map (fn (np,mp) => [#1 np, #1 mp]) amicable  
http://rosettacode.org/wiki/Animation
Animation
Animation is integral to many parts of GUIs, including both the fancy effects when things change used in window managers, and of course games.   The core of any animation system is a scheme for periodically changing the display while still remaining responsive to the user.   This task demonstrates this. Task Create a window containing the string "Hello World! " (the trailing space is significant). Make the text appear to be rotating right by periodically removing one letter from the end of the string and attaching it to the front. When the user clicks on the (windowed) text, it should reverse its direction.
#PureBasic
PureBasic
OpenWindow(0,0,0,500,100,"Hello World!",#PB_Window_ScreenCentered|#PB_Window_SystemMenu)   text$ = "Hello World! " direction = 1   LoadFont(0,"",60) ButtonGadget(0,2,2,496,96,text$) : SetGadgetFont(0,FontID(0))   Repeat event = WaitWindowEvent(50) Select event Case #PB_Event_Gadget If EventGadget() = 0 direction*-1 EndIf Case #PB_Event_CloseWindow End EndSelect   If ElapsedMilliseconds()-tick > 400 offset+direction If offset > Len(text$)-1 offset = 0 ElseIf offset < 0 offset = Len(text$)-1 EndIf SetGadgetText(0,Mid(text$,offset+1)+Left(text$,offset)) tick = ElapsedMilliseconds() EndIf ForEver
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.
#Kotlin
Kotlin
import java.awt.* import java.util.concurrent.* import javax.swing.*   class Pendulum(private val length: Int) : JPanel(), Runnable { init { val f = JFrame("Pendulum") f.add(this) f.defaultCloseOperation = JFrame.EXIT_ON_CLOSE f.pack() f.isVisible = true isDoubleBuffered = true }   override fun paint(g: Graphics) { with(g) { color = Color.WHITE fillRect(0, 0, width, height) color = Color.BLACK val anchor = Element(width / 2, height / 4) val ball = Element((anchor.x + Math.sin(angle) * length).toInt(), (anchor.y + Math.cos(angle) * length).toInt()) drawLine(anchor.x, anchor.y, ball.x, ball.y) fillOval(anchor.x - 3, anchor.y - 4, 7, 7) fillOval(ball.x - 7, ball.y - 7, 14, 14) } }   override fun run() { angleVelocity += -9.81 / length * Math.sin(angle) * dt angle += angleVelocity * dt repaint() }   override fun getPreferredSize() = Dimension(2 * length + 50, length / 2 * 3)   private data class Element(val x: Int, val y: Int)   private val dt = 0.1 private var angle = Math.PI / 2 private var angleVelocity = 0.0 }   fun main(a: Array<String>) { val executor = Executors.newSingleThreadScheduledExecutor() executor.scheduleAtFixedRate(Pendulum(200), 0, 15, TimeUnit.MILLISECONDS) }
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.
#C
C
typedef const char * amb_t;   amb_t amb(size_t argc, ...) { amb_t *choices; va_list ap; int i;   if(argc) { choices = malloc(argc*sizeof(amb_t)); va_start(ap, argc); i = 0; do { choices[i] = va_arg(ap, amb_t); } while(++i < argc); va_end(ap);   i = 0; do { TRY(choices[i]); } while(++i < argc); free(choices); }   FAIL; }   int joins(const char *left, const char *right) { return left[strlen(left)-1] == right[0]; }   int _main() { const char *w1,*w2,*w3,*w4;   w1 = amb(3, "the", "that", "a"); w2 = amb(3, "frog", "elephant", "thing"); w3 = amb(3, "walked", "treaded", "grows"); w4 = amb(2, "slowly", "quickly");   if(!joins(w1, w2)) amb(0); if(!joins(w2, w3)) amb(0); if(!joins(w3, w4)) amb(0);   printf("%s %s %s %s\n", w1, w2, w3, w4);   return EXIT_SUCCESS; }
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
#ALGOL_68
ALGOL 68
BEGIN # aliquot sequence classification # # maximum sequence length we consider # INT max sequence length = 16; # possible classifications # STRING perfect classification = "perfect "; STRING amicable classification = "amicable "; STRING sociable classification = "sociable "; STRING aspiring classification = "aspiring "; STRING cyclic classification = "cyclic "; STRING terminating classification = "terminating "; STRING non terminating classification = "non terminating"; # structure to hold an aliquot sequence and its classification # MODE ALIQUOT = STRUCT( STRING classification , [ 1 : max sequence length ]LONG INT sequence , INT length ); # maximum value for sequence elements - if any element is more than this, # # we assume it is non-teriminating # LONG INT max element = 140 737 488 355 328; # returns the sum of the proper divisors of n # OP DIVISORSUM = ( LONG INT n )LONG INT: BEGIN LONG INT abs n = ABS n; IF abs n < 2 THEN 0 # -1, 0 and 1 have no proper divisors # ELSE # have a number with possible divisors # LONG INT result := 1; # 1 is always a divisor # # a FOR loop counter can only be an INT, hence the WHILE loop # LONG INT d := ENTIER long sqrt( abs n ); WHILE d > 1 DO IF abs n MOD d = 0 THEN # found another divisor # result +:= d; IF d * d /= abs n THEN # add the other divisor # result +:= abs n OVER d FI FI; d -:= 1 OD; result FI END # DIVISORSUM # ; # generates the aliquot sequence of the number k and its classification # # at most max elements of the sequence are considered # OP CLASSIFY = ( LONG INT k )ALIQUOT : BEGIN ALIQUOT result; classification OF result := "non-terminating"; INT lb = LWB sequence OF result; INT ub = UPB sequence OF result; ( sequence OF result )[ lb ] := k; # the first element is always k # length OF result := 1; FOR i FROM lb + 1 TO ub DO ( sequence OF result )[ i ] := 0 OD; BOOL classified := FALSE; LONG INT prev k := k; FOR i FROM lb + 1 TO ub WHILE NOT classified DO length OF result +:= 1; LONG INT next k := ( sequence OF result )[ i ] := DIVISORSUM prev k; classified := TRUE; IF next k = 0 THEN # the sequence terminates # classification OF result := terminating classification ELIF next k > max element THEN # the sequence gets too large # classification OF result := non terminating classification ELIF next k = k THEN # the sequence that returns to k # classification OF result := IF i = lb + 1 THEN perfect classification ELIF i = lb + 2 THEN amicable classification ELSE sociable classification FI ELIF next k = prev k THEN # the sequence repeats with non-k # classification OF result := aspiring classification ELSE # check for repeating sequence with a period more than 1 # classified := FALSE; FOR prev pos FROM lb TO i - 2 WHILE NOT classified DO IF classified := ( sequence OF result )[ prev pos ] = next k THEN # found a repeatition # classification OF result := cyclic classification FI OD FI; prev k := next k OD; result END # CLASSIFY # ; # test cases as per the task # []LONG INT test cases = ( 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 , 11, 12, 28, 496, 220, 1184, 12496, 1264460, 790, 909 , 562, 1064, 1488 , 15355717786080 ); FOR i FROM LWB test cases TO UPB test cases DO LONG INT k := test cases[ i ]; ALIQUOT seq = CLASSIFY k; print( ( whole( k, -14 ), ": ", classification OF seq, ":" ) ); FOR e FROM LWB sequence OF seq + 1 TO length OF seq DO print( ( " ", whole( ( sequence OF seq )[ e ], 0 ) ) ) OD; print( ( newline ) ) OD END
http://rosettacode.org/wiki/Address_of_a_variable
Address of a variable
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation | Comparison | Matching Memory Operations Pointers & references | Addresses Task Demonstrate how to get the address of a variable and how to set the address of a variable.
#ARM_Assembly
ARM Assembly
    /* ARM assembly Raspberry PI */ /* program adrvar.s */   /* Constantes */ .equ STDOUT, 1 .equ WRITE, 4 .equ EXIT, 1 /* Initialized data */ .data szMessage: .asciz "Hello. \n " @ message szRetourLigne: .asciz "\n" iValDeb: .int 5 @ value 5 in array of 4 bytes /* No Initialized data */ .bss iValeur: .skip 4 @ reserve 4 bytes in memory   .text .global main main: ldr r0,=szMessage @ adresse of message short program bl affichageMess @ call function @ or ldr r0,iAdrszMessage @ adresse of message big program (size code > 4K) bl affichageMess @ call function   ldr r1,=iValDeb @ adresse of variable -> r1 short program ldr r0,[r1] @ value of iValdeb -> r0 ldr r1,iAdriValDeb @ adresse of variable -> r1 big program ldr r0,[r1] @ value of iValdeb -> r0     /* set variables */ ldr r1,=iValeur @ adresse of variable -> r1 short program str r0,[r1] @ value of r0 -> iValeur ldr r1,iAdriValeur @ adresse of variable -> r1 big program str r0,[r1] @ value of r0 -> iValeur     /* end of program */ mov r0, #0 @ return code mov r7, #EXIT @ request to exit program swi 0 @ perform the system call iAdriValDeb: .int iValDeb iAdriValeur: .int iValeur iAdrszMessage: .int szMessage iAdrszRetourLigne: .int szRetourLigne /******************************************************************/ /* affichage des messages avec calcul longueur */ /******************************************************************/ /* r0 contient l adresse du message */ affichageMess: push {fp,lr} /* save des 2 registres */ push {r0,r1,r2,r7} /* save des autres registres */ mov r2,#0 /* compteur longueur */ 1: /*calcul de la longueur */ ldrb r1,[r0,r2] /* recup octet position debut + indice */ cmp r1,#0 /* si 0 c est fini */ beq 1f add r2,r2,#1 /* sinon on ajoute 1 */ b 1b 1: /* donc ici r2 contient la longueur du message */ mov r1,r0 /* adresse du message en r1 */ mov r0,#STDOUT /* code pour écrire sur la sortie standard Linux */ mov r7, #WRITE /* code de l appel systeme 'write' */ swi #0 /* appel systeme */ pop {r0,r1,r2,r7} /* restaur des autres registres */ pop {fp,lr} /* restaur des 2 registres */ bx lr /* retour procedure */    
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.
#8th
8th
  with: a   : nextrow \ a -- a len [ ( drop [1] ), ( drop [1,1] ), ( ' n:+ y 1 slide 1 push ) ] swap 2 min caseof ;   ;with   with: n   : .x \ n -- dup [ ( drop ), ( drop "x" . ), ( "x^" . . ) ] swap 2 min caseof space ;   : .term \ coef exp -- ; omit coef for 1x^n when n > 0 over 1 = over 0 > and if nip .x else swap . .x then ;   : .sgn \ +/-1 -- [ "-", null, "+" ] swap 1+ caseof . space ;   : .lhs \ n -- "(x-1)^" . . ;   : .rhs \ a -- a a:len 1- >r 1 swap ( third .sgn r@ rot - .term -1 * ) a:each nip rdrop ;   : .eqn \ a -- a a:len 1- .lhs " = " . .rhs ;   : .binomials \ -- [] ( nextrow .eqn cr ) 8 times drop ;   : primerow? \ a -- a ? a:len 3 < if false ;then 1 a:@ >r \ 2nd position is the number to check for primality true swap ( nip dup 1 = swap r@ mod 0 = or and ) a:each swap rdrop ;   : .primes-via-aks \ -- [] ( nextrow primerow? if 1 a:@ . space then ) 50 times drop ;   ;with   .binomials cr "The primes upto 50 are (via AKS): " . .primes-via-aks cr   bye
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.
#AArch64_Assembly
AArch64 Assembly
  /* ARM assembly AARCH64 Raspberry PI 3B or android 64 bits */ /* program additivePrime64.s */   /*******************************************/ /* Constantes file */ /*******************************************/ /* for this file see task include a file in language AArch64 assembly*/ .include "../includeConstantesARM64.inc"   .equ MAXI, 500   /*********************************/ /* Initialized data */ /*********************************/ .data szMessResult: .asciz "Prime  : @ \n" szMessCounter: .asciz "Number found : @ \n" szCarriageReturn: .asciz "\n"   /*********************************/ /* UnInitialized data */ /*********************************/ .bss sZoneConv: .skip 24 TablePrime: .skip 8 * MAXI /*********************************/ /* code section */ /*********************************/ .text .global main main: // entry of program   bl createArrayPrime mov x5,x0 // prime number   ldr x4,qAdrTablePrime // address prime table mov x10,#0 // init counter mov x6,#0 // indice 1: ldr x2,[x4,x6,lsl #3] // load prime mov x9,x2 // save prime mov x7,#0 // init digit sum mov x1,#10 // divisor 2: // begin loop mov x0,x2 // dividende udiv x2,x0,x1 msub x3,x2,x1,x0 // compute remainder add x7,x7,x3 // add digit to digit sum cmp x2,#0 // quotient null ? bne 2b // no -> comppute other digit   mov x8,#1 // indice 4: // prime search loop cmp x8,x5 // maxi ? bge 5f // yes ldr x0,[x4,x8,lsl #3] // load prime cmp x0,x7 // prime >= digit sum ? add x0,x8,1 csel x8,x0,x8,lt // no -> increment indice blt 4b // and loop bne 5f // > mov x0,x9 // equal bl displayPrime add x10,x10,#1 // increment counter 5: add x6,x6,#1 // increment first indice cmp x6,x5 // maxi ? blt 1b // and loop   mov x0,x10 // number counter ldr x1,qAdrsZoneConv bl conversion10 // call décimal conversion ldr x0,qAdrszMessCounter ldr x1,qAdrsZoneConv // insert conversion in message bl strInsertAtCharInc bl affichageMess // display message   100: // standard end of the program mov x0, #0 // return code mov x8, #EXIT // request to exit program svc #0 // perform the system call qAdrszCarriageReturn: .quad szCarriageReturn qAdrszMessResult: .quad szMessResult qAdrszMessCounter: .quad szMessCounter qAdrTablePrime: .quad TablePrime /******************************************************************/ /* créate prime array */ /******************************************************************/ createArrayPrime: stp x1,lr,[sp,-16]! // save registres ldr x4,qAdrTablePrime // address prime table mov x0,#1 str x0,[x4] // store 1 in array mov x0,#2 str x0,[x4,#8] // store 2 in array mov x0,#3 str x0,[x4,#16] // store 3 in array mov x5,#3 // prine counter mov x7,#5 // first number to test 1: mov x6,#1 // indice 2: mov x0,x7 // dividende ldr x1,[x4,x6,lsl #3] // load divisor udiv x2,x0,x1 msub x3,x2,x1,x0 // compute remainder cmp x3,#0 // null remainder ? beq 4f // yes -> end loop cmp x2,x1 // quotient < divisor bge 3f str x7,[x4,x5,lsl #3] // dividende is prime store in array add x5,x5,#1 // increment counter b 4f // and end loop 3: add x6,x6,#1 // else increment indice cmp x6,x5 // maxi ? blt 2b // no -> loop 4: add x7,x7,#2 // other odd number cmp x7,#MAXI // maxi ? blt 1b // no -> loop mov x0,x5 // return counter 100: ldp x1,lr,[sp],16 // restaur des 2 registres ret /******************************************************************/ /* Display prime table elements */ /******************************************************************/ /* x0 contains the prime */ displayPrime: stp x1,lr,[sp,-16]! // save registres ldr x1,qAdrsZoneConv bl conversion10 // call décimal conversion ldr x0,qAdrszMessResult ldr x1,qAdrsZoneConv // insert conversion in message bl strInsertAtCharInc bl affichageMess // display message 100: ldp x1,lr,[sp],16 // restaur des 2 registres ret   qAdrsZoneConv: .quad sZoneConv   /********************************************************/ /* File Include fonctions */ /********************************************************/ /* for this file see task include a file in language AArch64 assembly */ .include "../includeARM64.inc"    
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.
#Ada
Ada
with Ada.Text_Io;   procedure Additive_Primes is   Last  : constant := 499; Columns : constant := 12;   type Prime_List is array (2 .. Last) of Boolean;   function Get_Primes return Prime_List is Prime : Prime_List := (others => True); begin for P in Prime'Range loop if Prime (P) then for N in 2 .. Positive'Last loop exit when N * P not in Prime'Range; Prime (N * P) := False; end loop; end if; end loop; return Prime; end Get_Primes;   function Sum_Of (N : Natural) return Natural is Image : constant String := Natural'Image (N); Sum  : Natural := 0; begin for Char of Image loop Sum := Sum + (if Char in '0' .. '9' then Natural'Value ("" & Char) else 0); end loop; return Sum; end Sum_Of;   package Natural_Io is new Ada.Text_Io.Integer_Io (Natural); use Ada.Text_Io, Natural_Io;   Prime : constant Prime_List := Get_Primes; Count : Natural := 0; begin Put_Line ("Additive primes <500:"); for N in Prime'Range loop if Prime (N) and then Prime (Sum_Of (N)) then Count := Count + 1; Put (N, Width => 5); if Count mod Columns = 0 then New_Line; end if; end if; end loop; New_Line;   Put ("There are "); Put (Count, Width => 2); Put (" additive primes."); New_Line; end Additive_Primes;