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
#Erlang
Erlang
  -module(rbtree). -export([insert/3, find/2]).   % Node structure: { Key, Value, Color, Smaller, Bigger }   find(_, nil) -> not_found; find(Key, { Key, Value, _, _, _ }) -> { found, { Key, Value } }; find(Key, { Key1, _, _, Left, _ }) when Key < Key1 -> find(Key, Left); find(Key, { Key1, _, _, _, Right }) when Key > Key1 -> find(Key, Right).   insert(Key, Value, Tree) -> make_black(ins(Key, Value, Tree)).   ins(Key, Value, nil) -> { Key, Value, r, nil, nil }; ins(Key, Value, { Key, _, Color, Left, Right }) -> { Key, Value, Color, Left, Right }; ins(Key, Value, { Ky, Vy, Cy, Ly, Ry }) when Key < Ky -> balance({ Ky, Vy, Cy, ins(Key, Value, Ly), Ry }); ins(Key, Value, { Ky, Vy, Cy, Ly, Ry }) when Key > Ky -> balance({ Ky, Vy, Cy, Ly, ins(Key, Value, Ry) }).   make_black({ Key, Value, _, Left, Right }) -> { Key, Value, b, Left, Right }.   balance({ Kx, Vx, b, Lx, { Ky, Vy, r, Ly, { Kz, Vz, r, Lz, Rz } } }) -> { Ky, Vy, r, { Kx, Vx, b, Lx, Ly }, { Kz, Vz, b, Lz, Rz } }; balance({ Kx, Vx, b, Lx, { Ky, Vy, r, { Kz, Vz, r, Lz, Rz }, Ry } }) -> { Kz, Vz, r, { Kx, Vx, b, Lx, Lz }, { Ky, Vy, b, Rz, Ry } }; balance({ Kx, Vx, b, { Ky, Vy, r, { Kz, Vz, r, Lz, Rz }, Ry }, Rx }) -> { Ky, Vy, r, { Kz, Vz, b, Lz, Rz }, { Kx, Vx, b, Ry, Rx } }; balance({ Kx, Vx, b, { Ky, Vy, r, Ly, { Kz, Vz, r, Lz, Rz } }, Rx }) -> { Kz, Vz, r, { Ky, Vy, b, Ly, Lz }, { Kx, Vx, b, Rz, Rx } }; balance(T) -> T.  
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
#CLU
CLU
kprime = proc (n,k: int) returns (bool) f: int := 0 p: int := 2 while f<k & p*p<=n do while n//p=0 do n := n/p f := f+1 end p := p+1 end if n>1 then f:=f+1 end return(f=k) end kprime   start_up = proc () po: stream := stream$primary_output() for k: int in int$from_to(1,5) do i: int := 2 c: int := 0 stream$puts(po, "k = " || int$unparse(k) || ":") while c<10 do if kprime(i,k) then stream$putright(po, int$unparse(i), 4) c := c+1 end i := i+1 end stream$putl(po, "") end end start_up
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
#COBOL
COBOL
IDENTIFICATION DIVISION. PROGRAM-ID. ALMOST-PRIME.   DATA DIVISION. WORKING-STORAGE SECTION. 01 CONTROL-VARS. 03 K PIC 9. 03 I PIC 999. 03 SEEN PIC 99. 03 N PIC 999. 03 P PIC 99. 03 P-SQUARED PIC 9(4). 03 F PIC 99. 03 N-DIV-P PIC 999V999. 03 FILLER REDEFINES N-DIV-P. 05 NEXT-N PIC 999. 05 FILLER PIC 999. 88 N-DIVS-P VALUE ZERO.   01 OUT-VARS. 03 K-LN PIC X(70). 03 K-LN-PTR PIC 99. 03 LN-HDR. 05 FILLER PIC X(4) VALUE "K = ". 05 K-OUT PIC 9. 05 FILLER PIC X VALUE ":". 03 I-FMT. 05 FILLER PIC X VALUE SPACE. 05 I-OUT PIC ZZ9.   PROCEDURE DIVISION. BEGIN. PERFORM K-ALMOST-PRIMES VARYING K FROM 1 BY 1 UNTIL K IS GREATER THAN 5. STOP RUN.   K-ALMOST-PRIMES. MOVE SPACES TO K-LN. MOVE 1 TO K-LN-PTR. MOVE ZERO TO SEEN. MOVE K TO K-OUT. STRING LN-HDR DELIMITED BY SIZE INTO K-LN WITH POINTER K-LN-PTR. PERFORM I-K-ALMOST-PRIME VARYING I FROM 2 BY 1 UNTIL SEEN IS EQUAL TO 10. DISPLAY K-LN.   I-K-ALMOST-PRIME. MOVE ZERO TO F, P-SQUARED. MOVE I TO N. PERFORM PRIME-FACTOR VARYING P FROM 2 BY 1 UNTIL F IS NOT LESS THAN K OR P-SQUARED IS GREATER THAN N. IF N IS GREATER THAN 1, ADD 1 TO F. IF F IS EQUAL TO K, MOVE I TO I-OUT, ADD 1 TO SEEN, STRING I-FMT DELIMITED BY SIZE INTO K-LN WITH POINTER K-LN-PTR.   PRIME-FACTOR. MULTIPLY P BY P GIVING P-SQUARED. DIVIDE N BY P GIVING N-DIV-P. PERFORM DIVIDE-FACTOR UNTIL NOT N-DIVS-P.   DIVIDE-FACTOR. MOVE NEXT-N TO N. ADD 1 TO F. DIVIDE N BY P GIVING N-DIV-P.
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
#AutoHotkey
AutoHotkey
FileRead, Contents, unixdict.txt Loop, Parse, Contents, % "`n", % "`r" { ; parsing each line of the file we just read Loop, Parse, A_LoopField ; parsing each letter/character of the current word Dummy .= "," A_LoopField Sort, Dummy, % "D," ; sorting those letters before removing the delimiters (comma) StringReplace, Dummy, Dummy, % ",", % "", All List .= "`n" Dummy " " A_LoopField , Dummy := "" } ; at this point, we have a list where each line looks like <LETTERS><SPACE><WORD> Count := 0, Contents := "", List := SubStr(List,2) Sort, List Loop, Parse, List, % "`n", % "`r" { ; now the list is sorted, parse it counting the consecutive lines with the same set of <LETTERS> Max := (Count > Max) ? Count : Max StringSplit, LinePart, A_LoopField, % " " ; (LinePart1 are the letters, LinePart2 is the word) If ( PreviousLinePart1 = LinePart1 ) Count++ , WordList .= "," LinePart2 Else var_Result .= ( Count <> Max ) ? "" ; don't append if the number of common words is too low  : "`n" Count "`t" PreviousLinePart1 "`t" SubStr(WordList,2) , WordList := "" , Count := 0 PreviousLinePart1 := LinePart1 } List := "", var_Result := SubStr(var_Result,2) Sort, var_Result, R N ; make the higher scores appear first Loop, Parse, var_Result, % "`n", % "`r" If ( 1 == InStr(A_LoopField,Max) ) var_Output .= "`n" A_LoopField Else ; output only those sets of letters that scored the maximum amount of common words Break MsgBox, % ClipBoard := SubStr(var_Output,2) ; the result is also copied to the clipboard
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
#Klingphix
Klingphix
include ..\Utilitys.tlhy   :bearing sub 360 mod 540 add 360 mod 180 sub ;   20 45 bearing -45 45 bearing -85 90 bearing -95 90 bearing -45 125 bearing -45 145 bearing 29.4803 -88.6381 bearing -78.3251 -159.036 bearing -70099.74233810938 29840.67437876723 bearing -165313.6666297357 33693.9894517456 bearing 1174.8380510598456 -154146.66490124757 bearing 60175.77306795546 42213.07192354373 bearing   pstack   " " input
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
#ooRexx
ooRexx
-- This assumes you've already downloaded the following file and placed it -- in the current directory: http://www.puzzlers.org/pub/wordlists/unixdict.txt   -- There are several different ways of reading the file. I chose the -- supplier method just because I haven't used it yet in any other examples. source = .stream~new('unixdict.txt')~supplier -- this holds our mappings of the anagrams. This is good use for the -- relation class anagrams = .relation~new count = 0 -- this is used to keep track of the maximums   loop while source~available word = source~item -- this produces a string consisting of the characters in sorted order -- Note: the ~~ used to invoke sort makes that message return value be -- the target array. The sort method does not normally have a return value. key = word~makearray('')~~sort~tostring("l", "") -- add this to our mapping. This creates multiple entries for each -- word that uses the same key anagrams[key] = word source~next end   -- now get the set of unique keys keys = .set~new~~putall(anagrams~allIndexes) -- the longest count tracker longest = 0 -- our list of the longest pairs pairs = .array~new   loop key over keys -- don't even bother doing the deranged checks for any key -- shorter than our current longest if key~length < longest then iterate   words = anagrams~allAt(key) -- singletons aren't anagrams at all newCount = words~items loop i = 1 to newCount - 1 word1 = words[i] loop j = 1 to newCount word2 = words[j] -- bitxor will have '00'x in every position where these -- strings match. If found, go around and check the -- next one if word1~bitxor(word2)~pos('00'x) > 0 then iterate -- we have a match else do if word1~length > longest then do -- throw away anything we've gathered so far pairs~empty longest = word1~length end pairs~append(.array~of(word1, word2)) end end end end   say "The longest deranged anagrams we found are:" loop pair over pairs say pair[1] pair[2] 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.
#Klingphix
Klingphix
include ..\Utilitys.tlhy     :fib %f !f  %fr [ %n !n $n 2 < ( [$n] [$n 1 - $fr eval $n 2 - $fr eval +] ) if ] !fr   $f 0 < ( ["Error: number is negative"] [$f true $fr if] ) if ;     25 fib ? msec ? "End " input
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.
#GFA_Basic
GFA Basic
  OPENW 1 CLEARW 1 ' DIM f%(20001) ! sum of proper factors for each n FOR i%=1 TO 20000 f%(i%)=@sum_proper_divisors(i%) NEXT i% ' look for pairs FOR i%=1 TO 20000 FOR j%=i%+1 TO 20000 IF f%(i%)=j% AND i%=f%(j%) PRINT "Amicable pair ";i%;" ";j% ENDIF NEXT j% NEXT i% ' PRINT PRINT "-- found all amicable pairs" ~INP(2) CLOSEW 1 ' ' Compute the sum of proper divisors of given number ' FUNCTION sum_proper_divisors(n%) LOCAL i%,sum%,root% ' IF n%>1 ! n% must be 2 or larger sum%=1 ! start with 1 root%=SQR(n%) ! note that root% is an integer ' check possible factors, up to sqrt FOR i%=2 TO root% IF n% MOD i%=0 sum%=sum%+i% ! i% is a factor IF i%*i%<>n% ! check i% is not actual square root of n% sum%=sum%+n%/i% ! so n%/i% will also be a factor ENDIF ENDIF NEXT i% ENDIF RETURN sum% ENDFUNC  
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.
#Python
Python
#!/usr/bin/env python3 import sys   from PyQt5.QtCore import QBasicTimer, Qt from PyQt5.QtGui import QFont from PyQt5.QtWidgets import QApplication, QLabel     class Marquee(QLabel): def __init__(self, **kwargs): super().__init__(**kwargs) self.right_to_left_direction = True self.initUI() self.timer = QBasicTimer() self.timer.start(80, self)   def initUI(self): self.setWindowFlags(Qt.FramelessWindowHint) self.setAttribute(Qt.WA_TranslucentBackground) self.setText("Hello World! ") self.setFont(QFont(None, 50, QFont.Bold)) # make more irritating for the authenticity with <marquee> element self.setStyleSheet("QLabel {color: cyan; }")   def timerEvent(self, event): i = 1 if self.right_to_left_direction else -1 self.setText(self.text()[i:] + self.text()[:i]) # rotate   def mouseReleaseEvent(self, event): # change direction on mouse release self.right_to_left_direction = not self.right_to_left_direction   def keyPressEvent(self, event): # exit on Esc if event.key() == Qt.Key_Escape: self.close()     app = QApplication(sys.argv) w = Marquee() # center widget on the screen w.adjustSize() # update w.rect() now w.move(QApplication.instance().desktop().screen().rect().center() - w.rect().center()) w.show() sys.exit(app.exec())
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.
#Liberty_BASIC
Liberty BASIC
nomainwin WindowWidth = 400 WindowHeight = 300   open "Pendulum" for graphics_nsb_nf as #main #main "down;fill white; flush" #main "color black" #main "trapclose [quit.main]"   Angle = asn(1) DeltaT = 0.1 PendLength = 150 FixX = int(WindowWidth / 2) FixY = 40   timer 30, [swing]   wait   [swing]   #main "cls" #main "discard"   PlumbobX = FixX + int(sin(Angle) * PendLength) PlumbobY = FixY + int(cos(Angle) * PendLength) AngAccel = -9.81 / PendLength * sin(Angle) AngVelocity = AngVelocity + AngAccel * DeltaT Angle = Angle + AngVelocity * DeltaT   #main "backcolor black" #main "place ";FixX;" ";FixY #main "circlefilled 3" #main "line ";FixX;" ";FixY;" ";PlumbobX;" ";PlumbobY #main "backcolor red" #main "circlefilled 10"   wait   [quit.main] close #main end
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.23
C#
using System; using System.Collections.Generic;   public class Amb : IDisposable { List<IValueSet> streams = new List<IValueSet>(); List<IAssertOrAction> assertsOrActions = new List<IAssertOrAction>(); volatile bool stopped = false;   public IAmbValue<T> DefineValues<T>(params T[] values) { return DefineValueSet(values); }   public IAmbValue<T> DefineValueSet<T>(IEnumerable<T> values) { ValueSet<T> stream = new ValueSet<T>(); stream.Enumerable = values; streams.Add(stream); return stream; }   public Amb Assert(Func<bool> function) { assertsOrActions.Add(new AmbAssert() { Level = streams.Count, IsValidFunction = function }); return this; }   public Amb Perform(Action action) { assertsOrActions.Add(new AmbAction() { Level = streams.Count, Action = action }); return this; }   public void Stop() { stopped = true; }   public void Dispose() { RunLevel(0, 0); if (!stopped) { throw new AmbException(); } }   void RunLevel(int level, int actionIndex) { while (actionIndex < assertsOrActions.Count && assertsOrActions[actionIndex].Level <= level) { if (!assertsOrActions[actionIndex].Invoke() || stopped) return; actionIndex++; } if (level < streams.Count) { using (IValueSetIterator iterator = streams[level].CreateIterator()) { while (iterator.MoveNext()) { RunLevel(level + 1, actionIndex); } } } }   interface IValueSet { IValueSetIterator CreateIterator(); }   interface IValueSetIterator : IDisposable { bool MoveNext(); }   interface IAssertOrAction { int Level { get; } bool Invoke(); }   class AmbAssert : IAssertOrAction { internal int Level; internal Func<bool> IsValidFunction;   int IAssertOrAction.Level { get { return Level; } }   bool IAssertOrAction.Invoke() { return IsValidFunction(); } }   class AmbAction : IAssertOrAction { internal int Level; internal Action Action;   int IAssertOrAction.Level { get { return Level; } }   bool IAssertOrAction.Invoke() { Action(); return true; } }   class ValueSet<T> : IValueSet, IAmbValue<T>, IValueSetIterator { internal IEnumerable<T> Enumerable; private IEnumerator<T> enumerator;   public T Value { get { return enumerator.Current; } }   public IValueSetIterator CreateIterator() { enumerator = Enumerable.GetEnumerator(); return this; }   public bool MoveNext() { return enumerator.MoveNext(); }   public void Dispose() { enumerator.Dispose(); } } }   public interface IAmbValue<T> { T Value { get; } }   public class AmbException : Exception { public AmbException() : base("AMB is angry") { } }
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
#AppleScript
AppleScript
on aliquotSum(n) if (n < 2) then return 0 set sum to 1 set sqrt to n ^ 0.5 set limit to sqrt div 1 if (limit = sqrt) then set sum to sum + limit set limit to limit - 1 end if repeat with i from 2 to limit if (n mod i is 0) then set sum to sum + i + n div i end repeat   return sum end aliquotSum   on aliquotSequence(k, maxLength, maxN) -- Generate the sequence within the specified limitations. set sequence to {k} set n to k repeat (maxLength - 1) times set n to aliquotSum(n) set repetition to (sequence contains n) if (repetition) then exit repeat set end of sequence to n if ((n = 0) or (n > maxN)) then exit repeat end repeat -- Analyse it. set sequenceLength to (count sequence) if (sequenceLength is 1) then set classification to "perfect" else if (n is 0) then set classification to "terminating" else if (n = k) then if (sequenceLength is 2) then set classification to "amicable" else set classification to "sociable" end if else if (repetition) then if (sequence ends with n) then set classification to "aspiring" else set classification to "cyclic" end if else set classification to "non-terminating" end if   return {sequence:sequence, classification:classification} end aliquotSequence   -- Task code: local output, maxLength, maxN, spacing, astid, k set output to {""} set {maxLength, maxN} to {16, 2 ^ 47} set spacing to " " set astid to AppleScript's text item delimiters set AppleScript's text item delimiters to ", " repeat with k in {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, ¬ 11, 12, 28, 496, 220, 1184, 12496, 1264460, 790, 909, 562, 1064, 1488, 1.535571778608E+13} set thisResult to aliquotSequence(k's contents, maxLength, maxN) set end of output to text -18 thru -1 of (spacing & k) & ": " & ¬ text 1 thru 17 of (thisResult's classification & spacing) & thisResult's sequence end repeat set AppleScript's text item delimiters to linefeed set output to output as text set AppleScript's text item delimiters to astid return output
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.
#Arturo
Arturo
x: 2 xInfo: info.get 'x   print [ "address of x:" xInfo\address "->" from.hex xInfo\address ]
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.
#Astro
Astro
var num = 12 var pointer = ptr(num) # get pointer   print pointer # print address   @unsafe # bad idea! pointer.addr = 0xFFFE # set the address  
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.
#AutoHotkey
AutoHotkey
msgbox % &var
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.
#AArch64_Assembly
AArch64 Assembly
  /* ARM assembly AARCH64 Raspberry PI 3B or android 64 bits */ /* program AKS64.s */   /*******************************************/ /* Constantes file */ /*******************************************/ /* for this file see task include a file in language AArch64 assembly*/ .include "../includeConstantesARM64.inc" .equ MAXI, 64 .equ NUMBERLOOP, 10   /*********************************/ /* Initialized data */ /*********************************/ .data szMessResult: .asciz " (x-1)^@ = " szMessResult1: .asciz " @ x^@ " szMessResPrime: .asciz "Number @ is prime. \n" szCarriageReturn: .asciz "\n"   /*********************************/ /* UnInitialized data */ /*********************************/ .bss sZoneConv: .skip 24 qTabCoef: .skip 8 * MAXI /*********************************/ /* code section */ /*********************************/ .text .global main main: // entry of program   mov x4,#1 1: // loop mov x0,x4 bl computeCoef // compute coefficient ldr x0,qAdrqTabCoef mov x0,x4 bl displayCoef // display coefficient add x4,x4,1 cmp x4,NUMBERLOOP blt 1b   mov x4,1 2: mov x0,x4 bl isPrime // is prime ? cmp x0,1 bne 3f mov x0,x4 ldr x1,qAdrsZoneConv bl conversion10 // call decimal conversion add x1,x1,x0 strb wzr,[x1] ldr x0,qAdrszMessResPrime ldr x1,qAdrsZoneConv // insert value conversion in message bl strInsertAtCharInc bl affichageMess   3: add x4,x4,1 cmp x4,MAXI blt 2b   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 qAdrsZoneConv: .quad sZoneConv qAdrqTabCoef: .quad qTabCoef qAdrszMessResPrime: .quad szMessResPrime /***************************************************/ /* display coefficients */ /***************************************************/ // x0 contains a number displayCoef: stp x1,lr,[sp,-16]! // save registres stp x2,x3,[sp,-16]! // save registres stp x4,x5,[sp,-16]! // save registres stp x6,x7,[sp,-16]! // save registres mov x2,x0 ldr x1,qAdrsZoneConv // bl conversion10 // call decimal conversion add x1,x1,x0 strb wzr,[x1] ldr x0,qAdrszMessResult ldr x1,qAdrsZoneConv // insert value conversion in message bl strInsertAtCharInc bl affichageMess ldr x3,qAdrqTabCoef 1: ldr x0,[x3,x2,lsl #3] ldr x1,qAdrsZoneConv // bl conversion10S // call decimal conversion 2: // removing spaces ldrb w6,[x1] cmp x6,' ' cinc x1,x1,eq beq 2b   ldr x0,qAdrszMessResult1 bl strInsertAtCharInc mov x4,x0 mov x0,x2 ldr x1,qAdrsZoneConv // else display odd message bl conversion10 // call decimal conversion add x1,x1,x0 strb wzr,[x1] mov x0,x4 ldr x1,qAdrsZoneConv // insert value conversion in message bl strInsertAtCharInc bl affichageMess subs x2,x2,#1 bge 1b   ldr x0,qAdrszCarriageReturn bl affichageMess 100: ldp x6,x7,[sp],16 // restaur des 2 registres ldp x4,x5,[sp],16 // restaur des 2 registres ldp x2,x3,[sp],16 // restaur des 2 registres ldp x1,lr,[sp],16 // restaur des 2 registres ret qAdrszMessResult: .quad szMessResult qAdrszMessResult1: .quad szMessResult1 /***************************************************/ /* compute coefficient */ /***************************************************/ // x0 contains a number computeCoef: stp x1,lr,[sp,-16]! // save registres stp x2,x3,[sp,-16]! // save registres stp x4,x5,[sp,-16]! // save registres stp x6,x7,[sp,-16]! // save registres ldr x1,qAdrqTabCoef // address coefficient array mov x2,1 str x2,[x1] // store 1 to coeff [0] mov x3,0 // indice 1 1: add x4,x3,1 mov x5,1 str x5,[x1,x4,lsl #3] mov x6,x3 // indice 2 = indice 1 2: cmp x6,0 // zero ? -> end loop ble 3f sub x4,x6,1 ldr x5,[x1,x4,lsl 3] ldr x4,[x1,x6,lsl 3] sub x5,x5,x4 str x5,[x1,x6,lsl 3] sub x6,x6,1 b 2b 3: ldr x2,[x1] // inversion coeff [0] neg x2,x2 str x2,[x1] add x3,x3,1 cmp x3,x0 blt 1b   100: ldp x6,x7,[sp],16 // restaur des 2 registres ldp x4,x5,[sp],16 // restaur des 2 registres ldp x2,x3,[sp],16 // restaur des 2 registres ldp x1,lr,[sp],16 // restaur des 2 registres ret /***************************************************/ /* verify number is prime */ /***************************************************/ // x0 contains a number isPrime: stp x1,lr,[sp,-16]! // save registres stp x2,x3,[sp,-16]! // save registres stp x4,x5,[sp,-16]! // save registres bl computeCoef ldr x4,qAdrqTabCoef // address coefficient array ldr x2,[x4] add x2,x2,1 str x2,[x4] ldr x2,[x4,x0,lsl 3] sub x2,x2,#1 str x2,[x4,x0,lsl 3] mov x5,x0 // number start 1: ldr x1,[x4,x5,lsl 3] // load one coeff sdiv x2,x1,x0 msub x3,x2,x0,x1 // compute remainder cmp x3,#0 // remainder = zéro ? bne 99f // if <> no prime subs x5,x5,#1 // next coef bgt 1b // and loop mov x0,#1 // prime b 100f 99: mov x0,0 // no prime 100: ldp x4,x5,[sp],16 // restaur des 2 registres ldp x2,x3,[sp],16 // restaur des 2 registres ldp x1,lr,[sp],16 // restaur des 2 registres ret /********************************************************/ /* 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.
#ALGOL_68
ALGOL 68
BEGIN # find additive primes - primes whose digit sum is also prime # # sieve the primes to max prime # PR read "primes.incl.a68" PR []BOOL prime = PRIMESIEVE 499; # find the additive primes # INT additive count := 0; FOR n TO UPB prime DO IF prime[ n ] THEN # have a prime # INT digit sum := 0; INT v := n; WHILE v > 0 DO digit sum +:= v MOD 10; v OVERAB 10 OD; IF prime( digit sum ) THEN # the digit sum is prime # print( ( " ", whole( n, -3 ) ) ); IF ( additive count +:= 1 ) MOD 20 = 0 THEN print( ( newline ) ) FI FI FI OD; print( ( newline, "Found ", whole( additive count, 0 ), " additive primes below ", whole( UPB prime + 1, 0 ), newline ) ) END
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
#F.23
F#
  // Pattern Matching. Nigel Galloway: January 15th., 2021 type colour= |Red |Black type rbT<'N>= |Empty |N of colour * rbT<'N> * rbT<'N> * 'N let repair=function |Black,N(Red,N(Red,ll,lr,lv),rl,v),rr,rv |Black,N(Red,ll,N(Red,lr,rl,v),lv),rr,rv |Black,ll,N(Red,N(Red,lr,rl,v),rr,rv),lv |Black,ll,N(Red,lr,N(Red,rl,rr,rv),v),lv->N(Red,N(Black,ll,lr,lv),N(Black,rl,rr,rv),v) |i,g,e,l->N(i,g,e,l) let insert item rbt = let rec insert=function |Empty->N(Red,Empty,Empty,item) |N(i,g,e,l) as node->if item>l then repair(i,g,insert e,l) elif item<l then repair(i,insert g,e,l) else node match insert rbt with N(_,g,e,l)->N(Black,g,e,l) |_->Empty  
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
#Go
Go
package main   import "fmt"   type Color string   const ( R Color = "R" B = "B" )   type Tree interface { ins(x int) Tree }   type E struct{}   func (_ E) ins(x int) Tree { return T{R, E{}, x, E{}} }   func (_ E) String() string { return "E" }   type T struct { cl Color le Tree aa int ri Tree }   func (t T) balance() Tree { if t.cl != B { return t } le, leIsT := t.le.(T) ri, riIsT := t.ri.(T) var lele, leri, rile, riri T var leleIsT, leriIsT, rileIsT, ririIsT bool if leIsT { lele, leleIsT = le.le.(T) } if leIsT { leri, leriIsT = le.ri.(T) } if riIsT { rile, rileIsT = ri.le.(T) } if riIsT { riri, ririIsT = ri.ri.(T) } switch { case leIsT && leleIsT && le.cl == R && lele.cl == R: _, t2, z, d := t.destruct() _, t3, y, c := t2.(T).destruct() _, a, x, b := t3.(T).destruct() return T{R, T{B, a, x, b}, y, T{B, c, z, d}} case leIsT && leriIsT && le.cl == R && leri.cl == R: _, t2, z, d := t.destruct() _, a, x, t3 := t2.(T).destruct() _, b, y, c := t3.(T).destruct() return T{R, T{B, a, x, b}, y, T{B, c, z, d}} case riIsT && rileIsT && ri.cl == R && rile.cl == R: _, a, x, t2 := t.destruct() _, t3, z, d := t2.(T).destruct() _, b, y, c := t3.(T).destruct() return T{R, T{B, a, x, b}, y, T{B, c, z, d}} case riIsT && ririIsT && ri.cl == R && riri.cl == R: _, a, x, t2 := t.destruct() _, b, y, t3 := t2.(T).destruct() _, c, z, d := t3.(T).destruct() return T{R, T{B, a, x, b}, y, T{B, c, z, d}} default: return t } }   func (t T) ins(x int) Tree { switch { case x < t.aa: return T{t.cl, t.le.ins(x), t.aa, t.ri}.balance() case x > t.aa: return T{t.cl, t.le, t.aa, t.ri.ins(x)}.balance() default: return t } }   func (t T) destruct() (Color, Tree, int, Tree) { return t.cl, t.le, t.aa, t.ri }   func (t T) String() string { return fmt.Sprintf("T(%s, %v, %d, %v)", t.cl, t.le, t.aa, t.ri) }   func insert(tr Tree, x int) Tree { t := tr.ins(x) switch t.(type) { case T: tt := t.(T) _, a, y, b := tt.destruct() return T{B, a, y, b} case E: return E{} default: return nil } }   func main() { var tr Tree = E{} for i := 1; i <= 16; i++ { tr = insert(tr, i) } fmt.Println(tr) }
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
#Common_Lisp
Common Lisp
(defun start () (loop for k from 1 to 5 do (format t "k = ~a: ~a~%" k (collect-k-almost-prime k))))   (defun collect-k-almost-prime (k &optional (d 2) (lst nil)) (cond ((= (length lst) 10) (reverse lst)) ((= (?-primality d) k) (collect-k-almost-prime k (+ d 1) (cons d lst))) (t (collect-k-almost-prime k (+ d 1) lst))))   (defun ?-primality (n &optional (d 2) (c 0)) (cond ((> d (isqrt n)) (+ c 1)) ((zerop (rem n d)) (?-primality (/ n d) d (+ c 1))) (t (?-primality n (+ d 1) c))))
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
#AWK
AWK
# JUMBLEA.AWK - words with the most duplicate spellings # syntax: GAWK -f JUMBLEA.AWK UNIXDICT.TXT { for (i=1; i<=NF; i++) { w = sortstr(toupper($i)) arr[w] = arr[w] $i " " n = gsub(/ /,"&",arr[w]) if (max_n < n) { max_n = n } } } END { for (w in arr) { if (gsub(/ /,"&",arr[w]) == max_n) { printf("%s\t%s\n",w,arr[w]) } } exit(0) } function sortstr(str, i,j,leng) { leng = length(str) for (i=2; i<=leng; i++) { for (j=i; j>1 && substr(str,j-1,1) > substr(str,j,1); j--) { str = substr(str,1,j-2) substr(str,j,1) substr(str,j-1,1) substr(str,j+1) } } return(str) }
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
#Kotlin
Kotlin
// version 1.1.2   class Angle(d: Double) { val value = when { d in -180.0 .. 180.0 -> d d > 180.0 -> (d - 180.0) % 360.0 - 180.0 else -> (d + 180.0) % 360.0 + 180.0 }   operator fun minus(other: Angle) = Angle(this.value - other.value) }   fun main(args: Array<String>) { val anglePairs = arrayOf( 20.0 to 45.0, -45.0 to 45.0, -85.0 to 90.0, -95.0 to 90.0, -45.0 to 125.0, -45.0 to 145.0, 29.4803 to -88.6381, -78.3251 to -159.036, -70099.74233810938 to 29840.67437876723, -165313.6666297357 to 33693.9894517456, 1174.8380510598456 to -154146.66490124757, 60175.77306795546 to 42213.07192354373 ) println(" b1 b2 diff") val f = "% 12.4f  % 12.4f  % 12.4f" for (ap in anglePairs) { val diff = Angle(ap.second) - Angle(ap.first) println(f.format(ap.first, ap.second, diff.value)) } }
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
#PARI.2FGP
PARI/GP
dict=readstr("unixdict.txt"); len=apply(s->#s, dict); getLen(L)=my(v=List()); for(i=1,#dict, if(len[i]==L, listput(v, dict[i]))); Vec(v); letters(s)=vecsort(Vec(s)); getAnagrams(v)=my(u=List(),L=apply(letters,v),t,w); for(i=1,#v-1, w=List(); t=L[i]; for(j=i+1,#v, if(L[j]==t, listput(w, v[j]))); if(#w, listput(u, concat([v[i]], Vec(w))))); Vec(u); deranged(s1,s2)=s1=Vec(s1);s2=Vec(s2); for(i=1,#s1, if(s1[i]==s2[i], return(0))); 1 getDeranged(v)=my(u=List(),w); for(i=1,#v-1, for(j=i+1,#v, if(deranged(v[i], v[j]), listput(u, [v[i], v[j]])))); Vec(u); f(n)=my(t=getAnagrams(getLen(n))); if(#t, concat(apply(getDeranged, t)), []); forstep(n=vecmax(len),1,-1, t=f(n); if(#t, return(t)))
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.
#Klong
Klong
  fib::{:[x<0;"error: negative":|x<2;x;.f(x-1)+.f(x-2)]}  
http://rosettacode.org/wiki/Amicable_pairs
Amicable pairs
Two integers N {\displaystyle N} and M {\displaystyle M} are said to be amicable pairs if N ≠ M {\displaystyle N\neq M} and the sum of the proper divisors of N {\displaystyle N} ( s u m ( p r o p D i v s ( N ) ) {\displaystyle \mathrm {sum} (\mathrm {propDivs} (N))} ) = M {\displaystyle =M} as well as s u m ( p r o p D i v s ( M ) ) = N {\displaystyle \mathrm {sum} (\mathrm {propDivs} (M))=N} . Example 1184 and 1210 are an amicable pair, with proper divisors:   1, 2, 4, 8, 16, 32, 37, 74, 148, 296, 592   and   1, 2, 5, 10, 11, 22, 55, 110, 121, 242, 605   respectively. Task Calculate and show here the Amicable pairs below 20,000; (there are eight). Related tasks Proper divisors Abundant, deficient and perfect number classifications Aliquot sequence classifications and its amicable classification.
#Go
Go
package main   import "fmt"   func pfacSum(i int) int { sum := 0 for p := 1; p <= i/2; p++ { if i%p == 0 { sum += p } } return sum }   func main() { var a[20000]int for i := 1; i < 20000; i++ { a[i] = pfacSum(i) } fmt.Println("The amicable pairs below 20,000 are:") for n := 2; n < 19999; n++ { m := a[n] if m > n && m < 20000 && n == a[m] { fmt.Printf("  %5d and %5d\n", n, m) } } }
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.
#Quick_BASIC
Quick BASIC
  'here accordingly to the version, QB or QBX REM $INCLUDE: 'QBX.BI'   DIM REGS AS REGTYPE DIM C AS STRING, SIZ AS INTEGER DIM I AS DOUBLE, DIRE AS INTEGER C = "Hello World! " SIZ = LEN(C)   SCREEN 12 'turn the cursor visible REGS.AX = 1 INTERRUPT 51, REGS, REGS   DO I = TIMER LOCATE 1, 1 PRINT C   REGS.AX = 5 'read mouse's queue of occurred pressings REGS.BX = 0 'the left button INTERRUPT 51, REGS, REGS   'BX is the selected button's quantity of occurred pressings IF REGS.BX <> 0 THEN IF REGS.CX >= 0 AND REGS.CX < SIZ * 8 AND REGS.DX >= 0 AND REGS.DX < 16 THEN DIRE = 1 - DIRE END IF END IF   'AX is all buttons' status IF (REGS.AX AND 2) <> 0 THEN EXIT DO   IF DIRE = 0 THEN C = RIGHT$(C, 1) + LEFT$(C, SIZ - 1) ELSE C = RIGHT$(C, SIZ - 1) + LEFT$(C, 1) END IF   DO WHILE TIMER < I + .08 IF TIMER < I THEN I = I - 86400 'midnight checking LOOP LOOP
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.
#Lingo
Lingo
global RODLEN, GRAVITY, DT global velocity, acceleration, angle, posX, posY   on startMovie   -- window properties _movie.stage.title = "Pendulum" _movie.stage.titlebarOptions.visible = TRUE _movie.stage.rect = rect(0, 0, 400, 400) _movie.centerStage = TRUE _movie.puppetTempo(30)   RODLEN = 180 GRAVITY = -9.8 DT = 0.03   velocity = 0.0 acceleration = 0.0 angle = PI/3 posX = 200 - sin(angle) * RODLEN posY = 100 + cos(angle) * RODLEN paint()   -- show the window _movie.stage.visible = TRUE end   on enterFrame acceleration = GRAVITY * sin(angle) velocity = velocity + acceleration * DT angle = angle + velocity * DT posX = 200 - sin(angle) * rodLen posY = 100 + cos(angle) * rodLen paint() end   on paint img = _movie.stage.image img.fill(img.rect, rgb(255,255,255)) img.fill(point(200-5, 100-5), point(200+5, 100+5), [#shapeType:#oval,#color:rgb(0,0,0)]) img.draw(point(200, 100), point(posX, posY), [#color:rgb(0,0,0)]) img.fill(point(posX-20, posY-20), point(posX+20, posY+20), [#shapeType:#oval,#lineSize:1,#bgColor:rgb(0,0,0),#color:rgb(255,255,0)]) end
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.2B.2B
C++
#include <iostream> #include <string_view> #include <boost/hana.hpp> #include <boost/hana/experimental/printable.hpp>   using namespace std; namespace hana = boost::hana;   // Define the Amb function. The first parameter is the constraint to be // enforced followed by the potential values. constexpr auto Amb(auto constraint, auto&& ...params) { // create the set of all possible solutions auto possibleSolutions = hana::cartesian_product(hana::tuple(params...));   // find one that matches the constraint auto foldOperation = [constraint](auto a, auto b) { bool meetsConstraint = constraint(a); return meetsConstraint ? a : b; };   return hana::fold_right(possibleSolutions, foldOperation); }   void AlgebraExample() { // use a tuple to hold the possible values of each variable constexpr hana::tuple x{1, 2, 3}; constexpr hana::tuple y{7, 6, 4, 5};   // the constraint enforcing x * y == 8 constexpr auto constraint = [](auto t) { return t[hana::size_c<0>] * t[hana::size_c<1>] == 8; };   // find the solution using the Amb function auto result = Amb(constraint, x, y);   cout << "\nx = " << hana::experimental::print(x); cout << "\ny = " << hana::experimental::print(y); cout << "\nx * y == 8: " << hana::experimental::print(result); }   void StringExample() { // the word lists to choose from constexpr hana::tuple words1 {"the"sv, "that"sv, "a"sv}; constexpr hana::tuple words2 {"frog"sv, "elephant"sv, "thing"sv}; constexpr hana::tuple words3 {"walked"sv, "treaded"sv, "grows"sv}; constexpr hana::tuple words4 {"slowly"sv, "quickly"sv};   // the constraint that the first letter of a word is the same as the last // letter of the previous word constexpr auto constraint = [](const auto t) { auto adjacent = hana::zip(hana::drop_back(t), hana::drop_front(t)); return hana::all_of(adjacent, [](auto t) { return t[hana::size_c<0>].back() == t[hana::size_c<1>].front(); }); };     // find the solution using the Amb function auto wordResult = Amb(constraint, words1, words2, words3, words4);   cout << "\n\nWords 1: " << hana::experimental::print(words1); cout << "\nWords 2: " << hana::experimental::print(words2); cout << "\nWords 3: " << hana::experimental::print(words3); cout << "\nWords 4: " << hana::experimental::print(words4); cout << "\nSolution: " << hana::experimental::print(wordResult) << "\n"; }   int main() { AlgebraExample(); StringExample(); }  
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
#ARM_Assembly
ARM Assembly
  /* ARM assembly Raspberry PI */ /* program aliquotSeq.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 MAXINUM, 10 .equ MAXI, 16 .equ NBDIVISORS, 1000   /*******************************************/ /* Initialized data */ /*******************************************/ .data szMessStartPgm: .asciz "Program start \n" szMessEndPgm: .asciz "Program normal end.\n" szMessErrorArea: .asciz "\033[31mError : area divisors too small.\033[0m \n" szMessError: .asciz "\033[31mError  !!!\033[0m \n" szMessErrGen: .asciz "Error end program.\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: .int 11,12,28,496,220,1184,12496,1264460,790,909,562,1064,1488 .equ NBNUMBER, (. - tbNumber ) / 4   /*******************************************/ /* UnInitialized data */ /*******************************************/ .bss .align 4 sZoneConv: .skip 24 tbZoneDecom: .skip 4 * NBDIVISORS // facteur 4 octets tbNumberSucc: .skip 4 * MAXI /*******************************************/ /* code section */ /*******************************************/ .text .global main main: @ program start ldr r0,iAdrszMessStartPgm @ display start message bl affichageMess   mov r4,#1 1: mov r0,r4 @ number bl aliquotClassif @ aliquot classification cmp r0,#-1 @ error ? beq 99f add r4,r4,#1 cmp r4,#MAXINUM ble 1b   ldr r5,iAdrtbNumber @ number array mov r4,#0 2: ldr r0,[r5,r4,lsl #2] @ load a number bl aliquotClassif @ aliquot classification cmp r0,#-1 @ error ? beq 99f add r4,r4,#1 @ next number cmp r4,#NBNUMBER @ maxi ? blt 2b @ no -> loop   ldr r0,iAdrszMessEndPgm @ display end message bl affichageMess b 100f 99: @ display error message ldr r0,iAdrszMessError bl affichageMess 100: @ standard end of the program mov r0, #0 @ return code mov r7, #EXIT @ request to exit program svc 0 @ perform system call iAdrszMessStartPgm: .int szMessStartPgm iAdrszMessEndPgm: .int szMessEndPgm iAdrszMessError: .int szMessError iAdrszCarriageReturn: .int szCarriageReturn iAdrtbZoneDecom: .int tbZoneDecom iAdrszMessResult: .int szMessResult iAdrsZoneConv: .int sZoneConv iAdrtbNumber: .int tbNumber /******************************************************************/ /* function aliquot classification */ /******************************************************************/ /* r0 contains number */ aliquotClassif: push {r3-r8,lr} @ save registers mov r5,r0 @ save number ldr r1,iAdrsZoneConv bl conversion10 @ convert ascii string mov r2,#0 strb r2,[r1,r0] ldr r0,iAdrszMessResHead ldr r1,iAdrsZoneConv bl strInsertAtCharInc @ put in head message bl affichageMess @ and display mov r0,r5 @ restaur number ldr r7,iAdrtbNumberSucc @ number successif array mov r4,#0 @ counter number successif 1: mov r6,r0 @ previous number ldr r1,iAdrtbZoneDecom bl decompFact @ create area of divisors cmp r0,#0 @ error ? blt 99f sub r3,r1,r6 @ sum mov r0,r3 ldr r1,iAdrsZoneConv bl conversion10 @ convert ascii string mov r2,#0 strb r2,[r1,r0] ldr r0,iAdrszMessResult ldr r1,iAdrsZoneConv bl strInsertAtCharInc @ and put in message bl affichageMess cmp r3,#0 @ sum = zero bne 11f ldr r0,iAdrszLibTerm @ terminating bl affichageMess b 100f 11: cmp r5,r3 @ compare number and sum bne 4f cmp r4,#0 @ first loop ? bne 2f ldr r0,iAdrszLibPerf @ perfect bl affichageMess b 100f 2: cmp r4,#1 @ second loop ? bne 3f ldr r0,iAdrszLibAmic @ amicable bl affichageMess b 100f 3: @ other loop ldr r0,iAdrszLibSoc @ sociable bl affichageMess b 100f   4: cmp r6,r3 @ compare sum and (sum - 1) bne 5f ldr r0,iAdrszLibAspi @ aspirant bl affichageMess b 100f 5: cmp r3,#1 @ if one ,no search in array beq 7f mov r2,#0 @ search indice 6: @ search number in array ldr r8,[r7,r2,lsl #2] cmp r8,r3 @ equal ? beq 8f @ yes -> cycling add r2,r2,#1 @ increment indice cmp r2,r4 @ end ? blt 6b @ no -> loop 7: cmp r4,#MAXI blt 10f ldr r0,iAdrszLibNoTerm @ no terminating bl affichageMess b 100f 8: @ cycling ldr r0,iAdrszLibCycl bl affichageMess b 100f   10: str r3,[r7,r4,lsl #2] @ store new sum in array add r4,r4,#1 @ increment counter mov r0,r3 @ new number = new sum b 1b @ and loop   99: @ display error ldr r0,iAdrszMessError bl affichageMess 100: pop {r3-r8,lr} @ restaur registers bx lr iAdrszMessResHead: .int szMessResHead iAdrszLibPerf: .int szLibPerf iAdrszLibAmic: .int szLibAmic iAdrszLibSoc: .int szLibSoc iAdrszLibCycl: .int szLibCycl iAdrszLibAspi: .int szLibAspi iAdrszLibNoTerm: .int szLibNoTerm iAdrszLibTerm: .int szLibTerm iAdrtbNumberSucc: .int tbNumberSucc /******************************************************************/ /* factor decomposition */ /******************************************************************/ /* r0 contains number */ /* r1 contains address of divisors area */ /* r0 return divisors items in array */ /* r1 return the sum of divisors */ decompFact: push {r3-r12,lr} @ save registers cmp r0,#1 moveq r1,#1 beq 100f mov r5,r1 mov r8,r0 @ save number bl isPrime @ prime ? cmp r0,#1 beq 98f @ yes is prime mov r1,#1 str r1,[r5] @ first factor mov r12,#1 @ divisors sum mov r10,#1 @ indice divisors table mov r9,#2 @ first divisor mov r6,#0 @ previous divisor mov r7,#0 @ number of same divisors   /* division loop */ 2: mov r0,r8 @ dividende mov r1,r9 @ divisor bl division @ r2 quotient r3 remainder cmp r3,#0 beq 3f @ if remainder zero -> divisor   /* not divisor -> increment next divisor */ cmp r9,#2 @ if divisor = 2 -> add 1 addeq r9,#1 addne r9,#2 @ else add 2 b 2b   /* divisor compute the new factors of number */ 3: mov r8,r2 @ else quotient -> new dividende cmp r9,r6 @ same divisor ? beq 4f @ yes   mov r0,r5 @ table address mov r1,r10 @ number factors in table mov r2,r9 @ divisor mov r3,r12 @ somme mov r4,#0 bl computeFactors cmp r0,#-1 beq 100f mov r10,r1 mov r12,r0 mov r6,r9 @ new divisor b 7f   4: @ same divisor sub r7,r10,#1 5: @ search in table the first use of divisor ldr r3,[r5,r7,lsl #2 ] cmp r3,r9 subne r7,#1 bne 5b @ and compute new factors after factors sub r4,r10,r7 @ start indice mov r0,r5 mov r1,r10 mov r2,r9 @ divisor mov r3,r12 bl computeFactors cmp r0,#-1 beq 100f mov r12,r0 mov r10,r1     /* divisor -> test if new dividende is prime */ 7: cmp r8,#1 @ dividende = 1 ? -> end beq 10f mov r0,r8 @ new dividende is prime ? mov r1,#0 bl isPrime @ the new dividende is prime ? cmp r0,#1 bne 10f @ the new dividende is not prime   cmp r8,r6 @ else dividende is same divisor ? beq 8f @ yes   mov r0,r5 mov r1,r10 mov r2,r8 mov r3,r12 mov r4,#0 bl computeFactors cmp r0,#-1 beq 100f mov r12,r0 mov r10,r1 mov r7,#0 b 11f 8: sub r7,r10,#1 9: ldr r3,[r5,r7,lsl #2 ] cmp r3,r8 subne r7,#1 bne 9b   mov r0,r5 mov r1,r10 sub r4,r10,r7 mov r2,r8 mov r3,r12 bl computeFactors cmp r0,#-1 beq 100f mov r12,r0 mov r10,r1   b 11f   10: cmp r9,r8 @ current divisor > new dividende ? ble 2b @ no -> loop   /* end decomposition */ 11: mov r0,r10 @ return number of table items mov r1,r12 @ return sum mov r3,#0 str r3,[r5,r10,lsl #2] @ store zéro in last table item b 100f     98: @ prime number add r1,r8,#1 mov r0,#0 @ return code b 100f 99: ldr r0,iAdrszMessError bl affichageMess mov r0,#-1 @ error code b 100f 100: pop {r3-r12,pc} @ restaur registers /******************************************************************/ /* compute all factors */ /******************************************************************/   /* r0 table factors address */ /* r1 number factors in table */ /* r2 new divisor */ /* r3 sum */ /* r4 start indice */ /* r0 return sum */ /* r1 return number factors in table */ computeFactors: push {r2-r6,lr} @ save registers mov r6,r1 @ number factors in table 1: ldr r5,[r0,r4,lsl #2 ] @ load one factor mul r5,r2,r5 @ multiply str r5,[r0,r1,lsl #2] @ and store in the table   adds r3,r5 movcs r0,#-1 @ overflow bcs 100f add r1,r1,#1 @ and increment counter add r4,r4,#1 cmp r4,r6 blt 1b mov r0,r3 @ factors sum 100: @ fin standard de la fonction pop {r2-r6,pc} @ restaur des registres /***************************************************/ /* check if a number is prime */ /***************************************************/ /* r0 contains the number */ /* r0 return 1 if prime 0 else */ isPrime: push {r1-r6,lr} @ save registers cmp r0,#0 beq 90f cmp r0,#17 bhi 1f cmp r0,#3 bls 80f @ for 1,2,3 return prime cmp r0,#5 beq 80f @ for 5 return prime cmp r0,#7 beq 80f @ for 7 return prime cmp r0,#11 beq 80f @ for 11 return prime cmp r0,#13 beq 80f @ for 13 return prime cmp r0,#17 beq 80f @ for 17 return prime 1: tst r0,#1 @ even ? beq 90f @ yes -> not prime mov r2,r0 @ save number sub r1,r0,#1 @ exposant n - 1 mov r0,#3 @ base bl moduloPuR32 @ compute base power n - 1 modulo n cmp r0,#1 bne 90f @ if <> 1 -> not prime   mov r0,#5 bl moduloPuR32 cmp r0,#1 bne 90f   mov r0,#7 bl moduloPuR32 cmp r0,#1 bne 90f   mov r0,#11 bl moduloPuR32 cmp r0,#1 bne 90f   mov r0,#13 bl moduloPuR32 cmp r0,#1 bne 90f   mov r0,#17 bl moduloPuR32 cmp r0,#1 bne 90f 80: mov r0,#1 @ is prime b 100f 90: mov r0,#0 @ no prime 100: @ fin standard de la fonction pop {r1-r6,pc} @ restaur des registres /********************************************************/ /* Calcul modulo de b puissance e modulo m */ /* Exemple 4 puissance 13 modulo 497 = 445 */ /* */ /********************************************************/ /* r0 nombre */ /* r1 exposant */ /* r2 modulo */ /* r0 return result */ moduloPuR32: push {r1-r7,lr} @ save registers cmp r0,#0 @ verif <> zero beq 100f cmp r2,#0 @ verif <> zero beq 100f @ TODO: v鲩fier les cas d erreur 1: mov r4,r2 @ save modulo mov r5,r1 @ save exposant mov r6,r0 @ save base mov r3,#1 @ start result   mov r1,#0 @ division de r0,r1 par r2 bl division32R mov r6,r2 @ base <- remainder 2: tst r5,#1 @ exposant even or odd beq 3f umull r0,r1,r6,r3 mov r2,r4 bl division32R mov r3,r2 @ result <- remainder 3: umull r0,r1,r6,r6 mov r2,r4 bl division32R mov r6,r2 @ base <- remainder   lsr r5,#1 @ left shift 1 bit cmp r5,#0 @ end ? bne 2b mov r0,r3 100: @ fin standard de la fonction pop {r1-r7,pc} @ restaur des registres   /***************************************************/ /* division number 64 bits in 2 registers by number 32 bits */ /***************************************************/ /* r0 contains lower part dividende */ /* r1 contains upper part dividende */ /* r2 contains divisor */ /* r0 return lower part quotient */ /* r1 return upper part quotient */ /* r2 return remainder */ division32R: push {r3-r9,lr} @ save registers mov r6,#0 @ init upper upper part remainder  !! mov r7,r1 @ init upper part remainder with upper part dividende mov r8,r0 @ init lower part remainder with lower part dividende mov r9,#0 @ upper part quotient mov r4,#0 @ lower part quotient mov r5,#32 @ bits number 1: @ begin loop lsl r6,#1 @ shift upper upper part remainder lsls r7,#1 @ shift upper part remainder orrcs r6,#1 lsls r8,#1 @ shift lower part remainder orrcs r7,#1 lsls r4,#1 @ shift lower part quotient lsl r9,#1 @ shift upper part quotient orrcs r9,#1 @ divisor sustract upper part remainder subs r7,r2 sbcs r6,#0 @ and substract carry bmi 2f @ n駡tive ?   @ positive or equal orr r4,#1 @ 1 -> right bit quotient b 3f 2: @ negative orr r4,#0 @ 0 -> right bit quotient adds r7,r2 @ and restaur remainder adc r6,#0 3: subs r5,#1 @ decrement bit size bgt 1b @ end ? mov r0,r4 @ lower part quotient mov r1,r9 @ upper part quotient mov r2,r7 @ remainder 100: @ function end pop {r3-r9,pc} @ restaur registers   /***************************************************/ /* ROUTINES INCLUDE */ /***************************************************/ .include "../affichage.inc"    
http://rosettacode.org/wiki/Active_Directory/Search_for_a_user
Active Directory/Search for a user
Make sure you Connect to Active Directory
#C
C
#include <ldap.h>   char *name, *password; ...   LDAP *ld = ldap_init("ldap.somewhere.com", 389); ldap_simple_bind_s(ld, name, password);   LDAPMessage **result; ldap_search_s(ld, "dc=somewhere,dc=com", LDAP_SCOPE_SUBTREE, /* search for all persons whose names start with joe or shmoe */ "(&(objectclass=person)(|(cn=joe*)(cn=shmoe*)))", NULL, /* return all attributes */ 0, /* want both types and values of attrs */ result); /* ldap will allocate room for return messages */   /* arduously do stuff here to result, with ldap_first_message(), ldap_parse_result(), etc. */   ldap_msgfree(*result); /* free messages */ ldap_unbind(ld); /* disconnect */
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.
#Axe
Axe
°A→B .B now contains the address of A
http://rosettacode.org/wiki/Address_of_a_variable
Address of a variable
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation | Comparison | Matching Memory Operations Pointers & references | Addresses Task Demonstrate how to get the address of a variable and how to set the address of a variable.
#BaCon
BaCon
  '---get a variable's address LOCAL x TYPE long PRINT ADDRESS(x)  
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.
#BASIC
BASIC
'get a variable's address: DIM x AS INTEGER, y AS LONG y = VARPTR(x)   'can't set the address, but can access a given memory location... 1 byte at a time DIM z AS INTEGER z = PEEK(y) z = z + (PEEK(y) * 256)
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.
#Ada
Ada
with Ada.Text_IO;   procedure Test_For_Primes is   type Pascal_Triangle_Type is array (Natural range <>) of Long_Long_Integer;   function Calculate_Pascal_Triangle (N : in Natural) return Pascal_Triangle_Type is Pascal_Triangle : Pascal_Triangle_Type (0 .. N); begin Pascal_Triangle (0) := 1; for I in Pascal_Triangle'First .. Pascal_Triangle'Last - 1 loop Pascal_Triangle (1 + I) := 1; for J in reverse 1 .. I loop Pascal_Triangle (J) := Pascal_Triangle (J - 1) - Pascal_Triangle (J); end loop; Pascal_Triangle (0) := -Pascal_Triangle (0); end loop; return Pascal_Triangle; end Calculate_Pascal_Triangle;   function Is_Prime (N : Integer) return Boolean is I  : Integer; Result : Boolean := True; Pascal_Triangle : constant Pascal_Triangle_Type := Calculate_Pascal_Triangle (N); begin I := N / 2; while Result and I > 1 loop Result := Result and Pascal_Triangle (I) mod Long_Long_Integer (N) = 0; I := I - 1; end loop; return Result; end Is_Prime;   function Image (N  : in Long_Long_Integer; Sign : in Boolean := False) return String is Image : constant String := N'Image; begin if N < 0 then return Image; else if Sign then return "+" & Image (Image'First + 1 .. Image'Last); else return Image (Image'First + 1 .. Image'Last); end if; end if; end Image;   procedure Show (Triangle : in Pascal_Triangle_Type) is use Ada.Text_IO; Begin for I in reverse Triangle'Range loop Put (Image (Triangle (I), Sign => True)); Put ("x^"); Put (Image (Long_Long_Integer (I))); Put (" "); end loop; end Show;   procedure Show_Pascal_Triangles is use Ada.Text_IO; begin for N in 0 .. 9 loop declare Pascal_Triangle : constant Pascal_Triangle_Type := Calculate_Pascal_Triangle (N); begin Put ("(x-1)^" & Image (Long_Long_Integer (N)) & " = "); Show (Pascal_Triangle); New_Line; end; end loop; end Show_Pascal_Triangles;   procedure Show_Primes is use Ada.Text_IO; begin for N in 2 .. 63 loop if Is_Prime (N) then Put (N'Image); end if; end loop; New_Line; end Show_Primes;   begin Show_Pascal_Triangles; Show_Primes; end Test_For_Primes;
http://rosettacode.org/wiki/Additive_primes
Additive primes
Definitions In mathematics, additive primes are prime numbers for which the sum of their decimal digits are also primes. Task Write a program to determine (and show here) all additive primes less than 500. Optionally, show the number of additive primes. Also see   the OEIS entry:   A046704 additive primes.   the prime-numbers entry:   additive primes.   the geeks for geeks entry: additive prime number.   the prime-numbers fandom: additive primes.
#ALGOL_W
ALGOL W
begin % find some additive primes - primes whose digit sum is also prime %  % sets p( 1 :: n ) to a sieve of primes up to n % procedure Eratosthenes ( logical array p( * ) ; integer value n ) ; begin p( 1 ) := false; p( 2 ) := true; for i := 3 step 2 until n do p( i ) := true; for i := 4 step 2 until n do p( i ) := false; for i := 3 step 2 until truncate( sqrt( n ) ) do begin integer ii; ii := i + i; if p( i ) then for pr := i * i step ii until n do p( pr ) := false end for_i ; end Eratosthenes ; integer MAX_NUMBER; MAX_NUMBER := 500; begin logical array prime( 1 :: MAX_NUMBER ); integer aCount;  % sieve the primes to MAX_NUMBER % Eratosthenes( prime, MAX_NUMBER );  % find the primes that are additive primes % aCount := 0; for i := 1 until MAX_NUMBER - 1 do begin if prime( i ) then begin integer dSum, v; v  := i; dSum := 0; while v > 0 do begin dSum := dSum + v rem 10; v  := v div 10 end while_v_gt_0 ; if prime( dSum ) then begin writeon( i_w := 4, s_w := 0, " ", i ); aCount := aCount + 1; if aCount rem 20 = 0 then write() end if_prime_dSum end if_prime_i end for_i ; write( i_w := 1, s_w := 0, "Found ", aCount, " additive primes below ", MAX_NUMBER ) end end.
http://rosettacode.org/wiki/Additive_primes
Additive primes
Definitions In mathematics, additive primes are prime numbers for which the sum of their decimal digits are also primes. Task Write a program to determine (and show here) all additive primes less than 500. Optionally, show the number of additive primes. Also see   the OEIS entry:   A046704 additive primes.   the prime-numbers entry:   additive primes.   the geeks for geeks entry: additive prime number.   the prime-numbers fandom: additive primes.
#APL
APL
((+⌿(4/10)⊤P)∊P)/P←(~P∊P∘.×P)/P←1↓⍳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
#Haskell
Haskell
data Color = R | B data Tree a = E | T Color (Tree a) a (Tree a)   balance :: Color -> Tree a -> a -> Tree a -> Tree a balance B (T R (T R a x b) y c ) z d = T R (T B a x b) y (T B c z d) balance B (T R a x (T R b y c)) z d = T R (T B a x b) y (T B c z d) balance B a x (T R (T R b y c) z d ) = T R (T B a x b) y (T B c z d) balance B a x (T R b y (T R c z d)) = T R (T B a x b) y (T B c z d) balance col a x b = T col a x b   insert :: Ord a => a -> Tree a -> Tree a insert x s = T B a y b where ins E = T R E x E ins s@(T col a y b) | x < y = balance col (ins a) y b | x > y = balance col a y (ins b) | otherwise = s T _ a y b = ins s
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
#J
J
insert=:{{ 'R';'';y;a: : if. 0=#y do. insert x elseif. 0=L.y do. x insert insert y else. 'C e K w'=. y select. *x - K case. _1 do. balance C;(x insert e);K;<w case. 0 do. y case. 1 do. balance C;e;K;<x insert w end. end. }}   NB. C: color, e: east, K: key, w: west NB. two cascaded reds under a black become two black siblings under a red balance=: {{ 'C e K w'=. y if. #e do. 'eC ee eK ew'=. e if. 'R'=eC do. if. #ee do. 'eeC eee eeK eew'=. ee NB. ((eee eeK eew) eK ew) K w => (eee eeK eew) eK (ew K w) if. 'R'=eeC do. 'R';('B';eee;eeK;<eew);eK;<'B';ew;K;<w return. end. end. if. #ew do. 'ewC ewe ewK eww'=. ew NB. (ee ek (ewe ewK eww)) K w => (ee ek ewe) ewK (eww K w) if. 'R'=ewC do. 'R';('B';ee;eK;<ewe);ewK;<'B';eww;K;<w return. end. end. end. end. if. #w do. 'wC we wK ww'=. w if. 'R'=wC do. if. #we do. 'weC wee weK wew'=. we NB. e K ((wee weK wew) wK ww) => (e K wee) weK (wew wK ww) if. 'R'=weC do. 'R';('B';e;K;<wee);weK;<'B';wew;wK;<ww return. end. end. if. #ww do. 'wwC wwe wwK www'=. ww NB. e K (we wK (wwe wwK www)) => (e K we) wK (wwe wwK www) if. 'R'=wwC do. 'R';('B';e;K;<we);wK;<'B';wwe;wwK;<www return. end. end. end. end. y }}
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
#Cowgol
Cowgol
include "cowgol.coh";   sub kprime(n: uint8, k: uint8): (kp: uint8) is var p: uint8 := 2; var f: uint8 := 0; while f < k and p*p <= n loop while 0 == n % p loop n := n / p; f := f + 1; end loop; p := p + 1; end loop; if n > 1 then f := f + 1; end if; if f == k then kp := 1; else kp := 0; end if; end sub;   var k: uint8 := 1; while k <= 5 loop print("k = "); print_i8(k); print(":");   var i: uint8 := 2; var c: uint8 := 0; while c < 10 loop if kprime(i,k) != 0 then print(" "); print_i8(i); c := c + 1; end if; i := i + 1; end loop; print_nl(); k := k + 1; end loop;
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
#D
D
import std.stdio, std.algorithm, std.traits;   Unqual!T[] decompose(T)(in T number) pure nothrow in { assert(number > 1); } body { typeof(return) result; Unqual!T n = number;   for (Unqual!T i = 2; n % i == 0; n /= i) result ~= i; for (Unqual!T i = 3; n >= i * i; i += 2) for (; n % i == 0; n /= i) result ~= i;   if (n != 1) result ~= n; return result; }   void main() { enum outLength = 10; // 10 k-th almost primes.   foreach (immutable k; 1 .. 6) { writef("K = %d: ", k); auto n = 2; // The "current number" to be checked. foreach (immutable i; 1 .. outLength + 1) { while (n.decompose.length != k) n++; // Now n is K-th almost prime. write(n, " "); n++; } writeln; } }
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
#BaCon
BaCon
OPTION COLLAPSE TRUE   DECLARE idx$ ASSOC STRING   FOR w$ IN LOAD$("unixdict.txt") STEP NL$   set$ = SORT$(EXPLODE$(w$, 1))   idx$(set$) = APPEND$(idx$(set$), 0, w$) total = AMOUNT(idx$(set$))   IF MaxCount < total THEN MaxCount = total NEXT   PRINT "Analyzing took ", TIMER, " msecs.", NL$   LOOKUP idx$ TO n$ SIZE x FOR y = 0 TO x-1 IF MaxCount = AMOUNT(idx$(n$[y])) THEN PRINT n$[y], ": ", idx$(n$[y]) NEXT
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
#Lua
Lua
bearing = {degrees = 0} -- prototype object   function bearing:assign(angle) angle = tonumber(angle) or 0 while angle > 180 do angle = angle - 360 end while angle < -180 do angle = angle + 360 end self.degrees = angle end   function bearing:new(size) local child_object = {} setmetatable(child_object, {__index = self}) child_object:assign(size) return child_object end   function bearing:subtract(other) local difference = self.degrees - other.degrees return self:new(difference) end   function bearing:list(sizes) local bearings = {} for index, size in ipairs(sizes) do table.insert(bearings, self:new(size)) end return bearings end   function bearing:text() return string.format("%.4f deg", self.degrees) end   function main() local subtrahends = bearing:list{ 20, -45, -85, -95, -45, -45, 29.4803, -78.3251, -70099.74233810938, -165313.6666297357, 1174.8380510598456, 60175.77306795546 } local minuends = bearing:list{ 45, 45, 90, 90, 125, 145, -88.6381, -159.036, 29840.67437876723, 33693.9894517456, -154146.66490124757, 42213.07192354373 } for index = 1, #minuends do local b2, b1 = minuends[index], subtrahends[index] local b3 = b2:subtract(b1) local statement = string.format( "%s - %s = %s\n", b2:text(), b1:text(), b3:text() ) io.write(statement) end end   main()
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
#Pascal
Pascal
program Anagrams_Deranged; {$IFDEF FPC} {$MODE Delphi} {$Optimization ON,ALL} uses SysUtils, Classes; {$ELSE} {$APPTYPE CONSOLE} uses System.SysUtils, System.Classes, {$R *.res} {$ENDIF}   function Sort(const s: string):string; //insertion sort var pRes : pchar; i, j, aLength: NativeInt; tmpc: Char; begin aLength := s.Length;   if aLength = 0 then exit('');   Result := s; //without it, s will be sorted UniqueString(Result); //insertion sort pRes := pChar(Result); dec(aLength,1); for i := 0 to aLength do Begin tmpc := pRes[i]; j := i-1; while (j>=0) AND (tmpc < pRes[j]) do Begin pRes[j+1] := pRes[j]; dec(j); end; inc(j); pRes[j]:= tmpc; end; end;   function CompareLength(List: TStringList; Index1, Index2: longInt): longInt; begin result := List[Index1].Length - List[Index2].Length; IF result = 0 then result := CompareStr(List[Index1],List[Index2]); end;   function IsDerangement(const word1, word2: string): Boolean; var i: NativeInt; begin for i := word1.Length downto 1 do if word1[i] = word2[i] then exit(False); Result := True; end;   var Dict,SortDict: TStringList; words: string; StopWatch: Int64; Count, Index: NativeInt;   begin Dict := TStringList.Create(); Dict.LoadFromFile('unixdict.txt');   StopWatch := GettickCount64; SortDict:= TStringList.Create(); SortDict.capacity := Dict.Count; For Index := 0 to Dict.Count - 1 do Begin SortDict.Add(Sort(Dict[Index])); //remember the origin in Dict SortDict.Objects[Index]:= TObject(Index); end;   SortDict.CustomSort(CompareLength);   Index := Dict.Count - 1; words := ''; Count := 1;   while Index - Count >= 0 do begin if SortDict[Index]= SortDict[Index - Count] then begin if IsDerangement(Dict[NativeInt(SortDict.Objects[Index])], Dict[NativeInt(SortDict.Objects[Index - Count])]) then begin words := Dict[NativeInt(SortDict.Objects[Index])] + ' - ' + Dict[NativeInt(SortDict.Objects[Index - Count])]; Break; end; Inc(Count); end else begin Dec(Index, Count); Count := 1; end; end; StopWatch := GettickCount64-StopWatch; Writeln(Format('Time pass: %d ms [AMD 2200G-Linux Fossa]',[StopWatch])); writeln(#10'Longest derangement words are:'#10#10, words);   SortDict.free; Dict.Free; 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.
#Kotlin
Kotlin
fun fib(n: Int): Int { require(n >= 0) fun fib1(k: Int, a: Int, b: Int): Int = if (k == 0) a else fib1(k - 1, b, a + b) return fib1(n, 0, 1) }   fun main(args: Array<String>) { for (i in 0..20) print("${fib(i)} ") println() }
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.
#Haskell
Haskell
divisors :: (Integral a) => a -> [a] divisors n = filter ((0 ==) . (n `mod`)) [1 .. (n `div` 2)]   main :: IO () main = do let range = [1 .. 20000 :: Int] divs = zip range $ map (sum . divisors) range pairs = [(n, m) | (n, nd) <- divs, (m, md) <- divs, n < m, nd == m, md == n] print pairs
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.
#R
R
  rotate_string <- function(x, forwards) {    nchx <- nchar(x)    if(forwards)    {                                         paste(substr(x, nchx, nchx), substr(x, 1, nchx - 1), sep = "")    } else    {                                                                 paste(substr(x, 2, nchx), substr(x, 1, 1), sep = "")    } }   handle_rotate_label <- function(obj, interval = 100) {   addHandlerIdle(obj,     handler = function(h, ...)     {        svalue(obj) <- rotate_string(svalue(obj), tag(obj, "forwards"))     },     interval = interval   ) }   handle_change_direction_on_click <- function(obj) {   addHandlerClicked(obj,     handler = function(h, ...)     {       tag(h$obj, "forwards") <- !tag(h$obj, "forwards")     }   ) }   library(gWidgets) library(gWidgetstcltk) #or library(gWidgetsRGtk2) or library(gWidgetsrJava)              lab <- glabel("Hello World! ", container = gwindow())   tag(lab, "forwards") <- TRUE handle_rotate_label(lab) handle_change_direction_on_click(lab)  
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.
#Racket
Racket
  #lang racket/gui   ;; One of 'left or 'right (define direction 'left)   ;; Set up the GUI (define animation-frame% (class frame% (super-new [label "Animation"])  ;; reverse direction on a click (define/override (on-subwindow-event win evt) (when (send evt button-down?) (set! direction (if (eq? direction 'left) 'right 'left))))))   (define frame (new animation-frame%)) (define msg (new message% [label "Hello World! "] [parent frame]))   ;; Timer callback to adjust the message (define (callback) (define old-label (send msg get-label)) (define len (string-length old-label)) (if (eq? direction 'left) (send msg set-label (string-append (substring old-label 1) (substring old-label 0 1))) (send msg set-label (string-append (substring old-label (- len 1) len) (substring old-label 0 (- len 1))))))   ;; Set a timer and go (define timer (new timer% [notify-callback callback] [interval 500]))   (send frame show #t)  
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.
#Logo
Logo
make "angle 45 make "L 1 make "bob 10   to draw.pendulum clearscreen seth :angle+180 ; down on screen is 180 forward :L*100-:bob penup forward :bob pendown arc 360 :bob end   make "G 9.80665 make "dt 1/30 make "acc 0 make "vel 0   to step.pendulum make "acc -:G / :L * sin :angle make "vel  :vel + :acc * :dt make "angle :angle + :vel * :dt wait :dt*60 draw.pendulum end   hideturtle until [key?] [step.pendulum]
http://rosettacode.org/wiki/Amb
Amb
Define and give an example of the Amb operator. The Amb operator (short for "ambiguous") expresses nondeterminism. This doesn't refer to randomness (as in "nondeterministic universe") but is closely related to the term as it is used in automata theory ("non-deterministic finite automaton"). The Amb operator takes a variable number of expressions (or values if that's simpler in the language) and yields a correct one which will satisfy a constraint in some future computation, thereby avoiding failure. Problems whose solution the Amb operator naturally expresses can be approached with other tools, such as explicit nested iterations over data sets, or with pattern matching. By contrast, the Amb operator appears integrated into the language. Invocations of Amb are not wrapped in any visible loops or other search patterns; they appear to be independent. Essentially Amb(x, y, z) splits the computation into three possible futures: a future in which the value x is yielded, a future in which the value y is yielded and a future in which the value z is yielded. The future which leads to a successful subsequent computation is chosen. The other "parallel universes" somehow go away. Amb called with no arguments fails. For simplicity, one of the domain values usable with Amb may denote failure, if that is convenient. For instance, it is convenient if a Boolean false denotes failure, so that Amb(false) fails, and thus constraints can be expressed using Boolean expressions like Amb(x * y == 8) which unless x and y add to four. A pseudo-code program which satisfies this constraint might look like: let x = Amb(1, 2, 3) let y = Amb(7, 6, 4, 5) Amb(x * y = 8) print x, y The output is 2 4 because Amb(1, 2, 3) correctly chooses the future in which x has value 2, Amb(7, 6, 4, 5) chooses 4 and consequently Amb(x * y = 8) produces a success. Alternatively, failure could be represented using strictly Amb(): unless x * y = 8 do Amb() Or else Amb could take the form of two operators or functions: one for producing values and one for enforcing constraints: let x = Ambsel(1, 2, 3) let y = Ambsel(4, 5, 6) Ambassert(x * y = 8) print x, y where Ambassert behaves like Amb() if the Boolean expression is false, otherwise it allows the future computation to take place, without yielding any value. The task is to somehow implement Amb, and demonstrate it with a program which chooses one word from each of the following four sets of character strings to generate a four-word sentence: "the" "that" "a" "frog" "elephant" "thing" "walked" "treaded" "grows" "slowly" "quickly" The constraint to be satisfied is that the last character of each word (other than the last) is the same as the first character of its successor. The only successful sentence is "that thing grows slowly"; other combinations do not satisfy the constraint and thus fail. The goal of this task isn't to simply process the four lists of words with explicit, deterministic program flow such as nested iteration, to trivially demonstrate the correct output. The goal is to implement the Amb operator, or a facsimile thereof that is possible within the language limitations.
#Clojure
Clojure
(ns amb (:use clojure.contrib.monads))   (defn amb [wss] (let [valid-word (fn [w1 w2] (if (and w1 (= (last w1) (first w2))) (str w1 " " w2)))] (filter #(reduce valid-word %) (with-monad sequence-m (m-seq wss)))))   amb> (amb '(("the" "that" "a") ("frog" "elephant" "thing") ("walked" "treaded" "grows") ("slowly" "quickly"))) (("that" "thing" "grows" "slowly"))  
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
#AWK
AWK
  #!/bin/gawk -f function sumprop(num, i,sum,root) { if (num == 1) return 0 sum=1 root=sqrt(num) for ( i=2; i < root; i++) { if (num % i == 0 ) { sum = sum + i + num/i } } if (num % root == 0) { sum = sum + root } return sum } function class(k, oldk,newk,seq){ # first term oldk = k seq = " " # second term newk = sumprop(oldk) oldk = newk seq = seq " " newk if (newk == 0) return "terminating " seq if (newk == k) return "perfect " seq # third term newk = sumprop(oldk) oldk = newk seq = seq " " newk if (newk == 0) return "terminating " seq if (newk == k) return "amicable " seq for (t=4; t<17; t++) { newk = sumprop(oldk) seq = seq " " newk if (newk == 0) return "terminating " seq if (newk == k) return "sociable (period " t-1 ") "seq if (newk == oldk) return "aspiring " seq if (index(seq," " newk " ") > 0) return "cyclic (at " newk ") " seq if (newk > 140737488355328) return "non-terminating (term > 140737488355328) " seq oldk = newk } return "non-terminating (after 16 terms) " seq } BEGIN{ print "Number classification sequence" for (j=1; j < 11; j++) { print j,class(j)} print 11,class(11) print 12,class(12) print 28,class(28) print 496,class(496) print 220,class(220) print 1184,class(1184) print 12496,class(12496) print 1264460,class(1264460) print 790,class(790) print 909,class(909) print 562,class(562) print 1064,class(1064) print 1488,class(1488) print 15355717786080,class(15355717786080)   }    
http://rosettacode.org/wiki/Active_Directory/Search_for_a_user
Active Directory/Search for a user
Make sure you Connect to Active Directory
#D
D
  import openldap; import std.stdio;   void main() { // connect to server auto ldap = LDAP("ldap://localhost");   // search for uid auto r = ldap.search_s("dc=example,dc=com", LDAP_SCOPE_SUBTREE, "(uid=%s)".format("test"));   // show properties writeln("Found dn: %s", r[0].dn); foreach(k, v; r[0].entry) writeln("%s = %s", k, v);   // bind on found entry int b = ldap.bind_s(r[0].dn, "password"); scope(exit) ldap.unbind; if (b) { writeln("error on binding"); return; }   // do something ...   }  
http://rosettacode.org/wiki/Active_Directory/Search_for_a_user
Active Directory/Search for a user
Make sure you Connect to Active Directory
#Eiffel
Eiffel
  feature -- Validation   is_user_credential_valid (a_domain, a_username, a_password: READABLE_STRING_GENERAL): BOOLEAN -- Is the pair `a_username'/`a_password' a valid credential in `a_domain'? local l_domain, l_username, l_password: WEL_STRING do create l_domain.make (a_domain) create l_username.make (a_username) create l_password.make (a_password) Result := cwel_is_credential_valid (l_domain.item, l_username.item, l_password.item) end  
http://rosettacode.org/wiki/Active_Directory/Search_for_a_user
Active Directory/Search for a user
Make sure you Connect to Active Directory
#Go
Go
package main   import ( "log" "github.com/jtblin/go-ldap-client" )   func main() { client := &ldap.LDAPClient{ Base: "dc=example,dc=com", Host: "ldap.example.com", Port: 389, GroupFilter: "(memberUid=%s)", } defer client.Close() err := client.Connect() if err != nil { log.Fatalf("Failed to connect : %+v", err) } groups, err := client.GetGroupsOfUser("username") if err != nil { log.Fatalf("Error getting groups for user %s: %+v", "username", err) } log.Printf("Groups: %+v", groups) }
http://rosettacode.org/wiki/Add_a_variable_to_a_class_instance_at_runtime
Add a variable to a class instance at runtime
Demonstrate how to dynamically add variables to an object (a class instance) at runtime. This is useful when the methods/variables of an instance are based on a data file that isn't available until runtime. Hal Fulton gives an example of creating an OO CSV parser at An Exercise in Metaprogramming with Ruby. This is referred to as "monkeypatching" by Pythonistas and some others.
#ActionScript
ActionScript
var object:Object = new Object(); object.foo = "bar";
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.
#BBC_BASIC
BBC BASIC
REM get a variable's address: y% = ^x%   REM can't set a variable's address, but can access a given memory location (4 bytes): x% = !y%
http://rosettacode.org/wiki/Address_of_a_variable
Address of a variable
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation | Comparison | Matching Memory Operations Pointers & references | Addresses Task Demonstrate how to get the address of a variable and how to set the address of a variable.
#C_.2F_C.2B.2B
C / C++
int i; void* address_of_i = &i;
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.
#C.23
C#
unsafe { int i = 5; void* address_of_i = &i; }
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.
#ALGOL_68
ALGOL 68
  BEGIN COMMENT Mathematical preliminaries.   First note that the homogeneous polynomial (a+b)^n is symmetrical (to see this just swap the variables a and b). Therefore its coefficients need be calculated only to that of (ab)^{n/2} for even n or (ab)^{(n-1)/2} for odd n.   Second, the coefficients are the binomial coefficients C(n,k) where the coefficient of a^k b^(n-k) is C(n,k) = n! / k! (k-1)!. This leads to an immediate and relatively efficient implementation for which we do not need to compute n! before dividing by k! and (k-1)! but, rather cancel common factors as we go along. Further, the well-known symmetry identity C(n,k) = C(n, n-k) allows a significant reduction in computational effort.   Third, (x-1)^n is the value of (a + b)^n when a=x and b = -1. The powers of -1 alternate between +1 and -1 so we may as well compute (x+1)^n and negate every other coefficient when printing. COMMENT PR precision=300 PR MODE LLI = LONG LONG INT; CO For brevity CO PROC choose = (INT n, k) LLI : BEGIN LLI result := 1; INT sym k := (k >= n%2 | n-k | k); CO Use symmetry CO IF sym k > 0 THEN FOR i FROM 0 TO sym k-1 DO result TIMESAB (n-i); result OVERAB (i+1) OD FI; result END; PROC coefficients = (INT n) [] LLI : BEGIN [0:n] LLI a; FOR i FROM 0 TO n%2 DO a[i] := a[n-i] := choose (n, i) CO Use symmetry CO OD; a END; COMMENT First print the polynomials (x-1)^n, remembering to alternate signs and to tidy up the constant term, the x^1 term and the x^n term. This means we must treat (x-1)^0 and (x-1)^1 specially COMMENT FOR n FROM 0 TO 7 DO [0:n] LLI a := coefficients (n); printf (($"(x-1)^", g(0), " = "$, n)); CASE n+1 IN printf (($g(0)l$, a[0])), printf (($"x - ", g(0)l$, a[1])) OUT printf (($"x^", g(0)$, n)); FOR i TO n-2 DO printf (($xax, g(0), "x^", g(0)$, (ODD i | "-" | "+"), a[i], n-i)) OD; printf (($xax, g(0), "x"$, (ODD (n-1) | "-" | "+"), a[n-1])); printf (($xaxg(0)l$, (ODD n | "-" | "+"), a[n])) ESAC OD; COMMENT Finally, for the "AKS" portion of the task, the sign of the coefficient has no effect on its divisibility by p so, once again, we may as well use the positive coefficients. Symmetry clearly reduces the necessary number of tests by a factor of two. COMMENT PROC is prime = (INT n) BOOL : BEGIN BOOL prime := TRUE; FOR i FROM 1 TO n%2 WHILE prime DO prime := choose (n, i) MOD n = 0 OD; prime END; print ("Primes < 50 are "); FOR n FROM 2 TO 50 DO (is prime (n) | printf (($g(0)x$, n)) ) OD; print (newline); print ("And just to show off, the primes between 900 and 1000 are "); FOR n FROM 900 TO 1000 DO IF is prime (n) THEN printf (($g(0)x$, n)) FI OD; print (newline) END  
http://rosettacode.org/wiki/Additive_primes
Additive primes
Definitions In mathematics, additive primes are prime numbers for which the sum of their decimal digits are also primes. Task Write a program to determine (and show here) all additive primes less than 500. Optionally, show the number of additive primes. Also see   the OEIS entry:   A046704 additive primes.   the prime-numbers entry:   additive primes.   the geeks for geeks entry: additive prime number.   the prime-numbers fandom: additive primes.
#AppleScript
AppleScript
on sieveOfEratosthenes(limit) script o property numberList : {missing value} end script   repeat with n from 2 to limit set end of o's numberList to n end repeat   repeat with n from 2 to (limit ^ 0.5) div 1 if (item n of o's numberList is n) then repeat with multiple from n * n to limit by n set item multiple of o's numberList to missing value end repeat end if end repeat   return o's numberList's numbers end sieveOfEratosthenes   on sumOfDigits(n) -- n assumed to be a positive decimal integer. set sum to n mod 10 set n to n div 10 repeat until (n = 0) set sum to sum + n mod 10 set n to n div 10 end repeat   return sum end sumOfDigits   on additivePrimes(limit) script o property primes : sieveOfEratosthenes(limit) property additives : {} end script   repeat with p in o's primes if (sumOfDigits(p) is in o's primes) then set end of o's additives to p's contents end repeat   return o's additives end additivePrimes   -- Task code: tell additivePrimes(499) to return {|additivePrimes<500|:it, numberThereof:count}
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
#jq
jq
# bindings($x) attempts to match . and $x structurally on the # assumption that . is free of JSON objects, and that any objects in # $x will have distinct, singleton keys that are to be interpreted as # variables. These variables will match the corresponding entities in # . if . and $x can be structurally matched. # # If . and $x cannot be matched, then null is returned; # otherwise, if $x contains no objects, {} is returned; # finally, if . and $x can be structurally matched, a composite object containing the bindings # will be returned. # Output: null (failure to match) or a single JSON object giving the bindings if any. def bindings($x): if $x == . then {} # by assumption, no bindings are necessary elif ($x|type) == "object" then ($x|keys) as $keys | if ($keys|length) == 1 then {($keys[0]): .} else "objects should be singletons"|error end elif type != ($x|type) then null elif type == "array" then if length != ($x|length) then null else . as $in | reduce range(0;length) as $i ({}; if . == null then null else ($in[$i] | bindings($x[$i]) ) as $m | if $m == null then null else . + $m end end) end else null end ;
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
#Julia
Julia
import Base.length   abstract type AbstractColoredNode end   struct RedNode <: AbstractColoredNode end; const R = RedNode() struct BlackNode <: AbstractColoredNode end; const B = BlackNode() struct Empty end; const E = Empty() length(e::Empty) = 1   function balance(b::BlackNode, v::Vector, z, d) if v[1] == R if length(v[2]) == 4 && v[2][1] == R return [R, [B, v[2][2], v[2][3], v[2][4]], v[3], [B, v[4], z, d]] elseif length(v[4]) == 4 && v[4][1] == R return [R, [B, v[2], v[3], v[4][2]], v[4][3], [B, v[4][4], z, d]] end end [b, v, z, d] end   function balance(b::BlackNode, a, x, v::Vector) if v[1] == R if length(v[2]) == 4 && v[2][1] == R return [R, [B, a, x, v[2][2]], v[2][3], [B, v[2][4], v[3], v[4]]] elseif length(v[4]) == 4 && v[4][1] == R return [R, [B, a, x, v[2]], v[3], [B, v[4][2], v[4][3], v[4][4]]] end end [b, a, x, v] end   function balance(b::BlackNode, a::Vector, x, v::Vector) if v[1] == R if length(v[2]) == 4 && v[2][1] == R return [R, [B, a, x, v[2][2]], v[2][3], [B, v[2][4], v[3], v[4]]] elseif length(v[4]) == 4 && v[4][1] == R return [R, [B, a, x, v[2]], v[3], [B, v[4][2], v[4][3], v[4][4]]] end end [b, a, x, v] end   balance(node, l, a, r) = [node, l, a, r]   function ins(v::Vector, x::Number) if length(v) == 4 if x < v[3] return balance(v[1], ins(v[2], x), v[3], v[4]) elseif x > v[3] return balance(v[1], v[2], v[3], ins(v[4], x)) end end v end   ins(t, a) = [R, E, a, E]   insert(v, a) = (t = ins(v, a); t[1] = B; t)   function testRB() t = E for i in rand(collect(1:20), 10) t = insert(t, i) end println(replace(string(t), r"lackNode\(\)|edNode\(\)|Any|mpty\(\)" => "")) end   testRB()  
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
#Delphi
Delphi
  program AlmostPrime;   {$APPTYPE CONSOLE}   function IsKPrime(const n, k: Integer): Boolean; var p, f, v: Integer; begin f := 0; p := 2; v := n; while (f < k) and (p*p <= n) do begin while (v mod p) = 0 do begin v := v div p; Inc(f); end; Inc(p); end; if v > 1 then Inc(f); Result := f = k; end;   var i, c, k: Integer;   begin for k := 1 to 5 do begin Write('k = ', k, ':'); c := 0; i := 2; while c < 10 do begin if IsKPrime(i, k) then begin Write(' ', i); Inc(c); end; Inc(i); end; WriteLn; end; 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
#BBC_BASIC
BBC BASIC
INSTALL @lib$+"SORTLIB" sort% = FN_sortinit(0,0)   REM Count number of words in dictionary: nwords% = 0 dict% = OPENIN("unixdict.txt") WHILE NOT EOF#dict% word$ = GET$#dict% nwords% += 1 ENDWHILE CLOSE #dict%   REM Create arrays big enough to contain the dictionary: DIM dict$(nwords%), sort$(nwords%)   REM Load the dictionary and sort the characters in the words: dict% = OPENIN("unixdict.txt") FOR word% = 1 TO nwords% word$ = GET$#dict% dict$(word%) = word$ sort$(word%) = FNsortchars(word$) NEXT word% CLOSE #dict%   REM Sort arrays using the 'sorted character' words as a key: C% = nwords% CALL sort%, sort$(1), dict$(1)   REM Count the longest sets of anagrams: max% = 0 set% = 1 FOR word% = 1 TO nwords%-1 IF sort$(word%) = sort$(word%+1) THEN set% += 1 ELSE IF set% > max% THEN max% = set% set% = 1 ENDIF NEXT word%   REM Output the results: set% = 1 FOR word% = 1 TO nwords%-1 IF sort$(word%) = sort$(word%+1) THEN set% += 1 ELSE IF set% = max% THEN FOR anagram% = word%-max%+1 TO word% PRINT dict$(anagram%),; NEXT PRINT ENDIF set% = 1 ENDIF NEXT word% END   DEF FNsortchars(word$) LOCAL C%, char&() DIM char&(LEN(word$)) $$^char&(0) = word$ C% = LEN(word$) CALL sort%, char&(0) = $$^char&(0)
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
#Maple
Maple
getDiff := proc(b1,b2) local r: r := frem(b2 - b1, 360): if r >= 180 then r := r - 360: fi: return r: end proc: getDiff(20,45); getDiff(-45,45); getDiff(-85,90); getDiff(-95,90); getDiff(-45,125); getDiff(-45,145); getDiff(29.4803, -88.6381); getDiff(-78.3251,-159.036); getDiff(-70099.74233810938,29840.67437876723); getDiff(-165313.6666297357,33693.9894517456); getDiff(1174.8380510598456,-154146.66490124757); getDiff(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
#Perl
Perl
sub deranged { # only anagrams ever get here my @a = split('', shift); # split word into letters my @b = split('', shift); for (0 .. $#a) { $a[$_] eq $b[$_] and return; } return 1 }   sub find_deranged { for my $i ( 0 .. $#_ ) { for my $j ( $i+1 .. $#_ ) { next unless deranged $_[$i], $_[$j];   print "length ", length($_[$i]), ": $_[$i] => $_[$j]\n"; return 1; } } }   my %letter_list; open my $in, 'unixdict.txt';   local $/ = undef;   for (split(' ', <$in>)) { # store anagrams in hash table by letters they contain push @{ $letter_list{ join('', sort split('', $_)) } }, $_ }   for ( sort { length($b) <=> length($a) } # sort by length, descending grep { @{ $letter_list{$_} } > 1 } # take only ones with anagrams keys %letter_list ) { # if we find a pair, they are the longested due to the sort before last if find_deranged(@{ $letter_list{$_} }); }
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.
#Lambdatalk
Lambdatalk
  1) defining a quasi-recursive function combined with a simple Ω-combinator: {def fibo {lambda {:n} {{{lambda {:f} {:f :f}} {lambda {:f :n :a :b} {if {< :n 0} then the number must be positive! else {if {<  :n 1} then :a else {:f :f {- :n 1} {+ :a :b} :a}}}}} :n 1 0}}} -> fibo   2) testing: {fibo -1} -> the number must be positive! {fibo 0} -> 1 {fibo 8} -> 34 {fibo 1000} -> 7.0330367711422765e+208 {S.map fibo {S.serie 1 20}} -> 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 6765 10946   We could also avoid any name and write an IIFE   {{lambda {:n} {{{lambda {:f} {:f :f}} {lambda {:f :n :a :b} {if {< :n 0} then the number must be positive! else {if {<  :n 1} then :a else {:f :f {- :n 1} {+ :a :b} :a}}}}} :n 1 0}} 8} -> 34  
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.
#J
J
factors=: [: /:~@, */&>@{@((^ i.@>:)&.>/)@q:~&__ properDivisors=: factors -. -.&1
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.
#Raku
Raku
use GTK::Simple; use GTK::Simple::App;   my $app = GTK::Simple::App.new(:title<Animation>); my $button = GTK::Simple::Button.new(label => 'Hello World! '); my $vbox = GTK::Simple::VBox.new($button);   my $repeat = $app.g-timeout(100); # milliseconds   my $dir = 1; $button.clicked.tap({ $dir *= -1 });   $repeat.tap( &{$button.label = $button.label.comb.List.rotate($dir).join} );   $app.set-content($vbox);   $app.run;
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.
#Lua
Lua
  function degToRad( d ) return d * 0.01745329251 end   function love.load() g = love.graphics rodLen, gravity, velocity, acceleration = 260, 3, 0, 0 halfWid, damp = g.getWidth() / 2, .989 posX, posY, angle = halfWid TWO_PI, angle = math.pi * 2, degToRad( 90 ) end   function love.update( dt ) acceleration = -gravity / rodLen * math.sin( angle ) angle = angle + velocity; if angle > TWO_PI then angle = 0 end velocity = velocity + acceleration velocity = velocity * damp posX = halfWid + math.sin( angle ) * rodLen posY = math.cos( angle ) * rodLen end   function love.draw() g.setColor( 250, 0, 250 ) g.circle( "fill", halfWid, 0, 8 ) g.line( halfWid, 4, posX, posY ) g.setColor( 250, 100, 20 ) g.circle( "fill", posX, posY, 20 ) end  
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.
#Common_Lisp
Common Lisp
(define-condition amb-failure () () (:report "No amb alternative succeeded."))   (defun invoke-ambiguously (function thunks) "Call function with successive values produced by successive functions in thunks until some invocation of function does not signal an amb-failure." (do ((thunks thunks (rest thunks))) ((endp thunks) (error 'amb-failure)) (let ((argument (funcall (first thunks)))) (handler-case (return (funcall function argument)) (amb-failure ())))))   (defmacro amblet1 ((var form) &body body) "If form is of the form (amb {form}*) then amblet1 is a convenient syntax for invoke-ambiguously, by which body is evaluated with var bound the results of each form until some evaluation of body does not signal an amb-failure. For any other form, amblet binds var the result of form, and evaluates body." (if (and (listp form) (eq (first form) 'amb)) `(invoke-ambiguously #'(lambda (,var) ,@body) (list ,@(loop for amb-form in (rest form) collecting `#'(lambda () ,amb-form)))) `(let ((,var ,form)) ,@body)))   (defmacro amblet (bindings &body body) "Like let, except that if an init-form is of the form (amb {form}*), then the corresponding var is bound with amblet1." (if (endp bindings) `(progn ,@body) `(amblet1 ,(first bindings) (amblet ,(rest bindings) ,@body))))
http://rosettacode.org/wiki/Active_Directory/Connect
Active Directory/Connect
The task is to establish a connection to an Active Directory or Lightweight Directory Access Protocol server.
#AutoHotkey
AutoHotkey
objConn := CreateObject("ADODB.Connection") objCmd := CreateObject("ADODB.Command") objConn.Provider := "ADsDSOObject" objConn.Open()
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
#BASIC256
BASIC256
# Rosetta Code problem: http://rosettacode.org/wiki/Aliquot_sequence_classifications # by Jjuanhdez, 06/2022   global limite limite = 20000000   dim nums = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 28, 496, 220, 1184, 12496, 1264460, 790, 909, 562, 1064, 1488}   for n = 0 to nums[?]-1 print "Number "; nums[n]; " : "; call PrintAliquotClassifier(nums[n]) next n print print "Program normal end." end   function PDtotal (n) total = 0 for y = 2 to n if (n mod y) = 0 then total += (n / y) next y return total end function   subroutine PrintAliquotClassifier (K) longit = 52: n = K: clase = 0: priorn = 0: inc = 0 dim Aseq(longit)   for element = 2 to longit Aseq[element] = PDtotal(n) n = int(Aseq[element]) print n; " "; begin case case n = 0 print " Terminating": clase = 1: exit for case n = K and element = 2 print " Perfect"  : clase = 2: exit for case n = K and element = 3 print " Amicable": clase = 3: exit for case n = K and element > 3 print " Sociable": clase = 4: exit for case n <> K and Aseq[element - 1] = Aseq[element] print " Aspiring": clase = 5: exit for case n <> K and Aseq[element - 2] = n print " Cyclic": clase = 6: exit for end case   if n > priorn then priorn = n: inc += 1 else inc = 0: priorn = 0 if inc = 11 or n > limite then exit for next element if clase = 0 then print " non-terminating" end subroutine
http://rosettacode.org/wiki/Active_Directory/Search_for_a_user
Active Directory/Search for a user
Make sure you Connect to Active Directory
#Haskell
Haskell
{-# LANGUAGE OverloadedStrings #-}   module Main (main) where   import Data.Foldable (for_) import qualified Data.Text.Encoding as Text (encodeUtf8) import Ldap.Client (Attr(..), Filter(..)) import qualified Ldap.Client as Ldap (Dn(..), Host(..), search, with, typesOnly)   main :: IO () main = do entries <- Ldap.with (Ldap.Plain "localhost") 389 $ \ldap -> Ldap.search ldap (Ldap.Dn "o=example.com") (Ldap.typesOnly True) (Attr "uid" := Text.encodeUtf8 "user") [] for_ entries $ \entry -> print entry
http://rosettacode.org/wiki/Active_Directory/Search_for_a_user
Active Directory/Search for a user
Make sure you Connect to Active Directory
#Java
Java
import java.io.IOException; import org.apache.directory.api.ldap.model.cursor.CursorException; import org.apache.directory.api.ldap.model.cursor.EntryCursor; import org.apache.directory.api.ldap.model.entry.Entry; import org.apache.directory.api.ldap.model.exception.LdapException; import org.apache.directory.api.ldap.model.message.SearchScope; import org.apache.directory.ldap.client.api.LdapConnection; import org.apache.directory.ldap.client.api.LdapNetworkConnection;   public class LdapSearchDemo {   public static void main(String[] args) throws IOException, LdapException, CursorException { new LdapSearchDemo().demonstrateSearch(); }   private void demonstrateSearch() throws IOException, LdapException, CursorException { try (LdapConnection conn = new LdapNetworkConnection("localhost", 11389)) { conn.bind("uid=admin,ou=system", "********"); search(conn, "*mil*"); conn.unBind(); } }   private void search(LdapConnection connection, String uid) throws LdapException, CursorException { String baseDn = "ou=users,o=mojo"; String filter = "(&(objectClass=person)(&(uid=" + uid + ")))"; SearchScope scope = SearchScope.SUBTREE; String[] attributes = {"dn", "cn", "sn", "uid"}; int ksearch = 0;   EntryCursor cursor = connection.search(baseDn, filter, scope, attributes); while (cursor.next()) { ksearch++; Entry entry = cursor.get(); System.out.printf("Search entry %d = %s%n", ksearch, entry); } } }
http://rosettacode.org/wiki/Add_a_variable_to_a_class_instance_at_runtime
Add a variable to a class instance at runtime
Demonstrate how to dynamically add variables to an object (a class instance) at runtime. This is useful when the methods/variables of an instance are based on a data file that isn't available until runtime. Hal Fulton gives an example of creating an OO CSV parser at An Exercise in Metaprogramming with Ruby. This is referred to as "monkeypatching" by Pythonistas and some others.
#Ada
Ada
with Ada.Text_IO; use Ada.Text_IO;   procedure Dynamic is package Abstract_Class is type Class is limited interface; function Boo (X : Class) return String is abstract; end Abstract_Class; use Abstract_Class;   package Base_Class is type Base is new Class with null record; overriding function Boo (X : Base) return String; end Base_Class;   package body Base_Class is function Boo (X : Base) return String is begin return "I am Class"; end Boo; end Base_Class; use Base_Class;   E : aliased Base; -- An instance of Base   begin -- Gone run-time declare type Monkey_Patch (Root : access Base) is new Class with record Foo : Integer := 1; end record; overriding function Boo (X : Monkey_Patch) return String; function Boo (X : Monkey_Patch) return String is begin -- Delegation to the base return X.Root.Boo; end Boo; EE : Monkey_Patch (E'Access); -- Extend E begin Put_Line (EE.Boo & " with" & Integer'Image (EE.Foo)); end; end Dynamic;
http://rosettacode.org/wiki/Add_a_variable_to_a_class_instance_at_runtime
Add a variable to a class instance at runtime
Demonstrate how to dynamically add variables to an object (a class instance) at runtime. This is useful when the methods/variables of an instance are based on a data file that isn't available until runtime. Hal Fulton gives an example of creating an OO CSV parser at An Exercise in Metaprogramming with Ruby. This is referred to as "monkeypatching" by Pythonistas and some others.
#Arturo
Arturo
define :myClass [name,surname][]   myInstance: to :myClass ["John" "Doe"] print myInstance   myInstance\age: 35 print myInstance
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.
#COBOL
COBOL
data division. working-storage section. 01 ptr usage pointer. 01 var pic x(64).   procedure division. set ptr to address of var.
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.
#Common_Lisp
Common Lisp
;;; Demonstration of references by swapping two variables using a function rather than a macro ;;; Needs http://paste.lisp.org/display/71952 (defun swap (ref-left ref-right) ;; without with-refs we would have to write this: ;; (psetf (deref ref-left) (deref ref-right) ;; (deref ref-right) (deref ref-left)) (with-refs ((l ref-left) (r ref-right)) (psetf l r r l)))   (defvar *x* 42) (defvar *y* 0)   (swap (ref *x*) (ref *y*))   ;; *y* -> 42 ;; *x* -> 0
http://rosettacode.org/wiki/Address_of_a_variable
Address of a variable
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation | Comparison | Matching Memory Operations Pointers & references | Addresses Task Demonstrate how to get the address of a variable and how to set the address of a variable.
#Component_Pascal
Component Pascal
  MODULE AddressVar; IMPORT SYSTEM,StdLog;   VAR x: INTEGER;   PROCEDURE Do*; BEGIN StdLog.String("ADR(x):> ");StdLog.IntForm(SYSTEM.ADR(x),StdLog.hexadecimal,8,'0',TRUE);StdLog.Ln END Do;   BEGIN x := 10; END AddressVar.  
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.
#ARM_Assembly
ARM Assembly
  /* ARM assembly Raspberry PI or android 32 bits */ /* program AKS.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, 32 .equ NUMBERLOOP, 10   /*********************************/ /* Initialized data */ /*********************************/ .data szMessResult: .asciz " (x-1)^@ = " szMessResult1: .asciz " @ x^@ " szMessResPrime: .asciz "Number @ is prime. \n" szCarriageReturn: .asciz "\n"   /*********************************/ /* UnInitialized data */ /*********************************/ .bss sZoneConv: .skip 24 iTabCoef: .skip 4 * MAXI /*********************************/ /* code section */ /*********************************/ .text .global main main: @ entry of program   mov r4,#1 1: @ loop mov r0,r4 bl computeCoef @ compute coefficient ldr r0,iAdriTabCoef mov r0,r4 bl displayCoef @ display coefficient add r4,r4,#1 cmp r4,#NUMBERLOOP blt 1b   mov r4,#1 2: mov r0,r4 bl isPrime @ is prime ? cmp r0,#1 bne 3f mov r0,r4 ldr r1,iAdrsZoneConv bl conversion10 @ call decimal conversion add r1,r0 mov r5,#0 strb r5,[r1] ldr r0,iAdrszMessResPrime ldr r1,iAdrsZoneConv @ insert value conversion in message bl strInsertAtCharInc bl affichageMess   3: add r4,r4,#1 cmp r4,#MAXI blt 2b   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 iAdrsZoneConv: .int sZoneConv iAdriTabCoef: .int iTabCoef iAdrszMessResPrime: .int szMessResPrime /***************************************************/ /* display coefficients */ /***************************************************/ // r0 contains a number displayCoef: push {r1-r6,lr} @ save registers mov r2,r0 ldr r1,iAdrsZoneConv @ bl conversion10 @ call decimal conversion add r1,r0 mov r5,#0 strb r5,[r1] ldr r0,iAdrszMessResult ldr r1,iAdrsZoneConv @ insert value conversion in message bl strInsertAtCharInc bl affichageMess ldr r3,iAdriTabCoef 1: ldr r0,[r3,r2,lsl #2] ldr r1,iAdrsZoneConv @ bl conversion10S @ call decimal conversion 2: @ removing spaces ldrb r6,[r1] cmp r6,#' ' addeq r1,#1 beq 2b   ldr r0,iAdrszMessResult1 bl strInsertAtCharInc mov r4,r0 mov r0,r2 ldr r1,iAdrsZoneConv @ else display odd message bl conversion10 @ call decimal conversion add r1,r0 mov r5,#0 strb r5,[r1] mov r0,r4 ldr r1,iAdrsZoneConv @ insert value conversion in message bl strInsertAtCharInc bl affichageMess subs r2,r2,#1 bge 1b   ldr r0,iAdrszCarriageReturn bl affichageMess 100: pop {r1-r6,lr} @ restaur registers bx lr @ return iAdrszMessResult: .int szMessResult iAdrszMessResult1: .int szMessResult1 /***************************************************/ /* compute coefficient */ /***************************************************/ // r0 contains a number computeCoef: push {r1-r6,lr} @ save registers ldr r1,iAdriTabCoef @ address coefficient array mov r2,#1 str r2,[r1] @ store 1 to coeff [0] mov r3,#0 @ indice 1 1: add r4,r3,#1 mov r5,#1 str r5,[r1,r4,lsl #2] mov r6,r3 @ indice 2 = indice 1 2: cmp r6,#0 @ zero ? -> end loop ble 3f sub r4,r6,#1 ldr r5,[r1,r4,lsl #2] ldr r4,[r1,r6,lsl #2] sub r5,r5,r4 str r5,[r1,r6,lsl #2] sub r6,r6,#1 b 2b 3: ldr r2,[r1] @ inversion coeff [0] neg r2,r2 str r2,[r1] add r3,r3,#1 cmp r3,r0 blt 1b   100: pop {r1-r6,lr} @ restaur registers bx lr @ return /***************************************************/ /* verify number is prime */ /***************************************************/ // r0 contains a number isPrime: push {r1-r5,lr} @ save registers bl computeCoef ldr r4,iAdriTabCoef @ address coefficient array ldr r2,[r4] add r2,r2,#1 str r2,[r4] ldr r2,[r4,r0,lsl #2] sub r2,r2,#1 str r2,[r4,r0,lsl #2] mov r5,r0 @ number start mov r1,r0 @ divisor 1: ldr r0,[r4,r5,lsl #2] @ load one coeff cmp r0,#0 @ if negative inversion neglt r0,r0 bl division @ because this routine is number positive only cmp r3,#0 @ remainder = zéro ? movne r0,#0 @ if <> no prime bne 100f subs r5,r5,#1 @ next coef bgt 1b mov r0,#1 @ prime   100: pop {r1-r5,lr} @ restaur registers bx lr @ return /***************************************************/ /* ROUTINES INCLUDE */ /***************************************************/ .include "../affichage.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.
#ARM_Assembly
ARM Assembly
  /* ARM assembly Raspberry PI */ /* program additivePrime.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, 500     /*********************************/ /* Initialized data */ /*********************************/ .data szMessResult: .asciz "Prime  : @ \n" szMessCounter: .asciz "Number found : @ \n" szCarriageReturn: .asciz "\n"   /*********************************/ /* UnInitialized data */ /*********************************/ .bss sZoneConv: .skip 24 TablePrime: .skip 4 * MAXI /*********************************/ /* code section */ /*********************************/ .text .global main main: @ entry of program   bl createArrayPrime mov r5,r0 @ prime number   ldr r4,iAdrTablePrime @ address prime table mov r10,#0 @ init counter mov r6,#0 @ indice 1: ldr r2,[r4,r6,lsl #2] @ load prime mov r9,r2 @ save prime mov r7,#0 @ init digit sum mov r1,#10 @ divisor 2: @ begin loop mov r0,r2 @ dividende bl division add r7,r7,r3 @ add digit to digit sum cmp r2,#0 @ quotient null ? bne 2b @ no -> comppute other digit   mov r8,#1 @ indice 4: @ prime search loop cmp r8,r5 @ maxi ? bge 5f @ yes ldr r0,[r4,r8,lsl #2] @ load prime cmp r0,r7 @ prime >= digit sum ? addlt r8,r8,#1 @ no -> increment indice blt 4b @ and loop bne 5f @ > mov r0,r9 @ equal bl displayPrime add r10,r10,#1 @ increment counter 5: add r6,r6,#1 @ increment first indice cmp r6,r5 @ maxi ? blt 1b @ and loop   mov r0,r10 @ number counter ldr r1,iAdrsZoneConv bl conversion10 @ call décimal conversion ldr r0,iAdrszMessCounter ldr r1,iAdrsZoneConv @ insert conversion in message bl strInsertAtCharInc bl affichageMess @ display message   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 iAdrszMessResult: .int szMessResult iAdrszMessCounter: .int szMessCounter iAdrTablePrime: .int TablePrime /******************************************************************/ /* créate prime array */ /******************************************************************/ createArrayPrime: push {r1-r7,lr} @ save registers ldr r4,iAdrTablePrime @ address prime table mov r0,#1 str r0,[r4] @ store 1 in array mov r0,#2 str r0,[r4,#4] @ store 2 in array mov r0,#3 str r0,[r4,#8] @ store 3 in array mov r5,#3 @ prine counter mov r7,#5 @ first number to test 1: mov r6,#1 @ indice 2: mov r0,r7 @ dividende ldr r1,[r4,r6,lsl #2] @ load divisor bl division cmp r3,#0 @ null remainder ? beq 3f @ yes -> end loop cmp r2,r1 @ quotient < divisor strlt r7,[r4,r5,lsl #2] @ dividende is prime store in array addlt r5,r5,#1 @ increment counter blt 3f @ and end loop add r6,r6,#1 @ else increment indice cmp r6,r5 @ maxi ? blt 2b @ no -> loop 3: add r7,#2 @ other odd number cmp r7,#MAXI @ maxi ? blt 1b @ no -> loop mov r0,r5 @ return counter 100: pop {r1-r7,pc} /******************************************************************/ /* Display prime table elements */ /******************************************************************/ /* r0 contains the prime */ displayPrime: push {r1,lr} @ save registers ldr r1,iAdrsZoneConv bl conversion10 @ call décimal conversion ldr r0,iAdrszMessResult ldr r1,iAdrsZoneConv @ insert conversion in message bl strInsertAtCharInc bl affichageMess @ display message 100: pop {r1,pc}   iAdrsZoneConv: .int sZoneConv /***************************************************/ /* ROUTINES INCLUDE */ /***************************************************/ .include "../affichage.inc"    
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
#Kotlin
Kotlin
// version 1.1.51   import Color.*   enum class Color { R, B }   sealed class Tree<A : Comparable<A>> {   fun insert(x: A): Tree<A> { val t = ins(x) return when (t) { is T -> { val (_, a, y, b) = t T(B, a, y, b) }   is E -> E() } }   abstract fun ins(x: A): Tree<A> }   class E<A : Comparable<A>> : Tree<A>() {   override fun ins(x: A): Tree<A> = T(R, E(), x, E())   override fun toString() = "E" }   data class T<A : Comparable<A>>( val cl: Color, val le: Tree<A>, val aa: A, val ri: Tree<A> ) : Tree<A>() {   private fun balance(): Tree<A> { if (cl != B) return this val res = if (le is T && le.le is T && le.cl == R && le.le.cl == R) { val (_, t, z, d) = this val (_, t2, y, c) = t as T val (_, a, x, b) = t2 as T T(R, T(B, a, x, b), y, T(B, c, z, d)) } else if (le is T && le.ri is T && le.cl == R && le.ri.cl == R) { val (_, t, z, d) = this val (_, a, x, t2) = t as T val (_, b, y, c) = t2 as T T(R, T(B, a, x, b), y, T(B, c, z, d)) } else if (ri is T && ri.le is T && ri.cl == R && ri.le.cl == R) { val (_, a, x, t) = this val (_, t2, z, d) = t as T val (_, b, y, c) = t2 as T T(R, T(B, a, x, b), y, T(B, c, z, d)) } else if (ri is T && ri.ri is T && ri.cl == R && ri.ri.cl == R) { val (_, a, x, t) = this val (_, b, y, t2) = t as T val (_, c, z, d) = t2 as T T(R, T(B, a, x, b), y, T(B, c, z, d)) } else this return res }   override fun ins(x: A): Tree<A> = when (x.compareTo(aa)) { -1 -> T(cl, le.ins(x), aa, ri).balance() +1 -> T(cl, le, aa, ri.ins(x)).balance() else -> this }   override fun toString() = "T($cl, $le, $aa, $ri)" }   fun main(args: Array<String>) { var tree: Tree<Int> = E() for (i in 1..16) { tree = tree.insert(i) } println(tree) }
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
#Draco
Draco
proc nonrec kprime(word n, k) bool: word f, p; f := 0; p := 2; while f < k and p*p <= n do while n%p = 0 do n := n/p; f := f+1 od; p := p+1 od; if n>1 then f+1 = k else f = k fi corp   proc nonrec main() void: byte k, i, c; for k from 1 upto 5 do write("k = ", k:1, ":"); i := 2; c := 0; while c < 10 do if kprime(i,k) then write(i:4); c := c+1 fi; i := i+1 od; writeln() od corp
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
#EchoLisp
EchoLisp
  (define (almost-prime? p k) (= k (length (prime-factors p))))   (define (almost-primes k nmax) (take (filter (rcurry almost-prime? k) [2 ..]) nmax))   (define (task (kmax 6) (nmax 10)) (for ((k [1 .. kmax])) (write 'k= k '|) (for-each write (almost-primes k nmax)) (writeln)))  
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
#BQN
BQN
words ← •FLines "unixdict.txt" •Show¨{𝕩/˜(⊢=⌈´)≠¨𝕩} (⊐∧¨)⊸⊔ 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
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
ClearAll[AngleDifference] AngleDifference[b1_, b2_] := Mod[b2 - b1, 360, -180] AngleDifference[20, 45] AngleDifference[-45, 45] AngleDifference[-85, 90] AngleDifference[-95, 90] AngleDifference[-45, 125] AngleDifference[-45, 145] AngleDifference[29.4803, -88.6381] AngleDifference[-78.3251, -159.036] AngleDifference[-70099.74233810938, 29840.67437876723] AngleDifference[-165313.6666297357, 33693.9894517456] AngleDifference[1174.8380510598456, -154146.66490124757] AngleDifference[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
#Phix
Phix
function deranged(string word1, word2) return sum(sq_eq(word1,word2))=0 end function integer fn = open("demo/unixdict.txt","r") sequence words = {}, anagrams = {}, last="", letters object word integer maxlen = 1 while 1 do word = trim(gets(fn)) if atom(word) then exit end if if length(word) then letters = sort(word) words = append(words, {letters, word}) end if end while close(fn) words = sort(words) for i=1 to length(words) do {letters,word} = words[i] if letters=last then anagrams[$] = append(anagrams[$],word) anagrams[$][1] = length(word) else last = letters anagrams = append(anagrams,{0,word}) end if end for anagrams = sort(anagrams) puts(1,"\nLongest deranged anagrams:\n") for i=length(anagrams) to 1 by -1 do last = anagrams[i] if last[1]<maxlen then exit end if for j=2 to length(last) do for k=j+1 to length(last) do if deranged(last[j],last[k]) then puts(1,last[j]&", "&last[k]&"\n") maxlen = last[1] end if end for end for end for
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.
#Lingo
Lingo
on fib (n) if n<0 then return _player.alert("negative arguments not allowed")   -- create instance of unnamed class in memory only (does not pollute namespace) m = new(#script) r = RETURN m.scriptText = "on fib (me,n)"&r&"if n<2 then return n"&r&"return me.fib(n-1)+me.fib(n-2)"&r&"end" aux = m.script.new() m.erase()   return aux.fib(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.
#Java
Java
import java.util.Map; import java.util.function.Function; import java.util.stream.Collectors; import java.util.stream.LongStream;   public class AmicablePairs {   public static void main(String[] args) { int limit = 20_000;   Map<Long, Long> map = LongStream.rangeClosed(1, limit) .parallel() .boxed() .collect(Collectors.toMap(Function.identity(), AmicablePairs::properDivsSum));   LongStream.rangeClosed(1, limit) .forEach(n -> { long m = map.get(n); if (m > n && m <= limit && map.get(m) == n) System.out.printf("%s %s %n", n, m); }); }   public static Long properDivsSum(long n) { return LongStream.rangeClosed(1, (n + 1) / 2).filter(i -> n % i == 0).sum(); } }
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.
#REBOL
REBOL
rebol [ Title: "Basic Animation" URL: http://rosettacode.org/wiki/Basic_Animation ]   message: "Hello World! " how: 1   roll: func [ "Shifts a text string right or left by one character." text [string!] "Text to shift." direction [integer!] "Direction to shift -- right: 1, left: -1." /local h t ][ either direction > 0 [ h: last text t: copy/part text ((length? text) - 1) ][ h: copy skip text 1 t: text/1 ] rejoin [h t] ]   ; This next bit specifies the GUI panel. The window will have a ; gradient backdrop, over which will be composited the text, in a ; monospaced font with a drop-shadow. A timer (the 'rate' bit) is set ; to update 24 times per second. The 'engage' function in the 'feel' ; block listens for events on the text face. Time events update the ; animation and mouse-down change the animation's direction.   view layout [ backdrop effect [gradient 0x1 coal black]   vh1 as-is message ; 'as-is' prevents text trimming. font [name: font-fixed] rate 24 feel [ engage: func [f a e] [ case [ 'time = a [set-face f message: roll message how] ; Animate. 'down = a [how: how * -1] ; Change direction. ] ] ] ]
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.
#M2000_Interpreter
M2000 Interpreter
  Module Pendulum { back() degree=180/pi THETA=Pi/2 SPEED=0 G=9.81 L=0.5 Profiler lasttimecount=0 cc=40 ' 40 ms every draw accold=0 Every cc { ACCEL=G*SIN(THETA*degree)/L/50 SPEED+=ACCEL/cc THETA+=SPEED Pendulum(THETA) if KeyPress(32) Then Exit }   Sub back() If not IsWine then Smooth On Cls 7,0 Pen 0 Move 0, scale.y/4 Draw scale.x,0 Step -scale.x/2 circle fill #AAAAAA, scale.x/50 Hold ' hold this as background End Sub   Sub Pendulum(x) x+=pi/2 Release ' place stored background to screen Width scale.x/2000 { Draw Angle x, scale.y/2.5 Width 1 { Circle Fill 14, scale.x/25 } Step Angle x, -scale.y/2.5 } Print @(1,1), lasttimecount if sgn(accold)<>sgn(ACCEL) then lasttimecount=timecount: Profiler accold=ACCEL Refresh 1000 End Sub } Pendulum  
http://rosettacode.org/wiki/Amb
Amb
Define and give an example of the Amb operator. The Amb operator (short for "ambiguous") expresses nondeterminism. This doesn't refer to randomness (as in "nondeterministic universe") but is closely related to the term as it is used in automata theory ("non-deterministic finite automaton"). The Amb operator takes a variable number of expressions (or values if that's simpler in the language) and yields a correct one which will satisfy a constraint in some future computation, thereby avoiding failure. Problems whose solution the Amb operator naturally expresses can be approached with other tools, such as explicit nested iterations over data sets, or with pattern matching. By contrast, the Amb operator appears integrated into the language. Invocations of Amb are not wrapped in any visible loops or other search patterns; they appear to be independent. Essentially Amb(x, y, z) splits the computation into three possible futures: a future in which the value x is yielded, a future in which the value y is yielded and a future in which the value z is yielded. The future which leads to a successful subsequent computation is chosen. The other "parallel universes" somehow go away. Amb called with no arguments fails. For simplicity, one of the domain values usable with Amb may denote failure, if that is convenient. For instance, it is convenient if a Boolean false denotes failure, so that Amb(false) fails, and thus constraints can be expressed using Boolean expressions like Amb(x * y == 8) which unless x and y add to four. A pseudo-code program which satisfies this constraint might look like: let x = Amb(1, 2, 3) let y = Amb(7, 6, 4, 5) Amb(x * y = 8) print x, y The output is 2 4 because Amb(1, 2, 3) correctly chooses the future in which x has value 2, Amb(7, 6, 4, 5) chooses 4 and consequently Amb(x * y = 8) produces a success. Alternatively, failure could be represented using strictly Amb(): unless x * y = 8 do Amb() Or else Amb could take the form of two operators or functions: one for producing values and one for enforcing constraints: let x = Ambsel(1, 2, 3) let y = Ambsel(4, 5, 6) Ambassert(x * y = 8) print x, y where Ambassert behaves like Amb() if the Boolean expression is false, otherwise it allows the future computation to take place, without yielding any value. The task is to somehow implement Amb, and demonstrate it with a program which chooses one word from each of the following four sets of character strings to generate a four-word sentence: "the" "that" "a" "frog" "elephant" "thing" "walked" "treaded" "grows" "slowly" "quickly" The constraint to be satisfied is that the last character of each word (other than the last) is the same as the first character of its successor. The only successful sentence is "that thing grows slowly"; other combinations do not satisfy the constraint and thus fail. The goal of this task isn't to simply process the four lists of words with explicit, deterministic program flow such as nested iteration, to trivially demonstrate the correct output. The goal is to implement the Amb operator, or a facsimile thereof that is possible within the language limitations.
#D
D
import std.stdio, std.array;   /** This amb function takes a comparison function and the possibilities that need to be checked.*/ //string[] amb(in bool function(in string, in string) pure comp, const(string)[] amb(in bool function(in string, in string) pure comp, in string[][] options, in string prev = null) pure { if (options.empty) return null;   foreach (immutable opt; options.front) { // If this is the base call, prev is null and we need to // continue. if (!prev.empty && !comp(prev, opt)) continue;   // Take care of the case where we have no options left. if (options.length == 1) return [opt];   // Traverse into the tree. const res = amb(comp, options[1 .. $], opt);   // If it was a failure, try the next one. if (!res.empty) return opt ~ res; // We have a match! }   return null; // No matches. }   void main() { immutable sets = [["the", "that", "a"], ["frog", "elephant", "thing"], ["walked", "treaded", "grows"], ["slowly", "quickly"]];   // Pass in the comparator and the available sets. // (The comparator is not nothrow because of UTF.) const result = amb((s, t) => s.back == t.front, sets);   if (result.empty) writeln("No matches found!"); else writefln("%-(%s %)", result); }
http://rosettacode.org/wiki/Active_Directory/Connect
Active Directory/Connect
The task is to establish a connection to an Active Directory or Lightweight Directory Access Protocol server.
#AutoIt
AutoIt
#include <AD.au3> _AD_Open()
http://rosettacode.org/wiki/Active_Directory/Connect
Active Directory/Connect
The task is to establish a connection to an Active Directory or Lightweight Directory Access Protocol server.
#C
C
#include <ldap.h> ... char *name, *password; ... LDAP *ld = ldap_init("ldap.somewhere.com", 389); ldap_simple_bind_s(ld, name, password); ... after done with it... ldap_unbind(ld);
http://rosettacode.org/wiki/Active_Directory/Connect
Active Directory/Connect
The task is to establish a connection to an Active Directory or Lightweight Directory Access Protocol server.
#C.23
C#
  // Requires adding a reference to System.DirectoryServices var objDE = new System.DirectoryServices.DirectoryEntry("LDAP://DC=onecity,DC=corp,DC=fabrikam,DC=com");  
http://rosettacode.org/wiki/Active_Directory/Connect
Active Directory/Connect
The task is to establish a connection to an Active Directory or Lightweight Directory Access Protocol server.
#ColdFusion
ColdFusion
  <cfldap server = "#someip#" action="query" start="somestart#" username = "#someusername#" password = "#somepassowrd#" name = "results" scope="subtree" attributes = "#attributeslist#" >  
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
#C
C
  #include<stdlib.h> #include<string.h> #include<stdio.h>   unsigned long long bruteForceProperDivisorSum(unsigned long long n){ unsigned long long i,sum = 0;   for(i=1;i<(n+1)/2;i++) if(n%i==0 && n!=i) sum += i;   return sum; }   void printSeries(unsigned long long* arr,int size,char* type){ int i;   printf("\nInteger : %llu, Type : %s, Series : ",arr[0],type);   for(i=0;i<size-1;i++) printf("%llu, ",arr[i]); printf("%llu",arr[i]); }   void aliquotClassifier(unsigned long long n){ unsigned long long arr[16]; int i,j;   arr[0] = n;   for(i=1;i<16;i++){ arr[i] = bruteForceProperDivisorSum(arr[i-1]);   if(arr[i]==0||arr[i]==n||(arr[i]==arr[i-1] && arr[i]!=n)){ printSeries(arr,i+1,(arr[i]==0)?"Terminating":(arr[i]==n && i==1)?"Perfect":(arr[i]==n && i==2)?"Amicable":(arr[i]==arr[i-1] && arr[i]!=n)?"Aspiring":"Sociable"); return; }   for(j=1;j<i;j++){ if(arr[j]==arr[i]){ printSeries(arr,i+1,"Cyclic"); return; } } }   printSeries(arr,i+1,"Non-Terminating"); }   void processFile(char* fileName){ FILE* fp = fopen(fileName,"r"); char str[21];   while(fgets(str,21,fp)!=NULL) aliquotClassifier(strtoull(str,(char**)NULL,10));   fclose(fp); }   int main(int argC,char* argV[]) { if(argC!=2) printf("Usage : %s <positive integer>",argV[0]); else{ if(strchr(argV[1],'.')!=NULL) processFile(argV[1]); else aliquotClassifier(strtoull(argV[1],(char**)NULL,10)); } return 0; }  
http://rosettacode.org/wiki/Active_Directory/Search_for_a_user
Active Directory/Search for a user
Make sure you Connect to Active Directory
#Julia
Julia
using LDAPClient   function searchLDAPusers(searchstring, uname, pword, host=["example", "com"]) conn = LDAPClient.LDAPConnection("ldap://ldap.server.net") LDAPClient.simple_bind(conn, uname, pword)   search_string = "CN=Users,DC=$(host[1]),DC=$(host[2])" scope = LDAPClient.LDAP_SCOPE_ONELEVEL chain = LDAPClient.search(conn, search_string, scope, filter="(&(objectClass=person)(&(uid=$(searchstring))))")   for entry in LDAPClient.each_entry(chain) println("Search for $searchstring found user $(entry["name"]) with attributes:") for attr in LDAPClient.each_attribute(entry) println(" ", attr) end end   LDAPClient.unbind(conn) end   searchLDAPusers("Mario", "my-username", "my-password")  
http://rosettacode.org/wiki/Active_Directory/Search_for_a_user
Active Directory/Search for a user
Make sure you Connect to Active Directory
#NetRexx
NetRexx
/* NetRexx */ options replace format comments java crossref symbols binary   import org.apache.directory.ldap.client.api.LdapConnection import org.apache.directory.ldap.client.api.LdapNetworkConnection import org.apache.directory.shared.ldap.model.cursor.EntryCursor import org.apache.directory.shared.ldap.model.entry.Entry import org.apache.directory.shared.ldap.model.exception.LdapException import org.apache.directory.shared.ldap.model.message.SearchScope import org.slf4j.Logger import org.slf4j.LoggerFactory   class RDirectorySearchLDAP public   properties constant log_ = LoggerFactory.getLogger(RDirectorySearchLDAP.class)   properties private constant ldapHostName = String 'localhost' ldapPort = int 11389 ldapDnStr = String 'uid=admin,ou=system' ldapCreds = String '********'   isTrue = boolean (1 == 1) isFalse = boolean (1 \== 1)   properties private static connection = LdapConnection   method main(args = String[]) public static   connected = isFalse do connected = setUp() if connected then do search('*mil*') end   finally if connected then do tearDown() end end   return   method search(uid = String '*') static returns boolean   state = isTrue cursor = EntryCursor baseDn = 'ou=users,o=mojo' filter = '(&(objectClass=person)(&(uid=' || uid || ')))' scope = SearchScope.SUBTREE attributes = String[] [String 'dn', 'cn', 'sn', 'uid'] do if log_.isTraceEnabled() then log_.trace('LDAP search') if log_.isInfoEnabled() then do log_.info('Begin search') log_.info(' search base distinguished name:' baseDn) log_.info(' search filter:' filter) log_.info(' search attributes:' Arrays.asList(attributes)) end cursor = connection.search(baseDn, filter, scope, attributes) loop ksearch = 1 while cursor.next() ev = cursor.get() if log_.isInfoEnabled() then log_.info('Search cursor entry count:' ksearch) if log_.isInfoEnabled() then log_.info(ev.toString()) end ksearch catch lex = LdapException state = isFalse log_.error('LDAP Error in cursor loop: Iteration' ksearch, Throwable lex) catch ex = Exception state = isFalse log_.error('I/O Error in cursor loop: Iteration' ksearch, Throwable ex) end   return state   method setUp() static returns boolean   state = isFalse do if log_.isInfoEnabled() then log_.info('LDAP Connection to' ldapHostName 'on port' ldapPort) connection = LdapNetworkConnection(ldapHostName, ldapPort)   if log_.isTraceEnabled() then log_.trace('LDAP bind') connection.bind(ldapDnStr, ldapCreds)   state = isTrue catch lex = LdapException state = isFalse log_.error('LDAP Error', Throwable lex) catch iox = IOException state = isFalse log_.error('I/O Error', Throwable iox) end   return state   method tearDown() static returns boolean   state = isFalse do if log_.isTraceEnabled() then log_.trace('LDAP unbind') connection.unBind() state = isTrue catch lex = LdapException state = isFalse log_.error('LDAP Error', Throwable lex) finally do connection.close() catch iox = IOException state = isFalse log_.error('I/O Error on connection.close()', Throwable iox) end end   return state  
http://rosettacode.org/wiki/Add_a_variable_to_a_class_instance_at_runtime
Add a variable to a class instance at runtime
Demonstrate how to dynamically add variables to an object (a class instance) at runtime. This is useful when the methods/variables of an instance are based on a data file that isn't available until runtime. Hal Fulton gives an example of creating an OO CSV parser at An Exercise in Metaprogramming with Ruby. This is referred to as "monkeypatching" by Pythonistas and some others.
#AutoHotkey
AutoHotkey
e := {} e.foo := 1