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/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.
#Scratch
Scratch
'Animation, by rbytes and Dutchman word$="Hello World! " 'use button window with text SET BUTTONS CUSTOM SET BUTTONS FONT SIZE 40 DRAW COLOR 0,0,0 DO 'the button is redrawn each loop BUTTON "anim" TEXT word$ AT 130,100 PAUSE .1 'touching the button reverses the scrolling IF BUTTON_PRESSED("anim") THEN flag=1-flag IF flag THEN 'shift right word$=RIGHT$(word$,1)&LEFT$(word$,LEN(word$)-1) ELSE 'shift left word$=RIGHT$(word$,LEN(word$)-1)&LEFT$(word$,1) ENDIF UNTIL 0
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.
#smart_BASIC
smart BASIC
'Animation, by rbytes and Dutchman word$="Hello World! " 'use button window with text SET BUTTONS CUSTOM SET BUTTONS FONT SIZE 40 DRAW COLOR 0,0,0 DO 'the button is redrawn each loop BUTTON "anim" TEXT word$ AT 130,100 PAUSE .1 'touching the button reverses the scrolling IF BUTTON_PRESSED("anim") THEN flag=1-flag IF flag THEN 'shift right word$=RIGHT$(word$,1)&LEFT$(word$,LEN(word$)-1) ELSE 'shift left word$=RIGHT$(word$,LEN(word$)-1)&LEFT$(word$,1) ENDIF UNTIL 0
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.
#ooRexx
ooRexx
  pendulum = .pendulum~new(10, 30)   before = .datetime~new do 100 -- somewhat arbitrary loop count call syssleep .2 now = .datetime~new pendulum~update(now - before) before = now say " X:" pendulum~x " Y:" pendulum~y end   ::class pendulum ::method init expose length theta x y velocity use arg length, theta x = rxcalcsin(theta) * length y = rxcalccos(theta) * length velocity = 0   ::attribute x GET ::attribute y GET   ::constant g -9.81 -- acceleration due to gravity   ::method update expose length theta x y velocity use arg duration acceleration = self~g / length * rxcalcsin(theta) durationSeconds = duration~microseconds / 1000000 x = rxcalcsin(theta, length) y = rxcalccos(theta, length) velocity = velocity + acceleration * durationSeconds theta = theta + velocity * durationSeconds   ::requires rxmath library    
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.
#Elena
Elena
import system'routines; import extensions; import extensions'routines;   joinable(former,later) = (former[former.Length - 1] == later[0]);   dispatcher = new { eval(object a, Func2 f) { ^ f(a[0],a[1]) }   eval(object a, Func3 f) { ^ f(a[0], a[1],a[2]) }   eval(object a, Func4 f) { ^ f(a[0],a[1],a[2],a[3]) }   eval(object a, Func5 f) { ^ f(a[0],a[1],a[2],a[3],a[4]) } };   class AmbValueCollection { object theCombinator;   constructor new(params object[] args) { theCombinator := SequentialEnumerator.new(params args) }   seek(cond) { theCombinator.reset();   theCombinator.seekEach:(v => dispatcher.eval(v,cond)) }   do(f) { var result := theCombinator.get(); if (nil != result) { dispatcher.eval(result,f) } else { InvalidArgumentException.raise() } } }   singleton ambOperator { for(params object[] args) = AmbValueCollection.new(params args); }   public program() { try { ambOperator .for( new object[]{"the","that","a"}, new object[]{"frog", "elephant", "thing"}, new object[]{"walked", "treaded", "grows"}, new object[]{"slowly", "quickly"}) .seek:(a,b,c,d => joinable(a,b) && joinable(b,c) && joinable(c,d) ) .do:(a,b,c,d) { console.printLine(a," ",b," ",c," ",d) } } catch(Exception e) { console.printLine:"AMB is angry" };   console.readChar() }
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.
#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.exception.LdapException import org.slf4j.Logger import org.slf4j.LoggerFactory   class RDirectoryLDAP public   properties constant log_ = LoggerFactory.getLogger(RDirectoryLDAP.class)   properties private static connection = LdapConnection null   method main(args = String[]) public static ldapHostName = String "localhost" ldapPort = int 10389   if log_.isInfoEnabled() then log_.info("LDAP Connection to" ldapHostName "on port" ldapPort) connection = LdapNetworkConnection(ldapHostName, ldapPort)   do if log_.isTraceEnabled() then log_.trace("LDAP bind") connection.bind()   if log_.isTraceEnabled() then log_.trace("LDAP unbind") connection.unBind() catch lex = LdapException log_.error("LDAP Error", Throwable lex) catch iox = IOException log_.error("I/O Error", Throwable iox) finally do if connection \= null then connection.close() catch iox = IOException log_.error("I/O Error on connection.close()", Throwable iox) end end   return  
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.
#Perl
Perl
  use Net::LDAP;   my $ldap = Net::LDAP->new('ldap://ldap.example.com') or die $@; my $mesg = $ldap->bind( $bind_dn, password => $bind_pass );  
http://rosettacode.org/wiki/Align_columns
Align columns
Given a text file of many lines, where fields within a line are delineated by a single 'dollar' character, write a program that aligns each column of fields by ensuring that words in each column are separated by at least one space. Further, allow for each word in a column to be either left justified, right justified, or center justified within its column. Use the following text to test your programs: Given$a$text$file$of$many$lines,$where$fields$within$a$line$ are$delineated$by$a$single$'dollar'$character,$write$a$program that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$ column$are$separated$by$at$least$one$space. Further,$allow$for$each$word$in$a$column$to$be$either$left$ justified,$right$justified,$or$center$justified$within$its$column. Note that:   The example input texts lines may, or may not, have trailing dollar characters.   All columns should share the same alignment.   Consecutive space characters produced adjacent to the end of lines are insignificant for the purposes of the task.   Output text will be viewed in a mono-spaced font on a plain text editor or basic terminal.   The minimum space between columns should be computed from the text and not hard-coded.   It is not a requirement to add separating characters between or around columns. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#360_Assembly
360 Assembly
* Align columns 12/04/2019 ALICOL CSECT USING ALICOL,R13 base register B 72(R15) skip savearea DC 17F'0' savearea SAVE (14,12) save previous context ST R13,4(R15) link backward ST R15,8(R13) link forward LR R13,R15 set addressability LA R8,1 i=1 DO WHILE=(C,R8,LE,=A(NI)) do r=1 to hbound(t) LA R7,1 j=1 LA R6,L'T i=length(t) DO WHILE=(C,R6,GE,=A(1)) do i=length(t) to 1 by -1 LR R1,R8 r MH R1,=AL2(L'T) ~ LA R4,T-L'T(R1) t(r) BCTR R4,0 -1 AR R4,R6 +i MVC CI,0(R4) ci=substr(t(r),i,1) CLI CI,C' ' if ci=' ' BE ITERI1 then iterate i CLI CI,C'$' if ci='$' BE ITERI1 then iterate i LR R7,R6 j=i B LEAVEI1 leave i ITERI1 BCTR R6,0 i-- ENDDO , enddo i LEAVEI1 LR R1,R8 r MH R1,=AL2(L'T) ~ LA R4,T-L'T(R1) @t(r) LA R2,WT @wt LR R5,R7 j ICM R5,B'1000',=C' ' padding LA R3,L'T length(wt) MVCL R2,R4 wt=substr(t(r),1,j) LA R0,1 1 ST R0,I0 i0=1 SR R9,R9 c=0 LA R6,1 i=1 DO WHILE=(CR,R6,LE,R7) do i=1 to j LA R4,WT-1 @wt AR R4,R6 i MVC CI(1),0(R4) ci=substr(wt,i,1) IF CLI,CI,EQ,C'$' THEN if ci='$' then BAL R14,SEQ call seq LR R2,R6 i LA R2,1(R2) +1 ST R2,I0 i0=i+1 ENDIF , endif LA R6,1(R6) i++ ENDDO , enddo i BAL R14,SEQ call seq IF C,R9,GT,COLS THEN if c>cols then ST R9,COLS cols=c ENDIF , endif LA R8,1(R8) r++ ENDDO , enddo r LR R2,R8 r BCTR R2,0 -1 ST R2,ROWS rows=r-1 LA R7,1 j=1 DO WHILE=(C,R7,LE,=A(3)) do j=1 to 3 XPRNT =C'--',2 print LA R8,1 r=1 DO WHILE=(C,R8,LE,ROWS) do r=1 to rows MVC PG,=CL120' ' pg=' ' LA R0,1 1 ST R0,IB ib=1 LA R9,1 c=1 DO WHILE=(C,R9,LE,COLS) do c=1 to cols LR R1,R8 r BCTR R1,0 -1 MH R1,=AL2(NJ) ~ AR R1,R9 c MH R1,=AL2(L'WOR) ~ LA R4,WOR-L'WOR(R1) @wor(r,c) MVC W,0(R4) w=wor(r,c) LA R6,L'W i=length(w) DO WHILE=(C,R6,GE,=A(1)) do i=length(w) to 1 by -1 LA R4,W-1 @w AR R4,R6 i MVC CI,0(R4) ci=substr(w,i,1) CLI CI,C' ' if ci^=' ' BNE LEAVEI2 then goto leavei2; BCTR R6,0 i-- ENDDO , enddo i LEAVEI2 EQU * ~ IF LTR,R6,Z,R6 THEN if i=0 then LA R10,1 l=1 ELSE , else LR R10,R6 l=i ENDIF , endif IF C,R7,EQ,=F'1' THEN if j=1 then L R11,IB ibx=ib ENDIF , endif IF C,R7,EQ,=F'2' THEN if j=2 then LR R1,R9 c SLA R1,2 ~ L R11,WID-L'WID(R1) wid(c) A R11,IB +ib SR R11,R10 ibx=ib+wid(c)-l ENDIF , endif IF C,R7,EQ,=F'3' THEN if j=3 then LR R1,R9 c SLA R1,2 ~ L R11,WID-L'WID(R1) wid(c) SR R11,R10 -l SRA R11,1 /2 A R11,IB ibx=ib+(wid(c)-l)/2 ENDIF , endif LA R2,PG-1 @pg AR R2,R11 +ibx LR R3,R10 l LA R4,W @w LR R5,R10 l MVCL R2,R4 substr(pg,ibx,l)=substr(w,1,l) LR R1,R9 c SLA R1,2 ~ L R2,WID-L'WID(R1) wid(c) A R2,IB +ib LA R2,1(R2) +1 ST R2,IB ib=ib+wid(c)+1 LA R9,1(R9) c++ ENDDO , enddo c XPRNT PG,L'PG print LA R8,1(R8) r++ ENDDO , enddo r LA R7,1(R7) j++ ENDDO , enddo j L R13,4(0,R13) restore previous savearea pointer RETURN (14,12),RC=0 restore registers from calling sav SEQ EQU * --begin seq LA R9,1(R9) c=c+1 LR R10,R6 i S R10,I0 l=i-i0 LA R4,WT-1 @wt A R4,I0 +i0 LR R5,R10 l ICM R5,B'1000',=C' ' padding LR R1,R8 r BCTR R1,0 -1 MH R1,=AL2(NJ) ~ AR R1,R9 +c MH R1,=AL2(L'WOR) ~ LA R2,WOR-L'WOR(R1) @wor(r,c) LA R3,L'WOR length(wor) MVCL R2,R4 wor(r,c)=substr(wt,i0,l) LR R1,R9 c SLA R1,2 ~ L R2,WID-L'WID(R1) wid(c) IF CR,R2,LT,R10 THEN if l>wid(c) then LR R1,R9 c SLA R1,2 ~ ST R10,WID-L'WID(R1) wid(c)=l ENDIF , endif BR R14 --end seq NI EQU 6 ni NJ EQU 12 nj T DC CL68'Given$a$text$file$of$many$lines,$where$fields$within$a$line$' DC CL68'are$delineated$by$a$single$''dollar''$character,$write$a$progX ramm' DC CL68'that$aligns$each$column$of$fields$by$ensuring$that$words$in$eX ach$' DC CL68'column$are$separated$by$at$least$one$space.' DC CL68'Further,$allow$for$each$word$in$a$column$to$be$either$left$' DC CL68'justified,$right$justified,$or$center$justified$within$its$coX lumn.' WOR DC (NI*NJ)CL10' ' wor(ni,nj) char(10) WID DC 16F'0' wid(16) COLS DC F'0' ROWS DC F'0' WT DS CL(L'T) W DS CL(L'WOR) CI DS CL1 I0 DS F IB DS F PG DS CL120 REGEQU END ALICOL
http://rosettacode.org/wiki/Active_object
Active object
In object-oriented programming an object is active when its state depends on clock. Usually an active object encapsulates a task that updates the object's state. To the outer world the object looks like a normal object with methods that can be called from outside. Implementation of such methods must have a certain synchronization mechanism with the encapsulated task in order to prevent object's state corruption. A typical instance of an active object is an animation widget. The widget state changes with the time, while as an object it has all properties of a normal widget. The task Implement an active integrator object. The object has an input and output. The input can be set using the method Input. The input is a function of time. The output can be queried using the method Output. The object integrates its input over the time and the result becomes the object's output. So if the input is K(t) and the output is S, the object state S is changed to S + (K(t1) + K(t0)) * (t1 - t0) / 2, i.e. it integrates K using the trapeze method. Initially K is constant 0 and S is 0. In order to test the object: set its input to sin (2π f t), where the frequency f=0.5Hz. The phase is irrelevant. wait 2s set the input to constant 0 wait 0.5s Verify that now the object's output is approximately 0 (the sine has the period of 2s). The accuracy of the result will depend on the OS scheduler time slicing and the accuracy of the clock.
#BBC_BASIC
BBC BASIC
INSTALL @lib$+"CLASSLIB" INSTALL @lib$+"TIMERLIB" INSTALL @lib$+"NOWAIT"   REM Integrator class: DIM integ{f$, t#, v#, tid%, @init, @@exit, input, output, tick} PROC_class(integ{})   REM Methods: DEF integ.@init integ.f$ = "0" : integ.tid% = FN_ontimer(10, PROC(integ.tick), 1) : ENDPROC DEF integ.@@exit PROC_killtimer(integ.tid%) : ENDPROC DEF integ.input (f$) integ.f$ = f$ : ENDPROC DEF integ.output = integ.v# DEF integ.tick integ.t# += 0.01 : integ.v# += EVAL(integ.f$) : ENDPROC   REM Test: PROC_new(myinteg{}, integ{}) PROC(myinteg.input) ("SIN(2*PI*0.5*myinteg.t#)") PROCwait(200) PROC(myinteg.input) ("0") PROCwait(50) PRINT "Final value = " FN(myinteg.output) PROC_discard(myinteg{})
http://rosettacode.org/wiki/Active_object
Active object
In object-oriented programming an object is active when its state depends on clock. Usually an active object encapsulates a task that updates the object's state. To the outer world the object looks like a normal object with methods that can be called from outside. Implementation of such methods must have a certain synchronization mechanism with the encapsulated task in order to prevent object's state corruption. A typical instance of an active object is an animation widget. The widget state changes with the time, while as an object it has all properties of a normal widget. The task Implement an active integrator object. The object has an input and output. The input can be set using the method Input. The input is a function of time. The output can be queried using the method Output. The object integrates its input over the time and the result becomes the object's output. So if the input is K(t) and the output is S, the object state S is changed to S + (K(t1) + K(t0)) * (t1 - t0) / 2, i.e. it integrates K using the trapeze method. Initially K is constant 0 and S is 0. In order to test the object: set its input to sin (2π f t), where the frequency f=0.5Hz. The phase is irrelevant. wait 2s set the input to constant 0 wait 0.5s Verify that now the object's output is approximately 0 (the sine has the period of 2s). The accuracy of the result will depend on the OS scheduler time slicing and the accuracy of the clock.
#C
C
#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <math.h> #include <sys/time.h> #include <pthread.h>   /* no need to lock the object: at worst the readout would be 1 tick off, which is no worse than integrator's inate inaccuracy */ typedef struct { double (*func)(double); struct timeval start; double v, last_v, last_t; pthread_t id; } integ_t, *integ;   void update(integ x) { struct timeval tv; double t, v, (*f)(double);   f = x->func; gettimeofday(&tv, 0); t = ((tv.tv_sec - x->start.tv_sec) * 1000000 + tv.tv_usec - x->start.tv_usec) * 1e-6; v = f ? f(t) : 0; x->v += (x->last_v + v) * (t - x->last_t) / 2; x->last_t = t; }   void* tick(void *a) { integ x = a; while (1) { usleep(100000); /* update every .1 sec */ update(x); } }   void set_input(integ x, double (*func)(double)) { update(x); x->func = func; x->last_t = 0; x->last_v = func ? func(0) : 0; }   integ new_integ(double (*func)(double)) { integ x = malloc(sizeof(integ_t)); x->v = x->last_v = 0; x->func = 0; gettimeofday(&x->start, 0); set_input(x, func); pthread_create(&x->id, 0, tick, x); return x; }   double sine(double t) { return sin(4 * atan2(1, 1) * t); }   int main() { integ x = new_integ(sine); sleep(2); set_input(x, 0); usleep(500000); printf("%g\n", x->v);   return 0; }
http://rosettacode.org/wiki/Achilles_numbers
Achilles numbers
This page uses content from Wikipedia. The original article was at Achilles number. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) An Achilles number is a number that is powerful but imperfect. Named after Achilles, a hero of the Trojan war, who was also powerful but imperfect. A positive integer n is a powerful number if, for every prime factor p of n, p2 is also a divisor. In other words, every prime factor appears at least squared in the factorization. All Achilles numbers are powerful. However, not all powerful numbers are Achilles numbers: only those that cannot be represented as mk, where m and k are positive integers greater than 1. A strong Achilles number is an Achilles number whose Euler totient (𝜑) is also an Achilles number. E.G. 108 is a powerful number. Its prime factorization is 22 × 33, and thus its prime factors are 2 and 3. Both 22 = 4 and 32 = 9 are divisors of 108. However, 108 cannot be represented as mk, where m and k are positive integers greater than 1, so 108 is an Achilles number. 360 is not an Achilles number because it is not powerful. One of its prime factors is 5 but 360 is not divisible by 52 = 25. Finally, 784 is not an Achilles number. It is a powerful number, because not only are 2 and 7 its only prime factors, but also 22 = 4 and 72 = 49 are divisors of it. Nonetheless, it is a perfect power; its square root is an even integer, so it is not an Achilles number. 500 = 22 × 53 is a strong Achilles number as its Euler totient, 𝜑(500), is 200 = 23 × 52 which is also an Achilles number. Task Find and show the first 50 Achilles numbers. Find and show at least the first 20 strong Achilles numbers. For at least 2 through 5, show the count of Achilles numbers with that many digits. See also Wikipedia: Achilles number OEIS:A052486 - Achilles numbers - powerful but imperfect numbers OEIS:A194085 - Strong Achilles numbers: Achilles numbers m such that phi(m) is also an Achilles number Related task: Powerful numbers Related task: Totient function
#ALGOL_68
ALGOL 68
BEGIN # find Achilles Numbers: numbers whose prime factors p appear at least # # twice (i.e. if p is a prime factor, so is p^2) and cannot be # # expressed as m^k for any integer m, k > 1 # # also find strong Achilles Numbers: Achilles Numbers where the Euler's # # totient of the number is also Achilles # # returns the number of integers k where 1 <= k <= n that are mutually # # prime to n # PROC totient = ( INT n )INT: # algorithm from the second Go sample # IF n < 3 THEN 1 # in the Totient Function task # ELIF n = 3 THEN 2 ELSE INT result := n; INT v := n; INT i := 2; WHILE i * i <= v DO IF v MOD i = 0 THEN WHILE v MOD i = 0 DO v OVERAB i OD; result -:= result OVER i FI; IF i = 2 THEN i := 1 FI; i +:= 2 OD; IF v > 1 THEN result -:= result OVER v FI; result FI # totient # ; # find the numbers # INT max number = 1 000 000; # max number we will consider # PR read "primes.incl.a68" PR # include prime utilities # []BOOL prime = PRIMESIEVE max number; # construct a sieve of primes # # table of numbers, will be set to TRUE for the Achilles Numbers # [ 1 : max number ]BOOL achiles; FOR a TO UPB achiles DO achiles[ a ] := TRUE OD; # remove the numbers that don't have squared primes as factors # achiles[ 1 ] := FALSE; FOR a TO UPB achiles DO IF prime[ a ] THEN # have a prime, remove it and every multiple of it that isn't a # # multiple of a squared # INT a count := 0; FOR j FROM a BY a TO UPB achiles DO a count +:= 1; IF a count = a THEN # have a multiple of i^2, keep the number # a count := 0 ELSE # not a multiple of i^2, remove the number # achiles[ j ] := FALSE FI OD FI OD; # achiles now has TRUE for the powerful numbers, remove all m^k (m,k > 1) # FOR m FROM 2 TO UPB achiles DO INT mk := m; INT max mk = UPB achiles OVER m; # avoid overflow if INT is 32 bit # WHILE mk <= max mk DO mk *:= m; achiles[ mk ] := FALSE OD OD; # achiles now has TRUE for imperfect powerful numbers # # show the first 50 Achilles Numbers # BEGIN print( ( "First 50 Achilles Numbers:", newline ) ); INT a count := 0; FOR a WHILE a count < 50 DO IF achiles[ a ] THEN a count +:= 1; print( ( " ", whole( a, -6 ) ) ); IF a count MOD 10 = 0 THEN print( ( newline ) ) FI FI OD END; # show the first 50 Strong Achilles numbers # BEGIN print( ( "First 20 Strong Achilles Numbers:", newline ) ); INT s count := 0; FOR s WHILE s count < 20 DO IF achiles[ s ] THEN IF achiles[ totient( s ) ] THEN s count +:= 1; print( ( " ", whole( s, -6 ) ) ); IF s count MOD 10 = 0 THEN print( ( newline ) ) FI FI FI OD END; # count the number of Achilles Numbers by their digit counts # BEGIN INT a count := 0; INT power of 10 := 100; INT digit count := 2; FOR a TO UPB achiles DO IF achiles[ a ] THEN # have an Achilles Number # a count +:= 1 FI; IF a = power of 10 THEN # have reached a power of 10 # print( ( "Achilles Numbers with ", whole( digit count, 0 ) , " digits: ", whole( a count, -6 ) , newline ) ); digit count +:= 1; power of 10 *:= 10; a count := 0 FI OD END END
http://rosettacode.org/wiki/Aliquot_sequence_classifications
Aliquot sequence classifications
An aliquot sequence of a positive integer K is defined recursively as the first member being K and subsequent members being the sum of the Proper divisors of the previous term. If the terms eventually reach 0 then the series for K is said to terminate. There are several classifications for non termination: If the second term is K then all future terms are also K and so the sequence repeats from the first term with period 1 and K is called perfect. If the third term would be repeating K then the sequence repeats with period 2 and K is called amicable. If the Nth term would be repeating K for the first time, with N > 3 then the sequence repeats with period N - 1 and K is called sociable. Perfect, amicable and sociable numbers eventually repeat the original number K; there are other repetitions... Some K have a sequence that eventually forms a periodic repetition of period 1 but of a number other than K, for example 95 which forms the sequence 95, 25, 6, 6, 6, ... such K are called aspiring. K that have a sequence that eventually forms a periodic repetition of period >= 2 but of a number other than K, for example 562 which forms the sequence 562, 284, 220, 284, 220, ... such K are called cyclic. And finally: Some K form aliquot sequences that are not known to be either terminating or periodic; these K are to be called non-terminating. For the purposes of this task, K is to be classed as non-terminating if it has not been otherwise classed after generating 16 terms or if any term of the sequence is greater than 2**47 = 140,737,488,355,328. Task Create routine(s) to generate the aliquot sequence of a positive integer enough to classify it according to the classifications given above. Use it to display the classification and sequences of the numbers one to ten inclusive. Use it to show the classification and sequences of the following integers, in order: 11, 12, 28, 496, 220, 1184, 12496, 1264460, 790, 909, 562, 1064, 1488, and optionally 15355717786080. Show all output on this page. Related tasks   Abundant, deficient and perfect number classifications. (Classifications from only the first two members of the whole sequence).   Proper divisors   Amicable pairs
#D
D
import std.stdio, std.range, std.algorithm, std.typecons, std.conv;   auto properDivisors(in ulong n) pure nothrow @safe /*@nogc*/ { return iota(1UL, (n + 1) / 2 + 1).filter!(x => n % x == 0 && n != x); }   enum pDivsSum = (in ulong n) pure nothrow @safe /*@nogc*/ => n.properDivisors.sum;   auto aliquot(in ulong n, in size_t maxLen=16, in ulong maxTerm=2UL^^47) pure nothrow @safe { if (n == 0) return tuple("Terminating", [0UL]); ulong[] s = [n]; size_t sLen = 1; ulong newN = n;   while (sLen <= maxLen && newN < maxTerm) { newN = s.back.pDivsSum; if (s.canFind(newN)) { if (s[0] == newN) { if (sLen == 1) { return tuple("Perfect", s); } else if (sLen == 2) { return tuple("Amicable", s); } else return tuple(text("Sociable of length ", sLen), s); } else if (s.back == newN) { return tuple("Aspiring", s); } else return tuple(text("Cyclic back to ", newN), s); } else if (newN == 0) { return tuple("Terminating", s ~ 0); } else { s ~= newN; sLen++; } }   return tuple("Non-terminating", s); }   void main() { foreach (immutable n; 1 .. 11) writefln("%s: %s", n.aliquot[]); writeln; foreach (immutable n; [11, 12, 28, 496, 220, 1184, 12496, 1264460, 790, 909, 562, 1064, 1488]) writefln("%s: %s", n.aliquot[]); }
http://rosettacode.org/wiki/Active_Directory/Search_for_a_user
Active Directory/Search for a user
Make sure you Connect to Active Directory
#REXX
REXX
/* Rexx */ do LDAP_URL = 'ldap://localhost:11389' LDAP_DN_STR = 'uid=admin,ou=system' LDAP_CREDS = '********' LDAP_BASE_DN = 'ou=users,o=mojo' LDAP_SCOPE = 'sub' LDAP_FILTER = '"(&(objectClass=person)(&(uid=*mil*)))"' LDAP_ATTRIBUTES = '"dn" "cn" "sn" "uid"'   ldapCommand = , 'ldapsearch' , '-s base' , '-H' LDAP_URL , '-LLL' , '-x' , '-v' , '-s' LDAP_SCOPE , '-D' LDAP_DN_STR , '-w' LDAP_CREDS , '-b' LDAP_BASE_DN , LDAP_FILTER , LDAP_ATTRIBUTES , ''   say ldapCommand address command, ldapCommand   return end exit  
http://rosettacode.org/wiki/Active_Directory/Search_for_a_user
Active Directory/Search for a user
Make sure you Connect to Active Directory
#Ruby
Ruby
require 'rubygems' require 'net/ldap'   ldap = Net::LDAP.new(:host => 'hostname', :base => 'base') ldap.authenticate('bind_dn', 'bind_pass')   filter = Net::LDAP::Filter.pres('objectclass') filter &= Net::LDAP::Filter.eq('sn','Jackman') # or filter = Net::LDAP::Filter.construct('(&(objectclass=*)(sn=Jackman))')   results = ldap.search(:filter => filter) # returns an array of Net::LDAP::Entry objects   puts results[0][:sn] # ==> "Jackman"
http://rosettacode.org/wiki/Active_Directory/Search_for_a_user
Active Directory/Search for a user
Make sure you Connect to Active Directory
#Run_BASIC
Run BASIC
This allows the client on the web to see their directory. The user can click on any file or directory and this will give them the following options: [upload] data from their computer to the server [delete] data from their directory [rename] files [view] image files
http://rosettacode.org/wiki/Active_Directory/Search_for_a_user
Active Directory/Search for a user
Make sure you Connect to Active Directory
#Scala
Scala
import org.apache.directory.api.ldap.model.message.SearchScope import org.apache.directory.ldap.client.api.{LdapConnection, LdapNetworkConnection}   object LdapSearchDemo extends App {   class LdapSearch {   def demonstrateSearch(): Unit = {   val conn = new LdapNetworkConnection("localhost", 11389) try { conn.bind("uid=admin,ou=system", "********") search(conn, "*mil*") conn.unBind() } finally if (conn != null) conn.close()   }   private def search(connection: LdapConnection, uid: String): Unit = { val baseDn = "ou=users,o=mojo" val filter = "(&(objectClass=person)(&(uid=" + uid + ")))" val scope = SearchScope.SUBTREE val attributes = List("dn", "cn", "sn", "uid") var ksearch = 0 val cursor = connection.search(baseDn, filter, scope, attributes: _*) while (cursor.next) { ksearch += 1 val entry = cursor.get printf("Search entry %d = %s%n", ksearch, entry) } } }   new LdapSearch().demonstrateSearch()   }
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.
#Groovy
Groovy
class A { final x = { it + 25 } private map = new HashMap() Object get(String key) { map[key] } void set(String key, Object value) { map[key] = value } }
http://rosettacode.org/wiki/Add_a_variable_to_a_class_instance_at_runtime
Add a variable to a class instance at runtime
Demonstrate how to dynamically add variables to an object (a class instance) at runtime. This is useful when the methods/variables of an instance are based on a data file that isn't available until runtime. Hal Fulton gives an example of creating an OO CSV parser at An Exercise in Metaprogramming with Ruby. This is referred to as "monkeypatching" by Pythonistas and some others.
#Icon_and_Unicon
Icon and Unicon
  link ximage   procedure main() c1 := foo(1,2) # instance of foo write("c1:\n",ximage(c1)) c1 := extend(c1,["c","d"],[8,9]) # 2 new fields write("new c1:\n",ximage(c1)) c1 := extend(c1,["e"],[7]) # 1 more write("newest c1:\n",ximage(c1)) end   class foo(a,b) # dummy class end   procedure extend(instance,newvars,newvals) #: extend a class instance every put(f := [],fieldnames(instance)) # copy existing fieldnames c := ["tempconstructor"] ||| f # new constructor every put(c,!newvars) # append new vars t := constructor!c # new constructor x := t() # new instance every x[v := !f] := instance[v] # same as old instance x.__s := x # new self if \newvals then every i := 1 to min(*newvars,*newvals) do x[newvars[i]] := newvals[i] # add new vars = values return x end
http://rosettacode.org/wiki/Address_of_a_variable
Address of a variable
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation | Comparison | Matching Memory Operations Pointers & references | Addresses Task Demonstrate how to get the address of a variable and how to set the address of a variable.
#IWBASIC
IWBASIC
  == Get ==   There are at least three ways to get the address of a variable in IWBASIC. The first is to use the address of operator:   DEF X:INT PRINT &X 'This will print in the console window (after OPENCONSOLE is issued.) 'To Print in an open window the appropriate Window variable is specified, e.g., PRINT Win,&X.   The second is to use a pointer:   DEF X:INT DEF pPointer:POINTER pPointer=X   The third is to use the Windows API function Lstrcpy. That is done in the same way as the Creative Basic example; however, the function would be declared as follows: DECLARE IMPORT,Lstrcpy(P1:POINTER,P2:POINTER),INT.   == Set ==   It appears to the author that the closest one can come to being able to assign an address to a variable is to set which bytes will be used to store a variable in a block of reserved memory:   DEF pMem as POINTER pMem = NEW(CHAR,1000) : 'Get 1000 bytes to play with #<STRING>pMem = "Copy a string into memory" pMem += 100 #<UINT>pMem = 34234: 'Use bytes 100-103 to store a UINT DELETE pMem  
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.
#J
J
var =: 52 NB. Any variable (including data, functions, operators etc) var_addr =: 15!:6<'var' NB. Get address new_var =: 15!:7 var_addr NB. Set 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.
#Java
Java
julia> x = [1, 2, 3] julia> ptr = pointer_from_objref(x) Ptr{Void} @0x000000010282e4a0 julia> unsafe_pointer_to_objref(ptr) 3-element Array{Int64,1}: 1 2 3
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.
#Julia
Julia
julia> x = [1, 2, 3] julia> ptr = pointer_from_objref(x) Ptr{Void} @0x000000010282e4a0 julia> unsafe_pointer_to_objref(ptr) 3-element Array{Int64,1}: 1 2 3
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.
#C.2B.2B
C++
  #include <iomanip> #include <iostream> using namespace std;   const int pasTriMax = 61;   uint64_t pasTri[pasTriMax + 1];   void pascalTriangle(unsigned long n) // Calculate the n'th line 0.. middle { unsigned long j, k;   pasTri[0] = 1; j = 1; while (j <= n) { j++; k = j / 2; pasTri[k] = pasTri[k - 1]; for ( ;k >= 1; k--) pasTri[k] += pasTri[k - 1]; } }   bool isPrime(unsigned long n) { if (n > pasTriMax) { cout << n << " is out of range" << endl; exit(1); }   pascalTriangle(n); bool res = true; int i = n / 2; while (res && (i > 1)) { res = res && (pasTri[i] % n == 0); i--; } return res; }   void expandPoly(unsigned long n) { const char vz[] = {'+', '-'};   if (n > pasTriMax) { cout << n << " is out of range" << endl; exit(1); }   switch (n) { case 0: cout << "(x-1)^0 = 1" << endl; break; case 1: cout << "(x-1)^1 = x-1" << endl; break; default: pascalTriangle(n); cout << "(x-1)^" << n << " = "; cout << "x^" << n; bool bVz = true; int nDiv2 = n / 2; for (unsigned long j = n - 1; j > nDiv2; j--, bVz = !bVz) cout << vz[bVz] << pasTri[n - j] << "*x^" << j; for (unsigned long j = nDiv2; j > 1; j--, bVz = !bVz) cout << vz[bVz] << pasTri[j] << "*x^" << j; cout << vz[bVz] << pasTri[1] << "*x"; bVz = !bVz; cout << vz[bVz] << pasTri[0] << endl; break; } }   int main() { for (unsigned long n = 0; n <= 9; n++) expandPoly(n); for (unsigned long n = 2; n <= pasTriMax; n++) if (isPrime(n)) cout << setw(3) << n; cout << endl; }  
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.
#CLU
CLU
% Sieve of Erastothenes % Returns an array [1..max] marking the primes sieve = proc (max: int) returns (array[bool]) prime: array[bool] := array[bool]$fill(1, max, true) prime[1] := false   for p: int in int$from_to(2, max/2) do if prime[p] then for comp: int in int$from_to_by(p*2, max, p) do prime[comp] := false end end end return(prime) end sieve   % Sum the digits of a number digit_sum = proc (n: int) returns (int) sum: int := 0 while n ~= 0 do sum := sum + n // 10 n := n / 10 end return(sum) end digit_sum   start_up = proc () max = 500 po: stream := stream$primary_output()   count: int := 0 prime: array[bool] := sieve(max) for i: int in array[bool]$indexes(prime) do if prime[i] cand prime[digit_sum(i)] then count := count + 1 stream$putright(po, int$unparse(i), 5) if count//10 = 0 then stream$putl(po, "") end end end   stream$putl(po, "\nFound " || int$unparse(count) || " additive primes < " || int$unparse(max)) end start_up
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.
#COBOL
COBOL
IDENTIFICATION DIVISION. PROGRAM-ID. ADDITIVE-PRIMES.   DATA DIVISION. WORKING-STORAGE SECTION. 01 VARIABLES. 03 MAXIMUM PIC 999. 03 AMOUNT PIC 999. 03 CANDIDATE PIC 999. 03 DIGIT PIC 9 OCCURS 3 TIMES, REDEFINES CANDIDATE. 03 DIGITSUM PIC 99.   01 PRIME-DATA. 03 COMPOSITE-FLAG PIC X OCCURS 500 TIMES. 88 PRIME VALUE ' '. 03 SIEVE-PRIME PIC 999. 03 SIEVE-COMP-START PIC 999. 03 SIEVE-COMP PIC 999. 03 SIEVE-MAX PIC 999.   01 OUT-FMT. 03 NUM-FMT PIC ZZZ9. 03 OUT-LINE PIC X(40). 03 OUT-PTR PIC 99.   PROCEDURE DIVISION. BEGIN. MOVE 500 TO MAXIMUM. MOVE 1 TO OUT-PTR. PERFORM SIEVE. MOVE ZERO TO AMOUNT. PERFORM TEST-NUMBER VARYING CANDIDATE FROM 2 BY 1 UNTIL CANDIDATE IS GREATER THAN MAXIMUM. DISPLAY OUT-LINE. DISPLAY SPACES. MOVE AMOUNT TO NUM-FMT. DISPLAY 'Amount of additive primes found: ' NUM-FMT. STOP RUN.   TEST-NUMBER. ADD DIGIT(1), DIGIT(2), DIGIT(3) GIVING DIGITSUM. IF PRIME(CANDIDATE) AND PRIME(DIGITSUM), ADD 1 TO AMOUNT, PERFORM WRITE-NUMBER.   WRITE-NUMBER. MOVE CANDIDATE TO NUM-FMT. STRING NUM-FMT DELIMITED BY SIZE INTO OUT-LINE WITH POINTER OUT-PTR. IF OUT-PTR IS GREATER THAN 40, DISPLAY OUT-LINE, MOVE SPACES TO OUT-LINE, MOVE 1 TO OUT-PTR.   SIEVE. MOVE SPACES TO PRIME-DATA. DIVIDE MAXIMUM BY 2 GIVING SIEVE-MAX. PERFORM SIEVE-OUTER-LOOP VARYING SIEVE-PRIME FROM 2 BY 1 UNTIL SIEVE-PRIME IS GREATER THAN SIEVE-MAX.   SIEVE-OUTER-LOOP. IF PRIME(SIEVE-PRIME), MULTIPLY SIEVE-PRIME BY 2 GIVING SIEVE-COMP-START, PERFORM SIEVE-INNER-LOOP VARYING SIEVE-COMP FROM SIEVE-COMP-START BY SIEVE-PRIME UNTIL SIEVE-COMP IS GREATER THAN MAXIMUM.   SIEVE-INNER-LOOP. MOVE 'X' TO COMPOSITE-FLAG(SIEVE-COMP).
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
#Picat
Picat
main => T = e, foreach (X in 1..10) insert(X,T,T1), T := T1 end, output(T,0).   insert(X,S,R) => ins(X,S,R1), R1 = $t(_,A,Y,B), R = $t(b,A,Y,B).   ins(X,e,R) => R = $t(r,e,X,e). ins(X,t(C,A,Y,B),R), X < Y => ins(X,A,Ao), balance(C,Ao,Y,B,R). ins(X,t(C,A,Y,B),R), X > Y => ins(X,B,Bo), balance(C,A,Y,Bo,R). ins(_X,T,R) => R = T.   balance(C,A,X,B,S) :- (bal(C,A,X,B,T) -> S = T ; S = $t(C,A,X,B)).   bal(b, t(r,t(r,A,X,B),Y,C), Z, D, R) => R = $t(r,t(b,A,X,B),Y,t(b,C,Z,D)). bal(b, t(r,A,X,t(r,B,Y,C)), Z, D, R) => R = $t(r,t(b,A,X,B),Y,t(b,C,Z,D)). bal(b, A, X, t(r,t(r,B,Y,C),Z,D), R) => R = $t(r,t(b,A,X,B),Y,t(b,C,Z,D)). bal(b, A, X, t(r,B,Y,t(r,C,Z,D)), R) => R = $t(r,t(b,A,X,B),Y,t(b,C,Z,D)).   output(e,Indent) => printf("%*w\n",Indent,e). output(t(C,A,Y,B),Indent) => output(A,Indent+6), printf("%*w[%w]\n",Indent,C,Y), output(B,Indent+6).  
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
#PicoLisp
PicoLisp
(be color (R)) (be color (B))   (be tree (@ E)) (be tree (@P (T @C @L @X @R)) (color @C) (tree @P @L) (call @P @X) (tree @P @R) )   (be bal (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)))) (be bal (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)))) (be bal (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)))) (be bal (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))))   (be balance (@C @A @X @B @S) (bal @C @A @X @B @S) T ) (be balance (@C @A @X @B (T @C @A @X @B)))   (be ins (@X E (T R E @X E))) (be ins (@X (T @C @A @Y @B) @R) (^ @ (> (-> @Y) (-> @X))) (ins @X @A @Ao) (balance @C @Ao @Y @B @R) T ) (be ins (@X (T @C @A @Y @B) @R) (^ @ (> (-> @X) (-> @Y))) (ins @X @B @Bo) (balance @C @A @Y @Bo @R) T ) (be ins (@X (T @C @A @Y @B) (T @C @A @Y @B)))   (be insert (@X @S (T B @A @Y @B)) (ins @X @S (T @ @A @Y @B)) )
http://rosettacode.org/wiki/Almost_prime
Almost prime
A   k-Almost-prime   is a natural number   n {\displaystyle n}   that is the product of   k {\displaystyle k}   (possibly identical) primes. Example 1-almost-primes,   where   k = 1 {\displaystyle k=1} ,   are the prime numbers themselves. 2-almost-primes,   where   k = 2 {\displaystyle k=2} ,   are the   semiprimes. Task Write a function/method/subroutine/... that generates k-almost primes and use it to create a table here of the first ten members of k-Almost primes for   1 <= K <= 5 {\displaystyle 1<=K<=5} . Related tasks   Semiprime   Category:Prime Numbers
#FreeBASIC
FreeBASIC
' FB 1.05.0 Win64   Function kPrime(n As Integer, k As Integer) As Boolean Dim f As Integer = 0 For i As Integer = 2 To n While n Mod i = 0 If f = k Then Return false f += 1 n \= i Wend Next Return f = k End Function   Dim As Integer i, c, k For k = 1 To 5 Print "k = "; k; " : "; i = 2 c = 0 While c < 10 If kPrime(i, k) Then Print Using "### "; i; c += 1 End If i += 1 Wend Print Next   Print Print "Press any key to quit" Sleep
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
#Clojure
Clojure
(require '[clojure.java.io :as io])   (def groups (with-open [r (io/reader wordfile)] (group-by sort (line-seq r))))   (let [wordlists (sort-by (comp - count) (vals groups)) maxlength (count (first wordlists))] (doseq [wordlist (take-while #(= (count %) maxlength) wordlists)] (println wordlist))
http://rosettacode.org/wiki/Angle_difference_between_two_bearings
Angle difference between two bearings
Finding the angle between two bearings is often confusing.[1] Task Find the angle which is the result of the subtraction b2 - b1, where b1 and b2 are the bearings. Input bearings are expressed in the range   -180   to   +180   degrees. The  result  is also expressed in the range   -180   to   +180   degrees. Compute the angle for the following pairs: 20 degrees (b1) and 45 degrees (b2) -45 and 45 -85 and 90 -95 and 90 -45 and 125 -45 and 145 29.4803 and -88.6381 -78.3251 and -159.036 Optional extra Allow the input bearings to be any (finite) value. Test cases -70099.74233810938 and 29840.67437876723 -165313.6666297357 and 33693.9894517456 1174.8380510598456 and -154146.66490124757 60175.77306795546 and 42213.07192354373
#OCaml
OCaml
let get_diff b1 b2 = let r = mod_float (b2 -. b1) 360.0 in if r < -180.0 then r +. 360.0 else if r >= 180.0 then r -. 360.0 else r   let () = print_endline "Input in -180 to +180 range"; Printf.printf " %g\n" (get_diff 20.0 45.0); Printf.printf " %g\n" (get_diff (-45.0) 45.0); Printf.printf " %g\n" (get_diff (-85.0) 90.0); Printf.printf " %g\n" (get_diff (-95.0) 90.0); Printf.printf " %g\n" (get_diff (-45.0) 125.0); Printf.printf " %g\n" (get_diff (-45.0) 145.0); Printf.printf " %g\n" (get_diff (-45.0) 125.0); Printf.printf " %g\n" (get_diff (-45.0) 145.0); Printf.printf " %g\n" (get_diff 29.4803 (-88.6381)); Printf.printf " %g\n" (get_diff (-78.3251) (-159.036));   print_endline "Input in wider range"; Printf.printf " %g\n" (get_diff (-70099.74233810938) 29840.67437876723); Printf.printf " %g\n" (get_diff (-165313.6666297357) 33693.9894517456); Printf.printf " %g\n" (get_diff 1174.8380510598456 (-154146.66490124757)); Printf.printf " %g\n" (get_diff 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
#PowerShell
PowerShell
function Test-Deranged ([string[]]$Strings) { $array1 = $Strings[0].ToCharArray()   for ($i = 1; $i -lt $Strings.Count; $i++) { $array2 = $Strings[$i].ToCharArray()   for ($i = 0; $i -lt $array1.Count; $i++) { if ($array1[$i] -match $array2[$i]) { return $false } } }   return $true }     $words = [System.Collections.ArrayList]@()   Get-Content -Path ".\unixdict.txt" | ForEach-Object { [void]$words.Add([PSCustomObject]@{Word=$_; SortedWord=(($_.ToCharArray() | Sort-Object) -join "")}) }   [object[]]$anagrams = $words | Group-Object -Property SortedWord | Where-Object -Property Count -GT 1 | Sort-Object {$_.Name.Length} [string[]]$deranged = ($anagrams | ForEach-Object { if ((Test-Deranged $_.Group.Word)) {$_} } | Select-Object -Last 1).Group.Word   [PSCustomObject]@{ Length = $deranged[0].Length Words = $deranged }
http://rosettacode.org/wiki/Anonymous_recursion
Anonymous recursion
While implementing a recursive function, it often happens that we must resort to a separate   helper function   to handle the actual recursion. This is usually the case when directly calling the current function would waste too many resources (stack space, execution time), causing unwanted side-effects,   and/or the function doesn't have the right arguments and/or return values. So we end up inventing some silly name like   foo2   or   foo_helper.   I have always found it painful to come up with a proper name, and see some disadvantages:   You have to think up a name, which then pollutes the namespace   Function is created which is called from nowhere else   The program flow in the source code is interrupted Some languages allow you to embed recursion directly in-place.   This might work via a label, a local gosub instruction, or some special keyword. Anonymous recursion can also be accomplished using the   Y combinator. Task If possible, demonstrate this by writing the recursive version of the fibonacci function   (see Fibonacci sequence)   which checks for a negative argument before doing the actual recursion.
#Mathematica_.2F_Wolfram_Language
Mathematica / Wolfram Language
check := #<0& fib := If[check[#],Throw["Negative Argument"],If[#<=1,1,#0[#-2]+#0[#-1]]&[#]]& fib /@ Range[0,10]   {1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89}
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.
#Kotlin
Kotlin
// version 1.1   fun sumProperDivisors(n: Int): Int { if (n < 2) return 0 return (1..n / 2).filter{ (n % it) == 0 }.sum() }   fun main(args: Array<String>) { val sum = IntArray(20000, { sumProperDivisors(it) } ) println("The pairs of amicable numbers below 20,000 are:\n") for(n in 2..19998) { val m = sum[n] if (m > n && m < 20000 && n == sum[m]) { println(n.toString().padStart(5) + " and " + m.toString().padStart(5)) } } }
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.
#Standard_ML
Standard ML
open XWindows ; open Motif ;   structure TTd = Thread.Thread ; structure TTm = Thread.Mutex ;   val bannerWindow = fn () =>   let datatype thron = nothr | thr of TTd.thread ; val toThr = fn thr x=> x; val on = ref nothr ; val mx = TTm.mutex (); val dim = {tw=77,th=14} ; val shell = XtAppInitialise "" "click text to start or redirect" "top" [] [ XmNwidth 320, XmNheight 60 ] ; val main = XmCreateMainWindow shell "main" [ XmNmappedWhenManaged true ]  ; val canvas = XmCreateDrawingArea main "drawarea" [ XmNwidth (#tw dim), XmNheight (#th dim)] ;   val usegc = DefaultGC (XtDisplay canvas) ; val buf = XCreatePixmap (RootWindow (XtDisplay shell)) (Area{x=0,y=0,w = #tw dim, h= (#th dim) }) 24 ; val _ = (XSetBackground usegc 0xfffffff ; XDrawImageString buf usegc (XPoint {x=0,y= (#th dim)-1 } ) "Hello World! ") ; val drawparts = fn pos => ( XCopyArea buf (XtWindow canvas) usegc ( XPoint {x=pos,y=0} ) (Area{x=0,y=0,w = (#tw dim) - pos , h= #th dim }) ; XCopyArea buf (XtWindow canvas) usegc ( XPoint {x=00,y=0} ) (Area{x= (#tw dim) - pos ,y=0,w = pos, h= #th dim }) ; XFlush (XtDisplay canvas) ) ;   val direct = ref 1 ; fun shift s = ( drawparts ( s mod (#tw dim)) ; Posix.Process.sleep (Time.fromReal 0.1) ; shift ( s + (!direct)) ) ; val swdir = fn () => direct := ~ (!direct) ; val finish = fn () => ( if !on <> nothr then if TTd.isActive (toThr (!on)) then TTd.kill (toThr (!on)) else () else () ; on := nothr ); val movimg = fn () => ( finish () ; swdir () ; on := thr (TTd.fork (fn () => shift 0,[]) ) ) ; val setimg = fn (w,s,t) => ( finish () ; drawparts 0 ; t ) in   ( XtSetCallbacks canvas [ (XmNexposeCallback , setimg) , (XmNdestroyCallback, (fn (w,c,t)=>(finish();t))) ] XmNarmCallback ; XtAddEventHandler canvas [ ButtonPressMask ] false (fn (w,ButtonPress a)=> movimg ()|_=> ())  ; XtManageChild canvas ; XtManageChild main  ; XtRealizeWidget shell (* add loop here to compile *) )   end;
http://rosettacode.org/wiki/Animation
Animation
Animation is integral to many parts of GUIs, including both the fancy effects when things change used in window managers, and of course games.   The core of any animation system is a scheme for periodically changing the display while still remaining responsive to the user.   This task demonstrates this. Task Create a window containing the string "Hello World! " (the trailing space is significant). Make the text appear to be rotating right by periodically removing one letter from the end of the string and attaching it to the front. When the user clicks on the (windowed) text, it should reverse its direction.
#Suneido
Suneido
Window(Controller { Xmin: 50 Ymin: 50 New() { super(.layout()) .txt = .FindControl('text') .moveTimer = SetTimer(NULL, 0, 600, .moveTimerFunc) } direction: -1 moveTimer: false layout() { return #(Vert (Static 'Hello World! ', size: 12, weight: 600, notify:, name: 'text')) } moveTimerFunc(@unused) { str = .txt.Get() .txt.Set(str.Substr(1 * .direction) $ str.Substr(0, (1 * .direction))) } Static_Click() { .direction = .direction * -1 } Destroy() { if .moveTimer isnt false { KillTimer(NULL, .moveTimer) ClearCallback(.moveTimerFunc) } super.Destroy() } })
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.
#Oz
Oz
declare [QTk] = {Link ['x-oz://system/wp/QTk.ozf']}   Pi = 3.14159265   class PendulumModel feat K attr angle velocity   meth init(length:L <= 1.0 %% meters gravity:G <= 9.81 %% m/s² initialAngle:A <= Pi/2.) %% radians self.K = ~G / L angle := A velocity := 0.0 end   meth nextAngle(deltaT:DeltaTMS %% milliseconds  ?Angle) %% radians DeltaT = {Int.toFloat DeltaTMS} / 1000.0 %% seconds Acceleration = self.K * {Sin @angle} in velocity := @velocity + Acceleration * DeltaT angle := @angle + @velocity * DeltaT Angle = @angle end end   %% Animates a pendulum on a given canvas. class PendulumAnimation from Time.repeat feat Pend Rod Bob home:pos(x:160 y:50) length:140.0 delay   meth init(Pendulum Canvas delay:Delay <= 25) %% milliseconds self.Pend = Pendulum self.delay = Delay %% plate and pivot {Canvas create(line 0 self.home.y 320 self.home.y width:2 fill:grey50)} {Canvas create(oval 155 self.home.y-5 165 self.home.y+5 fill:grey50 outline:black)} %% the pendulum itself self.Rod = {Canvas create(line 1 1 1 1 width:3 fill:black handle:$)} self.Bob = {Canvas create(oval 1 1 2 2 fill:yellow outline:black handle:$)} %% {self setRepAll(action:Animate delay:Delay)} end   meth Animate Theta = {self.Pend nextAngle(deltaT:self.delay $)} %% calculate x and y from angle X = self.home.x + {Float.toInt self.length * {Sin Theta}} Y = self.home.y + {Float.toInt self.length * {Cos Theta}} in %% update canvas try {self.Rod setCoords(self.home.x self.home.y X Y)} {self.Bob setCoords(X-15 Y-15 X+15 Y+15)} catch system(tk(alreadyClosed ...) ...) then skip end end end   Pendulum = {New PendulumModel init}   Canvas GUI = td(title:"Pendulum" canvas(width:320 height:210 handle:?Canvas) action:proc {$} {Animation stop} {Window close} end ) Window = {QTk.build GUI}   Animation = {New PendulumAnimation init(Pendulum Canvas)} in {Window show} {Animation go}  
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.
#ERRE
ERRE
  PROGRAM AMB   ! ! for rosettacode.org !   !$KEY   DIM SET1$[2],SET2$[2],SET3$[2],SET4$[2]   FUNCTION WORDS_OK(STRING1$,STRING2$) WORDS_OK=(RIGHT$(STRING1$,1)=LEFT$(STRING2$,1)) END FUNCTION   PROCEDURE AMB(SET1$[],SET2$[],SET3$[],SET4$[]->RESULT$) RESULT$="" ! Empty string, e.g. fail FOR A=0 TO 2 DO FOR B=0 TO 2 DO FOR C=0 TO 2 DO FOR D=0 TO 2 DO IF WORDS_OK(SET1$[A],SET2$[B]) AND WORDS_OK(SET2$[B],SET3$[C]) AND WORDS_OK(SET3$[C],SET4$[D]) THEN RESULT$=SET1$[A]+" "+SET2$[B]+" "+SET3$[C]+" "+SET4$[D] EXIT PROCEDURE END IF END FOR END FOR END FOR END FOR END PROCEDURE   BEGIN PRINT(CHR$(12);)  ! CLS SET1$[0]="the" SET1$[1]="that" SET1$[2]="a" SET2$[0]="frog" SET2$[1]="elephant" SET2$[2]="thing" SET3$[0]="walked" SET3$[1]="treaded" SET3$[2]="grows" SET4$[0]="slowly" SET4$[1]="quickly" SET4$[2]=""   AMB(SET1$[],SET2$[],SET3$[],SET4$[]->TEXT$) IF TEXT$<>"" THEN PRINT("Correct sentence would be:") PRINT(TEXT$) ELSE PRINT("Failed to fine a correct sentence.") END IF PRINT PRINT("Press any key to exit.") REPEAT GET(Z$) UNTIL LEN(Z$)<>0 END PROGRAM  
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.
#Phix
Phix
include builtins/ldap.e constant servers = { "ldap.somewhere.com", } --... string name="name", password="passwd" --... for i=1 to length(servers) do atom ld = ldap_init(servers[i]) integer res = ldap_simple_bind_s(ld, name, password) printf(1,"%s: %d [%s]\n",{servers[i],res,ldap_err_desc(res)}) --... after done with it... ldap_unbind(ld) end for
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.
#PHP
PHP
<?php $ldap = ldap_connect($hostname, $port); $success = ldap_bind($ldap, $username, $password);
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.
#PicoLisp
PicoLisp
(unless (=0 (setq Ldap (native "libldap.so" "ldap_open" 'N "example.com" 389))) (quit "Can't open LDAP") )   (native "libldap.so" "ldap_simple_bind_s" 'I Ldap "user" "password")
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.
#Python
Python
import ldap   l = ldap.initialize("ldap://ldap.example.com") try: l.protocol_version = ldap.VERSION3 l.set_option(ldap.OPT_REFERRALS, 0)   bind = l.simple_bind_s("[email protected]", "password") finally: l.unbind()  
http://rosettacode.org/wiki/Accumulator_factory
Accumulator factory
A problem posed by Paul Graham is that of creating a function that takes a single (numeric) argument and which returns another function that is an accumulator. The returned accumulator function in turn also takes a single numeric argument, and returns the sum of all the numeric values passed in so far to that accumulator (including the initial value passed when the accumulator was created). Rules The detailed rules are at http://paulgraham.com/accgensub.html and are reproduced here for simplicity (with additions in small italic text). Before you submit an example, make sure the function Takes a number n and returns a function (lets call it g), that takes a number i, and returns n incremented by the accumulation of i from every call of function g(i). Although these exact function and parameter names need not be used Works for any numeric type-- i.e. can take both ints and floats and returns functions that can take both ints and floats. (It is not enough simply to convert all input to floats. An accumulator that has only seen integers must return integers.) (i.e., if the language doesn't allow for numeric polymorphism, you have to use overloading or something like that) Generates functions that return the sum of every number ever passed to them, not just the most recent. (This requires a piece of state to hold the accumulated value, which in turn means that pure functional languages can't be used for this task.) Returns a real function, meaning something that you can use wherever you could use a function you had defined in the ordinary way in the text of your program. (Follow your language's conventions here.) Doesn't store the accumulated value or the returned functions in a way that could cause them to be inadvertently modified by other code. (No global variables or other such things.) E.g. if after the example, you added the following code (in a made-up language) where the factory function is called foo: x = foo(1); x(5); foo(3); print x(2.3); It should print 8.3. (There is no need to print the form of the accumulator function returned by foo(3); it's not part of the task at all.) Task Create a function that implements the described rules. It need not handle any special error cases not described above. The simplest way to implement the task as described is typically to use a closure, providing the language supports them. Where it is not possible to hold exactly to the constraints above, describe the deviations.
#11l
11l
F accumulator(n) T Accumulator Float s F (Float n) .s = n F ()(Float n) .s += n R .s R Accumulator(n)   V x = accumulator(1) print(x(5)) print(x(2.3))   V x2 = accumulator(3) print(x2(5)) print(x2(3.3)) print(x2(0))
http://rosettacode.org/wiki/Align_columns
Align columns
Given a text file of many lines, where fields within a line are delineated by a single 'dollar' character, write a program that aligns each column of fields by ensuring that words in each column are separated by at least one space. Further, allow for each word in a column to be either left justified, right justified, or center justified within its column. Use the following text to test your programs: Given$a$text$file$of$many$lines,$where$fields$within$a$line$ are$delineated$by$a$single$'dollar'$character,$write$a$program that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$ column$are$separated$by$at$least$one$space. Further,$allow$for$each$word$in$a$column$to$be$either$left$ justified,$right$justified,$or$center$justified$within$its$column. Note that:   The example input texts lines may, or may not, have trailing dollar characters.   All columns should share the same alignment.   Consecutive space characters produced adjacent to the end of lines are insignificant for the purposes of the task.   Output text will be viewed in a mono-spaced font on a plain text editor or basic terminal.   The minimum space between columns should be computed from the text and not hard-coded.   It is not a requirement to add separating characters between or around columns. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#8th
8th
  quote | Given$a$text$file$of$many$lines,$where$fields$within$a$line$ are$delineated$by$a$single$'dollar'$character,$write$a$program that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$ column$are$separated$by$at$least$one$space. Further,$allow$for$each$word$in$a$column$to$be$either$left$ justified,$right$justified,$or$center$justified$within$its$column.| var, raw-text   [] var, data var width   : read-and-parse \ -- raw-text @ ( "$" s:/ data @ swap a:push drop ) s:eachline ;   : find-widest \ -- n data @ ( ( swap s:len nip n:max ) swap a:reduce ) 0 a:reduce ;   : print-data \ fmt -- width @ swap s:strfmt >r data @ ( nip ( nip r@ s:strfmt . ) a:each drop   cr ) a:each drop rdrop ;     : app:main read-and-parse   \ find widest column, and add one for the space: find-widest n:1+ width !   \ print the data cr "right:" . cr "%%>%ds" print-data cr "left:" . cr "%%<%ds" print-data cr "center:" . cr "%%|%ds" print-data bye ;    
http://rosettacode.org/wiki/Active_object
Active object
In object-oriented programming an object is active when its state depends on clock. Usually an active object encapsulates a task that updates the object's state. To the outer world the object looks like a normal object with methods that can be called from outside. Implementation of such methods must have a certain synchronization mechanism with the encapsulated task in order to prevent object's state corruption. A typical instance of an active object is an animation widget. The widget state changes with the time, while as an object it has all properties of a normal widget. The task Implement an active integrator object. The object has an input and output. The input can be set using the method Input. The input is a function of time. The output can be queried using the method Output. The object integrates its input over the time and the result becomes the object's output. So if the input is K(t) and the output is S, the object state S is changed to S + (K(t1) + K(t0)) * (t1 - t0) / 2, i.e. it integrates K using the trapeze method. Initially K is constant 0 and S is 0. In order to test the object: set its input to sin (2π f t), where the frequency f=0.5Hz. The phase is irrelevant. wait 2s set the input to constant 0 wait 0.5s Verify that now the object's output is approximately 0 (the sine has the period of 2s). The accuracy of the result will depend on the OS scheduler time slicing and the accuracy of the clock.
#C.23
C#
using System; using System.Threading.Tasks;   using static System.Diagnostics.Stopwatch; using static System.Math; using static System.Threading.Thread;   class ActiveObject { static double timeScale = 1.0 / Frequency;   Func<double, double> func; Task updateTask; double integral; double value; long timestamp0, timestamp;   public ActiveObject(Func<double, double> input) { timestamp0 = timestamp = GetTimestamp(); func = input; value = func(0); updateTask = Integrate(); }   public void ChangeInput(Func<double, double> input) { lock (updateTask) { func = input; } }   public double Value { get { lock (updateTask) { return integral; } } }   async Task Integrate() { while (true) { await Task.Yield(); var newTime = GetTimestamp(); double newValue;   lock (updateTask) { newValue = func((newTime - timestamp0) * timeScale); integral += (newValue + value) * (newTime - timestamp) * timeScale / 2; }   timestamp = newTime; value = newValue; } } }   class Program { static Func<double, double> Sine(double frequency) => t => Sin(2 * PI * frequency * t);   static void Main(string[] args) { var ao = new ActiveObject(Sine(0.5)); Sleep(TimeSpan.FromSeconds(2)); ao.ChangeInput(t => 0); Sleep(TimeSpan.FromSeconds(0.5)); Console.WriteLine(ao.Value); } }
http://rosettacode.org/wiki/Achilles_numbers
Achilles numbers
This page uses content from Wikipedia. The original article was at Achilles number. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) An Achilles number is a number that is powerful but imperfect. Named after Achilles, a hero of the Trojan war, who was also powerful but imperfect. A positive integer n is a powerful number if, for every prime factor p of n, p2 is also a divisor. In other words, every prime factor appears at least squared in the factorization. All Achilles numbers are powerful. However, not all powerful numbers are Achilles numbers: only those that cannot be represented as mk, where m and k are positive integers greater than 1. A strong Achilles number is an Achilles number whose Euler totient (𝜑) is also an Achilles number. E.G. 108 is a powerful number. Its prime factorization is 22 × 33, and thus its prime factors are 2 and 3. Both 22 = 4 and 32 = 9 are divisors of 108. However, 108 cannot be represented as mk, where m and k are positive integers greater than 1, so 108 is an Achilles number. 360 is not an Achilles number because it is not powerful. One of its prime factors is 5 but 360 is not divisible by 52 = 25. Finally, 784 is not an Achilles number. It is a powerful number, because not only are 2 and 7 its only prime factors, but also 22 = 4 and 72 = 49 are divisors of it. Nonetheless, it is a perfect power; its square root is an even integer, so it is not an Achilles number. 500 = 22 × 53 is a strong Achilles number as its Euler totient, 𝜑(500), is 200 = 23 × 52 which is also an Achilles number. Task Find and show the first 50 Achilles numbers. Find and show at least the first 20 strong Achilles numbers. For at least 2 through 5, show the count of Achilles numbers with that many digits. See also Wikipedia: Achilles number OEIS:A052486 - Achilles numbers - powerful but imperfect numbers OEIS:A194085 - Strong Achilles numbers: Achilles numbers m such that phi(m) is also an Achilles number Related task: Powerful numbers Related task: Totient function
#ARM_Assembly
ARM Assembly
  /* ARM assembly Raspberry PI */ /* program achilleNumber.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 NBFACT, 33 .equ MAXI, 50 .equ MAXI1, 20 .equ MAXI2, 1000000   /*********************************/ /* Initialized data */ /*********************************/ .data szMessNumber: .asciz " @ " szCarriageReturn: .asciz "\n" szErrorGen: .asciz "Program error !!!\n" szMessPrime: .asciz "This number is prime.\n" szMessTitAchille: .asciz "First 50 Achilles Numbers:\n" szMessTitStrong: .asciz "First 20 Strong Achilles Numbers:\n" szMessDigitsCounter: .asciz "Numbers with @ digits : @ \n" /*********************************/ /* UnInitialized data */ /*********************************/ .bss sZoneConv: .skip 24 tbZoneDecom: .skip 8 * NBFACT // factor 4 bytes, number of each factor 4 bytes /*********************************/ /* code section */ /*********************************/ .text .global main main: @ entry of program ldr r0,iAdrszMessTitAchille bl affichageMess mov r4,#1 @ start number mov r5,#0 @ total counter mov r6,#0 @ line display counter 1: mov r0,r4 bl controlAchille cmp r0,#0 @ achille number ? beq 2f @ no mov r0,r4 ldr r1,iAdrsZoneConv bl conversion10 @ call décimal conversion ldr r0,iAdrszMessNumber ldr r1,iAdrsZoneConv @ insert conversion in message bl strInsertAtCharInc bl affichageMess @ display message add r5,r5,#1 @ increment counter add r6,r6,#1 @ increment indice line display cmp r6,#10 @ if = 10 new line bne 2f mov r6,#0 ldr r0,iAdrszCarriageReturn bl affichageMess 2: add r4,r4,#1 @ increment number cmp r5,#MAXI blt 1b @ and loop   ldr r0,iAdrszMessTitStrong bl affichageMess mov r4,#1 @ start number mov r5,#0 @ total counter mov r6,#0   3: mov r0,r4 bl controlAchille cmp r0,#0 beq 4f mov r0,r4 bl computeTotient bl controlAchille cmp r0,#0 beq 4f mov r0,r4 ldr r1,iAdrsZoneConv bl conversion10 @ call décimal conversion ldr r0,iAdrszMessNumber ldr r1,iAdrsZoneConv @ insert conversion in message bl strInsertAtCharInc bl affichageMess @ display message add r5,r5,#1 add r6,r6,#1 cmp r6,#10 bne 4f mov r6,#0 ldr r0,iAdrszCarriageReturn bl affichageMess 4: add r4,r4,#1 cmp r5,#MAXI1 blt 3b   ldr r3,icstMaxi2 mov r4,#1 @ start number mov r6,#0 @ total counter 2 digits mov r7,#0 @ total counter 3 digits mov r8,#0 @ total counter 4 digits mov r9,#0 @ total counter 5 digits mov r10,#0 @ total counter 6 digits 5: mov r0,r4 bl controlAchille cmp r0,#0 beq 6f   mov r0,r4 ldr r1,iAdrsZoneConv bl conversion10 @ call décimal conversion r0 return digit number cmp r0,#6 addeq r10,r10,#1 beq 6f cmp r0,#5 addeq r9,r9,#1 beq 6f cmp r0,#4 addeq r8,r8,#1 beq 6f cmp r0,#3 addeq r7,r7,#1 beq 6f cmp r0,#2 addeq r6,r6,#1 beq 6f 6:   add r4,r4,#1 cmp r4,r3 blt 5b mov r0,#2 mov r1,r6 bl displayCounter mov r0,#3 mov r1,r7 bl displayCounter mov r0,#4 mov r1,r8 bl displayCounter mov r0,#5 mov r1,r9 bl displayCounter mov r0,#6 mov r1,r10 bl displayCounter b 100f 98: ldr r0,iAdrszErrorGen bl affichageMess 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 iAdrszErrorGen: .int szErrorGen iAdrsZoneConv: .int sZoneConv iAdrtbZoneDecom: .int tbZoneDecom iAdrszMessNumber: .int szMessNumber iAdrszMessTitAchille: .int szMessTitAchille iAdrszMessTitStrong: .int szMessTitStrong icstMaxi2: .int MAXI2 /******************************************************************/ /* display digit counter */ /******************************************************************/ /* r0 contains limit */ /* r1 contains counter */ displayCounter: push {r1-r3,lr} @ save registers mov r2,r1 ldr r1,iAdrsZoneConv bl conversion10 @ call décimal conversion ldr r0,iAdrszMessDigitsCounter ldr r1,iAdrsZoneConv @ insert conversion in message bl strInsertAtCharInc mov r3,r0 mov r0,r2 ldr r1,iAdrsZoneConv bl conversion10 @ call décimal conversion mov r0,r3 ldr r1,iAdrsZoneConv @ insert conversion in message bl strInsertAtCharInc bl affichageMess @ display message 100: pop {r1-r3,pc} @ restaur registers iAdrszMessDigitsCounter: .int szMessDigitsCounter /******************************************************************/ /* control if number is Achille number */ /******************************************************************/ /* r0 contains number */ /* r0 return 0 if not else return 1 */ controlAchille: push {r1-r4,lr} @ save registers mov r4,r0 ldr r1,iAdrtbZoneDecom bl decompFact @ factor decomposition cmp r0,#-1 beq 98f @ error ? cmp r0,#1 @ one only factor ? moveq r0,#0 beq 100f mov r1,r0 ldr r0,iAdrtbZoneDecom mov r2,r4 bl controlDivisor b 100f 98: ldr r0,iAdrszErrorGen bl affichageMess 100: pop {r1-r4,pc} @ restaur registers /******************************************************************/ /* control divisors function */ /******************************************************************/ /* r0 contains address of divisors area */ /* r1 contains the number of area items */ /* r2 contains number */ controlDivisor: push {r1-r10,lr} @ save registers cmp r1,#0 moveq r0,#0 beq 100f mov r6,r1 @ factors number mov r8,r2 @ save number mov r9,#0 @ indice mov r4,r0 @ save area address add r5,r4,r9,lsl #3 @ compute address first factor ldr r7,[r5,#4] @ load first exposant of factor add r2,r9,#1 1: add r5,r4,r2,lsl #3 @ compute address next factor ldr r3,[r5,#4] @ load exposant of factor cmp r3,r7 @ factor exposant <> ? bne 2f @ yes -> end verif add r2,r2,#1 @ increment indice cmp r2,r6 @ factor maxi ? blt 1b @ no -> loop mov r0,#0 b 100f @ all exposants are equals 2: mov r10,r2 @ save indice 21: movlt r2,r7 @ if r3 < r7 -> inversion movlt r7,r3 movlt r3,r2 @ r7 is the smaller exposant mov r0,r3 mov r1,r7 @ r7 < r3 bl computePgcd cmp r0,#1 beq 23f @ no commun multiple -> ne peux donc pas etre une puissance 22: add r10,r10,#1 @ increment indice cmp r10,r6 @ factor maxi ? movge r0,#0 bge 100f @ yes -> all exposants are multiples to smaller add r5,r4,r10,lsl #3 ldr r3,[r5,#4] @ load exposant of next factor cmp r3,r7 beq 22b @ for next b 21b @ for compare the 2 exposants   23: mov r9,#0 @ indice 3: add r5,r4,r9,lsl #3 ldr r7,[r5] @ load factor mul r1,r7,r7 @ factor square mov r0,r8 @ number bl division cmp r3,#0 @ remainder null ? movne r0,#0 bne 100f   add r9,#1 @ other factor cmp r9,r6 @ factors maxi ? blt 3b mov r0,#1 @ achille number ok 100: pop {r1-r10,lr} @ restaur registers bx lr @ return   /******************************************/ /* calcul du pgcd */ /*****************************************/ /* r0 number one */ /* r1 number two */ /* r0 result return */ computePgcd: push {r2,lr} @ save registers 1: cmp r0,#0 ble 2f cmp r1,r0 movgt r2,r0 movgt r0,r1 movgt r1,r2 sub r0,r1 b 1b 2: mov r0,r1 pop {r2,pc} @ restaur registers /******************************************************************/ /* compute totient of number */ /******************************************************************/ /* r0 contains number */ computeTotient: push {r1-r5,lr} @ save registers mov r4,r0 @ totient mov r5,r0 @ save number mov r1,#0 @ for first divisor 1: @ begin loop mul r3,r1,r1 @ compute square cmp r3,r5 @ compare number bgt 4f @ end add r1,r1,#2 @ next divisor mov r0,r5 bl division cmp r3,#0 @ remainder null ? bne 3f 2: @ begin loop 2 mov r0,r5 bl division cmp r3,#0 moveq r5,r2 @ new value = quotient beq 2b   mov r0,r4 @ totient bl division sub r4,r4,r2 @ compute new totient 3: cmp r1,#2 @ first divisor ? moveq r1,#1 @ divisor = 1 b 1b @ and loop 4: cmp r5,#1 @ final value > 1 ble 5f mov r0,r4 @ totient mov r1,r5 @ divide by value bl division sub r4,r4,r2 @ compute new totient 5:   mov r0,r4 100: pop {r1-r5,pc} @ restaur registers   /******************************************************************/ /* factor decomposition */ /******************************************************************/ /* r0 contains number */ /* r1 contains address of divisors area */ /* r0 return divisors items in table */ decompFact: push {r1-r8,lr} @ save registers mov r5,r1 mov r8,r0 @ save number bl isPrime @ prime ? cmp r0,#1 beq 98f @ yes is prime mov r4,#0 @ raz indice mov r1,#2 @ first divisor mov r6,#0 @ previous divisor mov r7,#0 @ number of same divisors 2: mov r0,r8 @ dividende bl division @ r1 divisor r2 quotient r3 remainder cmp r3,#0 bne 5f @ if remainder <> zero -> no divisor mov r8,r2 @ else quotient -> new dividende cmp r1,r6 @ same divisor ? beq 4f @ yes cmp r6,#0 @ no but is the first divisor ? beq 3f @ yes str r6,[r5,r4,lsl #2] @ else store in the table add r4,r4,#1 @ and increment counter str r7,[r5,r4,lsl #2] @ store counter add r4,r4,#1 @ next item mov r7,#0 @ and raz counter 3: mov r6,r1 @ new divisor 4: add r7,r7,#1 @ increment counter b 7f @ and loop   /* not divisor -> increment next divisor */ 5: cmp r1,#2 @ if divisor = 2 -> add 1 addeq r1,#1 addne r1,#2 @ else add 2 b 2b   /* divisor -> test if new dividende is prime */ 7: mov r3,r1 @ save divisor 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 9f @ yes cmp r6,#0 @ no but is the first divisor ? beq 8f @ yes it is a first str r6,[r5,r4,lsl #2] @ else store in table add r4,r4,#1 @ and increment counter str r7,[r5,r4,lsl #2] @ and store counter add r4,r4,#1 @ next item 8: mov r6,r8 @ new dividende -> divisor prec mov r7,#0 @ and raz counter 9: add r7,r7,#1 @ increment counter b 11f   10: mov r1,r3 @ current divisor = new divisor cmp r1,r8 @ current divisor > new dividende ? ble 2b @ no -> loop   /* end decomposition */ 11: str r6,[r5,r4,lsl #2] @ store last divisor add r4,r4,#1 str r7,[r5,r4,lsl #2] @ and store last number of same divisors add r4,r4,#1 lsr r0,r4,#1 @ return number of table items mov r3,#0 str r3,[r5,r4,lsl #2] @ store zéro in last table item add r4,r4,#1 str r3,[r5,r4,lsl #2] @ and zero in counter same divisor b 100f     98: //ldr r0,iAdrszMessPrime //bl affichageMess mov r0,#1 @ return code b 100f 99: ldr r0,iAdrszErrorGen bl affichageMess mov r0,#-1 @ error code b 100f 100: pop {r1-r8,lr} @ restaur registers bx lr iAdrszMessPrime: .int szMessPrime   /***************************************************/ /* check if a number is prime */ /***************************************************/ /* r0 contains the number */ /* r0 return 1 if prime 0 else */ @2147483647 @4294967297 @131071 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,lr} @ restaur des registres bx lr @ retour de la fonction en utilisant lr /********************************************************/ /* 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érifier les cas 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,lr} @ restaur des registres bx lr @ retour de la fonction en utilisant lr   /***************************************************/ /* 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égative ?   @ 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,lr} @ restaur registers bx lr     /***************************************************/ /* ROUTINES INCLUDE */ /***************************************************/ .include "../affichage.inc"  
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
#EchoLisp
EchoLisp
  ;; implementation of Floyd algorithm to find cycles in a graph ;; see Wikipedia https://en.wikipedia.org/wiki/Cycle_detection ;; returns (cycle-length cycle-starter steps) ;; steps = 0 if no cycle found ;; it's all about a tortoise 🐢 running at speed f(x) after a hare 🐰 at speed f(f (x)) ;; when they meet, a cycle is found   (define (floyd f x0 steps maxvalue) (define lam 1) ; cycle length (define tortoise (f x0)) (define hare (f (f x0)))   ;; cyclic  ? yes if steps > 0 (while (and (!= tortoise hare) (> steps 0)) (set!-values (tortoise hare) (values (f tortoise) (f (f hare)))) #:break (and (> hare maxvalue) (set! steps 0)) (set! steps (1- steps)))   ;; first repetition = cycle starter (set! tortoise x0) (while (and (!= tortoise hare) (> steps 0)) (set!-values (tortoise hare) (values (f tortoise) (f hare))))   ;; length of shortest cycle (set! hare (f tortoise)) (while (and (!= tortoise hare) (> steps 0)) (set! hare (f hare)) (set! lam (1+ lam))) (values lam tortoise steps))   ;; find cycle and classify (define (taxonomy n (steps 16) (maxvalue 140737488355328)) (define-values (cycle starter steps) (floyd sum-divisors n steps maxvalue)) (write n (cond (( = steps 0) 'non-terminating) (( = starter 0) 'terminating) ((and (= starter n) (= cycle 1)) 'perfect) ((and (= starter n) (= cycle 2)) 'amicable) ((= starter n) 'sociable ) ((= cycle 1) 'aspiring ) (else 'cyclic)))   (aliquote n starter) )   ;; print sequence (define (aliquote x0 (starter -1) (end -1 )(n 8)) (for ((i n)) (write x0) (set! x0 (sum-divisors x0)) #:break (and (= x0 end) (write x0)) (when (= x0 starter) (set! end starter))) (writeln ...))  
http://rosettacode.org/wiki/Active_Directory/Search_for_a_user
Active Directory/Search for a user
Make sure you Connect to Active Directory
#Tcl
Tcl
set Username "TestUser" set Filter "((&objectClass=*)(sAMAccountName=$Username))" set Base "dc=skycityauckland,dc=sceg,dc=com" set Attrs distinguishedName
http://rosettacode.org/wiki/Active_Directory/Search_for_a_user
Active Directory/Search for a user
Make sure you Connect to Active Directory
#UNIX_Shell
UNIX Shell
#!/bin/sh   LDAP_HOST="localhost" LDAP_PORT=11389 LDAP_DN_STR="uid=admin,ou=system" LDAP_CREDS="********" LDAP_BASE_DN="ou=users,o=mojo" LDAP_SCOPE="sub" LDAP_FILTER="(&(objectClass=person)(&(uid=*mil*)))" LDAP_ATTRIBUTES="dn cn sn uid"   ldapsearch \ -s base \ -h $LDAP_HOST \ -p $LDAP_PORT \ -LLL \ -x \ -v \ -s $LDAP_SCOPE \ -D $LDAP_DN_STR \ -w $LDAP_CREDS \ -b $LDAP_BASE_DN \ $LDAP_FILTER \ $LDAP_ATTRIBUTES  
http://rosettacode.org/wiki/Active_Directory/Search_for_a_user
Active Directory/Search for a user
Make sure you Connect to Active Directory
#VBScript
VBScript
strUsername = "TestUser" strQuery = "<LDAP://dc=skycityauckland,dc=sceg,dc=com>;"_ & "(&(objectclass=*)(samaccountname=" & strUsername & "));distinguishedname;subtree" objCmd.ActiveConnection = objConn objCmd.Properties("Page Size")=100 objCmd.CommandText = strQuery Set objRS = objCmd.Execute
http://rosettacode.org/wiki/Active_Directory/Search_for_a_user
Active Directory/Search for a user
Make sure you Connect to Active Directory
#Wren
Wren
/* active_directory_search_for_user.wren */   var LDAP_SCOPE_SUBTREE = 0x0002   foreign class LDAPMessage { construct new() {}   foreign msgfree() }   foreign class LDAP { construct init(host, port) {}   foreign simpleBindS(name, password)   foreign searchS(base, scope, filter, attrs, attrsOnly, res)   foreign unbind() }   class C { foreign static getInput(maxSize) }   var name = "" while (name == "") { System.write("Enter name : ") name = C.getInput(40) }   var password = "" while (password == "") { System.write("Enter password : ") password = C.getInput(40) }   var ld = LDAP.init("ldap.somewhere.com", 389) ld.simpleBindS(name, password)   var result = LDAPMessage.new() ld.searchS( "dc:somewhere,dc=com", LDAP_SCOPE_SUBTREE, "(&(objectclass=person)(|(cn=joe*)(cn=shmoe*)))", // all persons whose names start with joe or shmoe [], 0, result )   // do stuff with result   result.msgfree() ld.unbind()
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.
#Io
Io
Empty := Object clone   e := Empty clone e foo := 1
http://rosettacode.org/wiki/Add_a_variable_to_a_class_instance_at_runtime
Add a variable to a class instance at runtime
Demonstrate how to dynamically add variables to an object (a class instance) at runtime. This is useful when the methods/variables of an instance are based on a data file that isn't available until runtime. Hal Fulton gives an example of creating an OO CSV parser at An Exercise in Metaprogramming with Ruby. This is referred to as "monkeypatching" by Pythonistas and some others.
#J
J
C=:<'exampleclass' NB. this will be our class name V__C=: 0 NB. ensure the class exists OBJ1=:conew 'exampleclass' NB. create an instance of our class OBJ2=:conew 'exampleclass' NB. create another instance V__OBJ1,V__OBJ2 NB. both of our instances exist 0 W__OBJ1 NB. instance does not have a W |value error W__OBJ1=: 0 NB. here, we add a W to this instance W__OBJ1 NB. this instance now has a W 0 W__OBJ2 NB. our other instance does not |value error
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.
#JavaScript
JavaScript
e = {} // generic object e.foo = 1 e["bar"] = 2 // name specified at runtime
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.
#jq
jq
{"a":1} as $a | ($a + {"b":2}) as $a | $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.
#Kotlin
Kotlin
// Kotlin Native v0.5   import kotlinx.cinterop.*   fun main(args: Array<String>) { val intVar = nativeHeap.alloc<IntVar>() intVar.value = 42 with(intVar) { println("Value is $value, address is $rawPtr") } nativeHeap.free(intVar) }
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.
#Lambdatalk
Lambdatalk
    1) lambdas   {lambda {:x} {* :x :x}} -> _LAMB_123   2) arrays   '{A.new hello world} // defining an array -> _ARRA_123 // as replaced and used before post-processing -> [hello,world] // if unused after post-processing   3) pairs   {pre '{P.new hello world} // defining a pair -> _PAIR_123 // as replaced and used before post-processing -> (hello world) // if unused after post-processing   4) quotes   '{+ 1 2} // protecting an expression -> _QUOT_124 // as replaced and protected before post-processing -> {+ 1 2} // as displayed after post-processing  
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.
#Clojure
Clojure
(defn c "kth coefficient of (x - 1)^n" [n k] (/ (apply *' (range n (- n k) -1)) (apply *' (range k 0 -1)) (if (and (even? k) (< k n)) -1 1)))   (defn cs "coefficient series for (x - 1)^n, k=[0..n]" [n] (map #(c n %) (range (inc n))))   (defn aks? [p] (->> (cs p) rest butlast (every? #(-> % (mod p) zero?))))   (println "coefficient series n (k[0] .. k[n])") (doseq [n (range 10)] (println n (cs n))) (println) (println "primes < 50 per AKS:" (filter aks? (range 2 50)))
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.
#Common_Lisp
Common Lisp
  (defun sum-of-digits (n) "Return the sum of the digits of a number" (do* ((sum 0 (+ sum rem)) rem ) ((zerop n) sum) (multiple-value-setq (n rem) (floor n 10)) ))   (defun additive-primep (n) (and (primep n) (primep (sum-of-digits n))) )     ; To test if a number is prime we can use a number of different methods. Here I use Wilson's Theorem (see Primality by Wilson's theorem):   (defun primep (n) (unless (zerop n) (zerop (mod (1+ (factorial (1- n))) n)) ))   (defun factorial (n) (if (< n 2) 1 (* n (factorial (1- n)))) )      
http://rosettacode.org/wiki/Additive_primes
Additive primes
Definitions In mathematics, additive primes are prime numbers for which the sum of their decimal digits are also primes. Task Write a program to determine (and show here) all additive primes less than 500. Optionally, show the number of additive primes. Also see   the OEIS entry:   A046704 additive primes.   the prime-numbers entry:   additive primes.   the geeks for geeks entry: additive prime number.   the prime-numbers fandom: additive primes.
#Crystal
Crystal
# Fast/simple way to generate primes for small values. # Uses P3 Prime Generator (PG) and its Prime Generator Sequence (PGS).   def prime?(n) # P3 Prime Generator primality test return false unless (n | 1 == 3 if n < 5) || (n % 6) | 4 == 5 sqrt_n = Math.isqrt(n) # For Crystal < 1.2.0 use Math.sqrt(n).to_i pc = typeof(n).new(5) while pc <= sqrt_n return false if n % pc == 0 || n % (pc + 2) == 0 pc += 6 end true end   def additive_primes(n) primes = [2, 3] pc, inc = 5, 2 while pc < n primes << pc if prime?(pc) && prime?(pc.digits.sum) pc += inc; inc ^= 0b110 # generate P3 sequence: 5 7 11 13 17 19 ... end primes # list of additive primes <= n end   nn = 500 addprimes = additive_primes(nn) maxdigits = addprimes.last.digits.size addprimes.each_with_index { |n, idx| printf "%*d ", maxdigits, n; print "\n" if idx % 10 == 9 } # more efficient #addprimes.each_with_index { |n, idx| print "%#{maxdigits}d " % n; print "\n" if idx % 10 == 9} # alternatively puts "\n#{addprimes.size} additive primes below #{nn}."   puts   nn = 5000 addprimes = additive_primes(nn) maxdigits = addprimes.last.digits.size addprimes.each_with_index { |n, idx| printf "%*d ", maxdigits, n; print "\n" if idx % 10 == 9 } # more efficient puts "\n#{addprimes.size} additive primes below #{nn}."  
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
#Prolog
Prolog
color(r). color(b). tree(_,e). tree(P,t(C,L,X,R)) :- color(C), tree(P,L), call(P,X), tree(P,R). bal(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))). bal(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))). bal(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))). bal(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(C,A,X,B,S) :- ( bal(C,A,X,B,T) -> S = T ; S = t(C,A,X,B) ). ins(X,e,t(r,e,X,e)). ins(X,t(C,A,Y,B),R) :- ( X < Y -> ins(X,A,Ao), balance(C,Ao,Y,B,R)  ; X > Y -> ins(X,B,Bo), balance(C,A,Y,Bo,R)  ; X = Y -> R = t(C,A,Y,B) ). insert(X,S,t(b,A,Y,B)) :- ins(X,S,t(_,A,Y,B)).
http://rosettacode.org/wiki/Algebraic_data_types
Algebraic data types
Some languages offer direct support for algebraic data types and pattern matching on them. While this of course can always be simulated with manual tagging and conditionals, it allows for terse code which is easy to read, and can represent the algorithm directly. Task As an example, implement insertion in a red-black-tree. A red-black-tree is a binary tree where each internal node has a color attribute red or black. Moreover, no red node can have a red child, and every path from the root to an empty node must contain the same number of black nodes. As a consequence, the tree is balanced, and must be re-balanced after an insertion. Reference Red-Black Trees in a Functional Setting
#Python
Python
from __future__ import annotations from enum import Enum from typing import NamedTuple from typing import Optional     class Color(Enum): B = 0 R = 1     class Tree(NamedTuple): color: Color left: Optional[Tree] value: int right: Optional[Tree]   def insert(self, val: int) -> Tree: return self._insert(val).make_black()   def _insert(self, val: int) -> Tree: match compare(val, self.value): case _ if self == EMPTY: return Tree(Color.R, EMPTY, val, EMPTY) case -1: assert self.left is not None return Tree( self.color, self.left._insert(val), self.value, self.right ).balance() case 1: assert self.right is not None return Tree( self.color, self.left, self.value, self.right._insert(val) ).balance() case _: return self   def balance(self) -> Tree: match self: case (Color.B, (Color.R, (Color.R, a, x, b), y, c), z, d): return Tree(Color.R, Tree(Color.B, a, x, b), y, Tree(Color.B, c, z, d)) case (Color.B, (Color.R, a, x, (Color.R, b, y, c)), z, d): return Tree(Color.R, Tree(Color.B, a, x, b), y, Tree(Color.B, c, z, d)) case (Color.B, a, x, (Color.R, (Color.R, b, y, c), z, d)): return Tree(Color.R, Tree(Color.B, a, x, b), y, Tree(Color.B, c, z, d)) case (Color.B, a, x, (Color.R, b, y, (Color.R, c, z, d))): return Tree(Color.R, Tree(Color.B, a, x, b), y, Tree(Color.B, c, z, d)) case _: return self   def make_black(self) -> Tree: return self._replace(color=Color.B)   def __str__(self) -> str: if self == EMPTY: return "[]" return f"[{'R' if self.color == Color.R else 'B'}{self.value}]"   def print(self, indent: int = 0) -> None: if self != EMPTY: assert self.right is not None self.right.print(indent + 1)   print(f"{' ' * indent * 4}{self}")   if self != EMPTY: assert self.left is not None self.left.print(indent + 1)     EMPTY = Tree(Color.B, None, 0, None)     def compare(x: int, y: int) -> int: if x > y: return 1 if x < y: return -1 return 0     def main(): tree = EMPTY for i in range(1, 17): tree = tree.insert(i) tree.print()     if __name__ == "__main__": main()  
http://rosettacode.org/wiki/Almost_prime
Almost prime
A   k-Almost-prime   is a natural number   n {\displaystyle n}   that is the product of   k {\displaystyle k}   (possibly identical) primes. Example 1-almost-primes,   where   k = 1 {\displaystyle k=1} ,   are the prime numbers themselves. 2-almost-primes,   where   k = 2 {\displaystyle k=2} ,   are the   semiprimes. Task Write a function/method/subroutine/... that generates k-almost primes and use it to create a table here of the first ten members of k-Almost primes for   1 <= K <= 5 {\displaystyle 1<=K<=5} . Related tasks   Semiprime   Category:Prime Numbers
#Frink
Frink
for k = 1 to 5 { n=2 count = 0 print["k=$k:"] do { if length[factorFlat[n]] == k { print[" $n"] count = count + 1 } n = n + 1 } while count < 10   println[] }
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
#Futhark
Futhark
  let kprime(n: i32, k: i32): bool = let (p,f) = (2, 0) let (n,_,f) = loop (n, p, f) while f < k && p*p <= n do let (n,f) = loop (n, f) while 0 == n % p do (n/p, f+1) in (n, p+1, f) in f + (if n > 1 then 1 else 0) == k   let main(m: i32): [][]i32 = let f k = let ps = replicate 10 0 let (_,_,ps) = loop (i,c,ps) = (2,0,ps) while c < 10 do if kprime(i,k) then unsafe let ps[c] = i in (i+1, c+1, ps) else (i+1, c, ps) in ps in map f (1...m)  
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
#CLU
CLU
% Keep a list of anagrams anagrams = cluster is new, add, largest_size, sets anagram_set = struct[letters: string, words: array[string]] rep = array[anagram_set]   new = proc () returns (cvt) return(rep$[]) end new    % Sort the letters in a string sort = proc (s: string) returns (string) chars: array[int] := array[int]$fill(0,256,0) % Assuming ASCII here for c: char in string$chars(s) do i: int := char$c2i(c) chars[i] := chars[i] + 1 end sorted: array[char] := array[char]$predict(1,string$size(s)) for i: int in array[int]$indexes(chars) do for j: int in int$from_to(1,chars[i]) do array[char]$addh(sorted,char$i2c(i)) end end return(string$ac2s(sorted)) end sort    % Add a word add = proc (a: cvt, s: string) letters: string := sort(s) as: anagram_set begin for t_as: anagram_set in rep$elements(a) do if t_as.letters = letters then as := t_as exit found end end as := anagram_set${letters: letters, words: array[string]$[]} rep$addh(a, as) end except when found: end array[string]$addh(as.words, s) end add    % Find the size of the largest set largest_size = proc (a: cvt) returns (int) size: int := 0 for as: anagram_set in rep$elements(a) do cur: int := array[string]$size(as.words) if cur > size then size := cur end end return(size) end largest_size    % Yield all sets of a given size sets = iter (a: cvt, s: int) yields (sequence[string]) for as: anagram_set in rep$elements(a) do if array[string]$size(as.words) = s then yield(sequence[string]$a2s(as.words)) end end end sets end anagrams   start_up = proc () an: anagrams := anagrams$new() dict: stream := stream$open(file_name$parse("unixdict.txt"), "read") while true do anagrams$add(an, stream$getl(dict)) except when end_of_file: break end end stream$close(dict)   po: stream := stream$primary_output() max: int := anagrams$largest_size(an) stream$putl(po, "Largest amount of anagrams per set: " || int$unparse(max)) stream$putl(po, "")   for words: sequence[string] in anagrams$sets(an, max) do for word: string in sequence[string]$elements(words) do stream$putleft(po, word, 7) end stream$putl(po, "") end end start_up
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
#PARI.2FGP
PARI/GP
centerliftmod1(x)=frac(x+1/2)-1/2; anglediff(x,y)=centerliftmod1((y-x)/360)*360; vecFunc(f)=v->call(f,v); apply(vecFunc(anglediff), [[20,45], [-45,45], [-85,90], [-95,90], [-45,125], [-45,145], [29.4803,-88.6381], [-78.3251,-159.036], [-70099.74233810938,29840.67437876723], [-165313.6666297357,33693.9894517456], [1174.8380510598456,-154146.66490124757], [60175.77306795546,42213.07192354373]])
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
#Prolog
Prolog
longest_deranged_anagram :- http_open('http://www.puzzlers.org/pub/wordlists/unixdict.txt',In,[]), read_file(In, [], Out), close(In), msort(Out, MOut), group_pairs_by_key(MOut, GPL), map_list_to_pairs(compute_len, GPL, NGPL), predsort(my_compare, NGPL, GPLSort), search_derangement(GPLSort).     % order tuples to have longest words first my_compare(R, N1-(K1-E1), N2-(K2-E2)) :- ( N1 < N2 -> R = > ; N1 > N2 -> R = <; length(E1, L1), length(E2, L2), ( L1 < L2 -> R = <; L1 > L2 -> R = >; compare(R, K1, K2))).     compute_len(_-[H|_], Len) :- length(H, Len).     % check derangement of anagrams derangement([], []). derangement([H1|T1], [H2 | T2]) :- H1 \= H2, derangement(T1, T2).     search_derangement([_-(_-L) | T]) :- length(L, 1), !, search_derangement(T).     search_derangement([_-(_-L) | T]) :- ( search(L) -> true; search_derangement(T)).   search([]) :- fail. search([H | T]) :- ( search_one(H, T) -> true; search(T)).     search_one(Word, L) :- include(derangement(Word), L, [H|_]), atom_codes(W, Word), atom_codes(W1, H), format('Longest deranged anagrams : ~w ~w ~n', [W, W1]).     read_file(In, L, L1) :- read_line_to_codes(In, W), ( W == end_of_file -> L1 = L ; msort(W, W1), atom_codes(A, W1), read_file(In, [A-W | L], L1)).
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.
#MATLAB
MATLAB
  function v = fibonacci(n) assert(n >= 0) v = fibonacci(n,0,1);   % nested function function a = fibonacci(n,a,b) if n ~= 0 a = fibonacci(n-1,b,a+b); end end 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.
#Lua
Lua
function sumDivs (n) local sum = 1 for d = 2, math.sqrt(n) do if n % d == 0 then sum = sum + d sum = sum + n / d end end return sum end   for n = 2, 20000 do m = sumDivs(n) if m > n then if sumDivs(m) == n then print(n, m) end end end
http://rosettacode.org/wiki/Animation
Animation
Animation is integral to many parts of GUIs, including both the fancy effects when things change used in window managers, and of course games.   The core of any animation system is a scheme for periodically changing the display while still remaining responsive to the user.   This task demonstrates this. Task Create a window containing the string "Hello World! " (the trailing space is significant). Make the text appear to be rotating right by periodically removing one letter from the end of the string and attaching it to the front. When the user clicks on the (windowed) text, it should reverse its direction.
#SVG
SVG
<svg xmlns="http://www.w3.org/2000/svg" width="100" height="30"> <g id="all"> <rect width="100%" height="100%" fill="yellow"/> <g style="font: 18 'Times New Roman', serif; fill: black; stroke: white; stroke-width: 0.001; /* workaround for Batik oddity */ "> <text x="0" y="20" textLength="95">Hello World!</text> <text x="-100" y="20" textLength="95">Hello World!</text> <animateMotion restart="whenNotActive" repeatCount="indefinite" dur="2s" begin="0s;all.click" end="all.click" from="0,0" by="100,0"/> <animateMotion restart="whenNotActive" repeatCount="indefinite" dur="2s" begin="all.click" end="all.click" from="100,0" by="-100,0"/> </g> </g> </svg>
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.
#Perl
Perl
  use strict; use warnings; use Tk; use Math::Trig qw/:pi/;   my $root = new MainWindow( -title => 'Pendulum Animation' ); my $canvas = $root->Canvas(-width => 320, -height => 200); my $after_id;   for ($canvas) { $_->createLine( 0, 25, 320, 25, -tags => [qw/plate/], -width => 2, -fill => 'grey50' ); $_->createOval( 155, 20, 165, 30, -tags => [qw/pivot outline/], -fill => 'grey50' ); $_->createLine( 1, 1, 1, 1, -tags => [qw/rod width/], -width => 3, -fill => 'black' ); $_->createOval( 1, 1, 2, 2, -tags => [qw/bob outline/], -fill => 'yellow' ); }   $canvas->raise('pivot'); $canvas->pack(-fill => 'both', -expand => 1); my ($Theta, $dTheta, $length, $homeX, $homeY) = (45, 0, 150, 160, 25);   sub show_pendulum { my $angle = $Theta * pi() / 180; my $x = $homeX + $length * sin($angle); my $y = $homeY + $length * cos($angle); $canvas->coords('rod', $homeX, $homeY, $x, $y); $canvas->coords('bob', $x-15, $y-15, $x+15, $y+15); }       sub recompute_angle { my $scaling = 3000.0 / ($length ** 2); # first estimate my $firstDDTheta = -sin($Theta * pi / 180) * $scaling; my $midDTheta = $dTheta + $firstDDTheta; my $midTheta = $Theta + ($dTheta + $midDTheta)/2; # second estimate my $midDDTheta = -sin($midTheta * pi/ 180) * $scaling; $midDTheta = $dTheta + ($firstDDTheta + $midDDTheta)/2; $midTheta = $Theta + ($dTheta + $midDTheta)/2; # again, first $midDDTheta = -sin($midTheta * pi/ 180) * $scaling; my $lastDTheta = $midDTheta + $midDDTheta; my $lastTheta = $midTheta + ($midDTheta + $lastDTheta)/2; # again, second my $lastDDTheta = -sin($lastTheta * pi/180) * $scaling; $lastDTheta = $midDTheta + ($midDDTheta + $lastDDTheta)/2; $lastTheta = $midTheta + ($midDTheta + $lastDTheta)/2; # Now put the values back in our globals $dTheta = $lastDTheta; $Theta = $lastTheta; }     sub animate { recompute_angle; show_pendulum; $after_id = $root->after(15 => sub {animate() }); }   show_pendulum; $after_id = $root->after(500 => sub {animate});   $canvas->bind('<Destroy>' => sub {$after_id->cancel}); MainLoop;
http://rosettacode.org/wiki/Amb
Amb
Define and give an example of the Amb operator. The Amb operator (short for "ambiguous") expresses nondeterminism. This doesn't refer to randomness (as in "nondeterministic universe") but is closely related to the term as it is used in automata theory ("non-deterministic finite automaton"). The Amb operator takes a variable number of expressions (or values if that's simpler in the language) and yields a correct one which will satisfy a constraint in some future computation, thereby avoiding failure. Problems whose solution the Amb operator naturally expresses can be approached with other tools, such as explicit nested iterations over data sets, or with pattern matching. By contrast, the Amb operator appears integrated into the language. Invocations of Amb are not wrapped in any visible loops or other search patterns; they appear to be independent. Essentially Amb(x, y, z) splits the computation into three possible futures: a future in which the value x is yielded, a future in which the value y is yielded and a future in which the value z is yielded. The future which leads to a successful subsequent computation is chosen. The other "parallel universes" somehow go away. Amb called with no arguments fails. For simplicity, one of the domain values usable with Amb may denote failure, if that is convenient. For instance, it is convenient if a Boolean false denotes failure, so that Amb(false) fails, and thus constraints can be expressed using Boolean expressions like Amb(x * y == 8) which unless x and y add to four. A pseudo-code program which satisfies this constraint might look like: let x = Amb(1, 2, 3) let y = Amb(7, 6, 4, 5) Amb(x * y = 8) print x, y The output is 2 4 because Amb(1, 2, 3) correctly chooses the future in which x has value 2, Amb(7, 6, 4, 5) chooses 4 and consequently Amb(x * y = 8) produces a success. Alternatively, failure could be represented using strictly Amb(): unless x * y = 8 do Amb() Or else Amb could take the form of two operators or functions: one for producing values and one for enforcing constraints: let x = Ambsel(1, 2, 3) let y = Ambsel(4, 5, 6) Ambassert(x * y = 8) print x, y where Ambassert behaves like Amb() if the Boolean expression is false, otherwise it allows the future computation to take place, without yielding any value. The task is to somehow implement Amb, and demonstrate it with a program which chooses one word from each of the following four sets of character strings to generate a four-word sentence: "the" "that" "a" "frog" "elephant" "thing" "walked" "treaded" "grows" "slowly" "quickly" The constraint to be satisfied is that the last character of each word (other than the last) is the same as the first character of its successor. The only successful sentence is "that thing grows slowly"; other combinations do not satisfy the constraint and thus fail. The goal of this task isn't to simply process the four lists of words with explicit, deterministic program flow such as nested iteration, to trivially demonstrate the correct output. The goal is to implement the Amb operator, or a facsimile thereof that is possible within the language limitations.
#F.23
F#
// define the List "workflow" (monad) type ListBuilder() = member o.Bind( lst, f ) = List.concat( List.map (fun x -> f x) lst ) member o.Return( x ) = [x] member o.Zero() = []   let list = ListBuilder()   let amb = id   // last element of a sequence let last s = Seq.nth ((Seq.length s) - 1) s   // is the last element of left the same as the first element of right? let joins left right = last left = Seq.head right   let example = list { let! w1 = amb ["the"; "that"; "a"] let! w2 = amb ["frog"; "elephant"; "thing"] let! w3 = amb ["walked"; "treaded"; "grows"] let! w4 = amb ["slowly"; "quickly"] if joins w1 w2 && joins w2 w3 && joins w3 w4 then return String.concat " " [w1; w2; w3; w4] }   printfn "%s" (List.head example)
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.
#Racket
Racket
#lang racket (require net/ldap) (ldap-authenticate "ldap.somewhere.com" 389 "uid=username,ou=people,dc=somewhere,dc=com" password)
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.
#Raku
Raku
use LMDB;   my %DB := LMDB::DB.open(:path<some-dir>, %connection-parameters);  
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.
#Ruby
Ruby
require 'rubygems' require 'net/ldap' ldap = Net::LDAP.new(:host => 'ldap.example.com', :base => 'o=companyname') ldap.authenticate('bind_dn', 'bind_pass')
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.
#Run_BASIC
Run BASIC
print shell$("dir") ' shell out to the os and print it
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.
#Rust
Rust
  let conn = ldap3::LdapConn::new("ldap://ldap.example.com")?; conn.simple_bind("bind_dn", "bind_pass")?.success()?;  
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.
#Scala
Scala
import java.io.IOException   import org.apache.directory.api.ldap.model.exception.LdapException import org.apache.directory.ldap.client.api.{LdapConnection, LdapNetworkConnection}   object LdapConnectionDemo { @throws[LdapException] @throws[IOException] def main(args: Array[String]): Unit = { try { val connection: LdapConnection = new LdapNetworkConnection("localhost", 10389) try { connection.bind() connection.unBind() } finally if (connection != null) connection.close() } } }
http://rosettacode.org/wiki/Accumulator_factory
Accumulator factory
A problem posed by Paul Graham is that of creating a function that takes a single (numeric) argument and which returns another function that is an accumulator. The returned accumulator function in turn also takes a single numeric argument, and returns the sum of all the numeric values passed in so far to that accumulator (including the initial value passed when the accumulator was created). Rules The detailed rules are at http://paulgraham.com/accgensub.html and are reproduced here for simplicity (with additions in small italic text). Before you submit an example, make sure the function Takes a number n and returns a function (lets call it g), that takes a number i, and returns n incremented by the accumulation of i from every call of function g(i). Although these exact function and parameter names need not be used Works for any numeric type-- i.e. can take both ints and floats and returns functions that can take both ints and floats. (It is not enough simply to convert all input to floats. An accumulator that has only seen integers must return integers.) (i.e., if the language doesn't allow for numeric polymorphism, you have to use overloading or something like that) Generates functions that return the sum of every number ever passed to them, not just the most recent. (This requires a piece of state to hold the accumulated value, which in turn means that pure functional languages can't be used for this task.) Returns a real function, meaning something that you can use wherever you could use a function you had defined in the ordinary way in the text of your program. (Follow your language's conventions here.) Doesn't store the accumulated value or the returned functions in a way that could cause them to be inadvertently modified by other code. (No global variables or other such things.) E.g. if after the example, you added the following code (in a made-up language) where the factory function is called foo: x = foo(1); x(5); foo(3); print x(2.3); It should print 8.3. (There is no need to print the form of the accumulator function returned by foo(3); it's not part of the task at all.) Task Create a function that implements the described rules. It need not handle any special error cases not described above. The simplest way to implement the task as described is typically to use a closure, providing the language supports them. Where it is not possible to hold exactly to the constraints above, describe the deviations.
#8th
8th
  \ RossetaCode 'accumulator factory'   \ The 'accumulate' word stores the accumulated value in an array, because arrays \ are mutable: : accumulate \ n [m] -- n+m \ [m] -> [n+m] a:pop rot n:+ tuck a:push swap ;   \ To comply with the rules, this takes a number and wraps it in an array, and \ then curries it. Since 'curry:' is "immediate", we need to postpone its \ action using 'p:.   : make-accumulator 1 a:close ' accumulate p: curry: ;   \ We 'curry' the initial value along with 'accumulate' to create \ a new word, '+10', which will give us the accumulated values 10 make-accumulator +10   \ This loop will add 1, then 2, then 3, to the accumulator, which prints the \ results 11,13,16: ( +10 . cr ) 1 3 loop bye
http://rosettacode.org/wiki/Accumulator_factory
Accumulator factory
A problem posed by Paul Graham is that of creating a function that takes a single (numeric) argument and which returns another function that is an accumulator. The returned accumulator function in turn also takes a single numeric argument, and returns the sum of all the numeric values passed in so far to that accumulator (including the initial value passed when the accumulator was created). Rules The detailed rules are at http://paulgraham.com/accgensub.html and are reproduced here for simplicity (with additions in small italic text). Before you submit an example, make sure the function Takes a number n and returns a function (lets call it g), that takes a number i, and returns n incremented by the accumulation of i from every call of function g(i). Although these exact function and parameter names need not be used Works for any numeric type-- i.e. can take both ints and floats and returns functions that can take both ints and floats. (It is not enough simply to convert all input to floats. An accumulator that has only seen integers must return integers.) (i.e., if the language doesn't allow for numeric polymorphism, you have to use overloading or something like that) Generates functions that return the sum of every number ever passed to them, not just the most recent. (This requires a piece of state to hold the accumulated value, which in turn means that pure functional languages can't be used for this task.) Returns a real function, meaning something that you can use wherever you could use a function you had defined in the ordinary way in the text of your program. (Follow your language's conventions here.) Doesn't store the accumulated value or the returned functions in a way that could cause them to be inadvertently modified by other code. (No global variables or other such things.) E.g. if after the example, you added the following code (in a made-up language) where the factory function is called foo: x = foo(1); x(5); foo(3); print x(2.3); It should print 8.3. (There is no need to print the form of the accumulator function returned by foo(3); it's not part of the task at all.) Task Create a function that implements the described rules. It need not handle any special error cases not described above. The simplest way to implement the task as described is typically to use a closure, providing the language supports them. Where it is not possible to hold exactly to the constraints above, describe the deviations.
#ABAP
ABAP
report z_accumulator class acc definition. public section. methods: call importing iv_i type any default 0 exporting ev_r type any, constructor importing iv_d type f. private section. data a_sum type f. endclass.   class acc implementation. method call. add iv_i to a_sum. ev_r = a_sum. endmethod.   start-of-selection.   data: cl_acc type ref to acc, lv_ret2 type f, lv_ret1 type i.   create object cl_acc exporting iv_d = 1. cl_acc->call( exporting iv_i = 5 ). cl_acc->call( exporting iv_i = '2.3' importing ev_r = lv_ret2 ). cl_acc->call( exporting iv_i = 2 importing ev_r = lv_ret1 ). write : / lv_ret2 decimals 2 exponent 0 left-justified, / lv_ret1 left-justified.
http://rosettacode.org/wiki/Align_columns
Align columns
Given a text file of many lines, where fields within a line are delineated by a single 'dollar' character, write a program that aligns each column of fields by ensuring that words in each column are separated by at least one space. Further, allow for each word in a column to be either left justified, right justified, or center justified within its column. Use the following text to test your programs: Given$a$text$file$of$many$lines,$where$fields$within$a$line$ are$delineated$by$a$single$'dollar'$character,$write$a$program that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$ column$are$separated$by$at$least$one$space. Further,$allow$for$each$word$in$a$column$to$be$either$left$ justified,$right$justified,$or$center$justified$within$its$column. Note that:   The example input texts lines may, or may not, have trailing dollar characters.   All columns should share the same alignment.   Consecutive space characters produced adjacent to the end of lines are insignificant for the purposes of the task.   Output text will be viewed in a mono-spaced font on a plain text editor or basic terminal.   The minimum space between columns should be computed from the text and not hard-coded.   It is not a requirement to add separating characters between or around columns. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#AArch64_Assembly
AArch64 Assembly
  /* ARM assembly AARCH64 Raspberry PI 3B or android 64 bits */ /* program alignColumn64.s */   /*******************************************/ /* Constantes file */ /*******************************************/ /* for this file see task include a file in language AArch64 assembly*/ .include "../includeConstantesARM64.inc"   .equ BUFFERSIZE, 16 * 10   /*********************************/ /* Initialized data */ /*********************************/ .data szMessLeft: .asciz "LEFT :\n" szMessRight: .asciz "\nRIGHT :\n" szMessCenter: .asciz "\nCENTER :\n" szCarriageReturn: .asciz "\n"   szLine1: .asciz "Given$a$text$file$of$many$lines,$where$fields$within$a$line$" szLine2: .asciz "are$delineated$by$a$single$'dollar'$character,$write$a$program" szLine3: .asciz "that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$" szLine4: .asciz "column$are$separated$by$at$least$one$space." szLine5: .asciz "Further,$allow$for$each$word$in$a$column$to$be$either$left$" szLine6: .asciz "justified,$right$justified,$or$center$justified$within$its$column."   .align 8 qtbPtLine: .quad szLine1,szLine2,szLine3,szLine4,szLine5,szLine6 .equ NBLINES, (. - qtbPtLine) / 8   /*********************************/ /* UnInitialized data */ /*********************************/ .bss /*********************************/ /* code section */ /*********************************/ .text .global main main: // entry of program ldr x0,qAdrqtbPtLine bl computeMaxiLengthWords mov x19,x0 // column counter ldr x0,qAdrszMessLeft bl affichageMess ldr x0,qAdrqtbPtLine mov x1,x19 // column size bl alignLeft ldr x0,qAdrszMessRight bl affichageMess ldr x0,qAdrqtbPtLine mov x1,x19 // column size bl alignRight ldr x0,qAdrszMessCenter bl affichageMess ldr x0,qAdrqtbPtLine mov x1,x19 // column size bl alignCenter 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 qAdrszMessLeft: .quad szMessLeft qAdrszMessRight: .quad szMessRight qAdrszMessCenter: .quad szMessCenter qAdrqtbPtLine: .quad qtbPtLine /******************************************************************/ /* compute maxi words */ /******************************************************************/ /* x0 contains adresse pointer array */ computeMaxiLengthWords: stp fp,lr,[sp,-16]! // save registres mov x2,#0 // indice pointer array mov x3,#0 // maxi length words 1: ldr x1,[x0,x2,lsl #3] // load pointer mov x4,#0 // length words counter mov x5,#0 // indice line character 2: ldrb w6,[x1,x5] // load a line character cmp x6,#0 // line end ? beq 4f cmp x6,#'$' // separator ? bne 3f cmp x4,x3 csel x3,x4,x3,gt // if greather replace maxi mov x4,#-1 // raz length counter 3: add x4,x4,#1 add x5,x5,#1 // increment character indice b 2b // and loop 4: // end line cmp x4,x3 // compare word counter and maxi csel x3,x4,x3,gt // if greather replace maxi add x2,x2,#1 // increment indice line pointer cmp x2,#NBLINES // maxi ? blt 1b // no -> loop   mov x0,x3 // return maxi length counter 100: ldp fp,lr,[sp],16 // restaur des 2 registres ret   /******************************************************************/ /* align left */ /******************************************************************/ /* x0 contains the address of pointer array*/ /* x1 contains column size */ alignLeft: stp fp,lr,[sp,-16]! // save registres sub sp,sp,#BUFFERSIZE // reserve place for output buffer mov fp,sp mov x5,x0 // array address mov x2,#0 // indice array 1: ldr x3,[x5,x2,lsl #3] // load line pointer mov x4,#0 // line character indice mov x7,#0 // output buffer character indice mov x6,#0 // word lenght 2: ldrb w0,[x3,x4] // load a character line strb w0,[fp,x7] // store in buffer cmp w0,#0 // line end ? beq 6f cmp w0,#'$' // separator ? bne 5f mov x0,#' ' strb w0,[fp,x7] // replace $ by space 3: cmp x6,x1 // length word >= length column bge 4f add x7,x7,#1 mov x0,#' ' strb w0,[fp,x7] // add space to buffer add x6,x6,#1 b 3b // and loop 4: mov x6,#-1 // raz word length 5: add x4,x4,#1 // increment line indice add x7,x7,#1 // increment buffer indice add x6,x6,#1 // increment word length b 2b   6: mov x0,#'\n' strb w0,[fp,x7] // return line add x7,x7,#1 mov x0,#0 strb w0,[fp,x7] // final zéro mov x0,fp bl affichageMess // display output buffer add x2,x2,#1 cmp x2,#NBLINES blt 1b   100: add sp,sp,#BUFFERSIZE ldp fp,lr,[sp],16 // restaur des 2 registres ret /******************************************************************/ /* align right */ /******************************************************************/ /* x0 contains the address of pointer array*/ /* x1 contains column size */ alignRight: stp fp,lr,[sp,-16]! // save registres sub sp,sp,#BUFFERSIZE // reserve place for output buffer mov fp,sp mov x5,x0 // array address mov x2,#0 // indice array 1: ldr x3,[x5,x2,lsl #3] // load line pointer mov x4,#0 // line character indice mov x7,#0 // output buffer character indice mov x6,#0 // word lenght mov x8,x3 // word begin address 2: // compute word length ldrb w0,[x3,x4] // load a character line cmp w0,#0 // line end ? beq 3f cmp w0,#'$' // separator ? beq 3f add x4,x4,#1 // increment line indice add x6,x6,#1 // increment word length b 2b   3: cmp x6,#0 beq 4f sub x6,x1,x6 // compute left spaces to add 4: // loop add spaces to buffer cmp x6,#0 blt 5f mov x0,#' ' strb w0,[fp,x7] // add space to buffer add x7,x7,#1 sub x6,x6,#1 b 4b // and loop 5: mov x9,#0 6: // copy loop word to buffer ldrb w0,[x8,x9] cmp x0,#'$' beq 7f cmp x0,#0 // line end beq 8f strb w0,[fp,x7] add x7,x7,#1 add x9,x9,#1 b 6b 7: add x8,x8,x9 add x8,x8,#1 // new word begin mov x6,#0 // raz word length add x4,x4,#1 // increment line indice b 2b   8: mov x0,#'\n' strb w0,[fp,x7] // return line add x7,x7,#1 mov x0,#0 strb w0,[fp,x7] // final zéro mov x0,fp bl affichageMess // display output buffer add x2,x2,#1 cmp x2,#NBLINES blt 1b   100: add sp,sp,#BUFFERSIZE ldp fp,lr,[sp],16 // restaur des 2 registres ret /******************************************************************/ /* align center */ /******************************************************************/ /* x0 contains the address of pointer array*/ /* x1 contains column size */ alignCenter: stp fp,lr,[sp,-16]! // save registres sub sp,sp,#BUFFERSIZE // reserve place for output buffer mov fp,sp mov x5,x0 // array address mov x2,#0 // indice array 1: ldr x3,[x5,x2,lsl #3] // load line pointer mov x4,#0 // line character indice mov x7,#0 // output buffer character indice mov x6,#0 // word length mov x8,x3 // word begin address 2: // compute word length ldrb w0,[x3,x4] // load a character line cmp w0,#0 // line end ? beq 3f cmp w0,#'$' // separator ? beq 3f add x4,x4,#1 // increment line indice add x6,x6,#1 // increment word length b 2b 3: cmp x6,#0 beq 5f sub x6,x1,x6 // total spaces number to add mov x12,x6 lsr x6,x6,#1 // divise by 2 = left spaces number 4: cmp x6,#0 blt 5f mov x0,#' ' strb w0,[fp,x7] // add space to buffer add x7,x7,#1 // increment output indice sub x6,x6,#1 // decrement number space b 4b // and loop 5: mov x9,#0 6: // copy loop word to buffer ldrb w0,[x8,x9] cmp x0,#'$' // séparator ? beq 7f cmp x0,#0 // line end ? beq 10f strb w0,[fp,x7] add x7,x7,#1 add x9,x9,#1 b 6b 7: lsr x6,x12,#1 // divise total spaces by 2 sub x6,x12,x6 // and compute number spaces to right side 8: // loop to add right spaces cmp x6,#0 ble 9f mov x0,#' ' strb w0,[fp,x7] // add space to buffer add x7,x7,#1 sub x6,x6,#1 b 8b // and loop   9: add x8,x8,x9 add x8,x8,#1 // new address word begin mov x6,#0 // raz word length add x4,x4,#1 // increment line indice b 2b // and loop new word   10: mov x0,#'\n' strb w0,[fp,x7] // return line add x7,x7,#1 mov x0,#0 strb w0,[fp,x7] // final zéro mov x0,fp bl affichageMess // display output buffer add x2,x2,#1 // increment line indice cmp x2,#NBLINES // maxi ? blt 1b // loop   100: add sp,sp,#BUFFERSIZE ldp fp,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/Active_object
Active object
In object-oriented programming an object is active when its state depends on clock. Usually an active object encapsulates a task that updates the object's state. To the outer world the object looks like a normal object with methods that can be called from outside. Implementation of such methods must have a certain synchronization mechanism with the encapsulated task in order to prevent object's state corruption. A typical instance of an active object is an animation widget. The widget state changes with the time, while as an object it has all properties of a normal widget. The task Implement an active integrator object. The object has an input and output. The input can be set using the method Input. The input is a function of time. The output can be queried using the method Output. The object integrates its input over the time and the result becomes the object's output. So if the input is K(t) and the output is S, the object state S is changed to S + (K(t1) + K(t0)) * (t1 - t0) / 2, i.e. it integrates K using the trapeze method. Initially K is constant 0 and S is 0. In order to test the object: set its input to sin (2π f t), where the frequency f=0.5Hz. The phase is irrelevant. wait 2s set the input to constant 0 wait 0.5s Verify that now the object's output is approximately 0 (the sine has the period of 2s). The accuracy of the result will depend on the OS scheduler time slicing and the accuracy of the clock.
#C.2B.2B
C++
#include <atomic> #include <chrono> #include <cmath> #include <iostream> #include <mutex> #include <thread>   using namespace std::chrono_literals;   class Integrator { public: using clock_type = std::chrono::high_resolution_clock; using dur_t = std::chrono::duration<double>; using func_t = double(*)(double);   explicit Integrator(func_t f = nullptr); ~Integrator(); void input(func_t new_input); double output() { return integrate(); }   private: std::atomic_flag continue_; std::mutex mutex; std::thread worker;   func_t func; double state = 0; //Improves precision by reducing sin result error on large values clock_type::time_point const beginning = clock_type::now(); clock_type::time_point t_prev = beginning;   void do_work(); double integrate(); };   Integrator::Integrator(func_t f) : func(f) { continue_.test_and_set(); worker = std::thread(&Integrator::do_work, this); }   Integrator::~Integrator() { continue_.clear(); worker.join(); }   void Integrator::input(func_t new_input) { integrate(); std::lock_guard<std::mutex> lock(mutex); func = new_input; }   void Integrator::do_work() { while(continue_.test_and_set()) { integrate(); std::this_thread::sleep_for(1ms); } }   double Integrator::integrate() { std::lock_guard<std::mutex> lock(mutex); auto now = clock_type::now(); dur_t start = t_prev - beginning; dur_t fin = now - beginning; if(func) state += (func(start.count()) + func(fin.count())) * (fin - start).count() / 2; t_prev = now; return state; }   double sine(double time) { constexpr double PI = 3.1415926535897932; return std::sin(2 * PI * 0.5 * time); }   int main() { Integrator foo(sine); std::this_thread::sleep_for(2s); foo.input(nullptr); std::this_thread::sleep_for(500ms); std::cout << foo.output(); }
http://rosettacode.org/wiki/Achilles_numbers
Achilles numbers
This page uses content from Wikipedia. The original article was at Achilles number. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) An Achilles number is a number that is powerful but imperfect. Named after Achilles, a hero of the Trojan war, who was also powerful but imperfect. A positive integer n is a powerful number if, for every prime factor p of n, p2 is also a divisor. In other words, every prime factor appears at least squared in the factorization. All Achilles numbers are powerful. However, not all powerful numbers are Achilles numbers: only those that cannot be represented as mk, where m and k are positive integers greater than 1. A strong Achilles number is an Achilles number whose Euler totient (𝜑) is also an Achilles number. E.G. 108 is a powerful number. Its prime factorization is 22 × 33, and thus its prime factors are 2 and 3. Both 22 = 4 and 32 = 9 are divisors of 108. However, 108 cannot be represented as mk, where m and k are positive integers greater than 1, so 108 is an Achilles number. 360 is not an Achilles number because it is not powerful. One of its prime factors is 5 but 360 is not divisible by 52 = 25. Finally, 784 is not an Achilles number. It is a powerful number, because not only are 2 and 7 its only prime factors, but also 22 = 4 and 72 = 49 are divisors of it. Nonetheless, it is a perfect power; its square root is an even integer, so it is not an Achilles number. 500 = 22 × 53 is a strong Achilles number as its Euler totient, 𝜑(500), is 200 = 23 × 52 which is also an Achilles number. Task Find and show the first 50 Achilles numbers. Find and show at least the first 20 strong Achilles numbers. For at least 2 through 5, show the count of Achilles numbers with that many digits. See also Wikipedia: Achilles number OEIS:A052486 - Achilles numbers - powerful but imperfect numbers OEIS:A194085 - Strong Achilles numbers: Achilles numbers m such that phi(m) is also an Achilles number Related task: Powerful numbers Related task: Totient function
#C.2B.2B
C++
#include <algorithm> #include <chrono> #include <cmath> #include <cstdint> #include <iomanip> #include <iostream> #include <vector>   #include <boost/multiprecision/cpp_int.hpp>   using boost::multiprecision::uint128_t;   template <typename T> void unique_sort(std::vector<T>& vector) { std::sort(vector.begin(), vector.end()); vector.erase(std::unique(vector.begin(), vector.end()), vector.end()); }   auto perfect_powers(uint128_t n) { std::vector<uint128_t> result; for (uint128_t i = 2, s = sqrt(n); i <= s; ++i) for (uint128_t p = i * i; p < n; p *= i) result.push_back(p); unique_sort(result); return result; }   auto achilles(uint128_t from, uint128_t to, const std::vector<uint128_t>& pps) { std::vector<uint128_t> result; auto c = static_cast<uint128_t>(std::cbrt(static_cast<double>(to / 4))); auto s = sqrt(to / 8); for (uint128_t b = 2; b <= c; ++b) { uint128_t b3 = b * b * b; for (uint128_t a = 2; a <= s; ++a) { uint128_t p = b3 * a * a; if (p >= to) break; if (p >= from && !binary_search(pps.begin(), pps.end(), p)) result.push_back(p); } } unique_sort(result); return result; }   uint128_t totient(uint128_t n) { uint128_t tot = n; if ((n & 1) == 0) { while ((n & 1) == 0) n >>= 1; tot -= tot >> 1; } for (uint128_t p = 3; p * p <= n; p += 2) { if (n % p == 0) { while (n % p == 0) n /= p; tot -= tot / p; } } if (n > 1) tot -= tot / n; return tot; }   int main() { auto start = std::chrono::high_resolution_clock::now();   const uint128_t limit = 1000000000000000;   auto pps = perfect_powers(limit); auto ach = achilles(1, 1000000, pps);   std::cout << "First 50 Achilles numbers:\n"; for (size_t i = 0; i < 50 && i < ach.size(); ++i) std::cout << std::setw(4) << ach[i] << ((i + 1) % 10 == 0 ? '\n' : ' ');   std::cout << "\nFirst 50 strong Achilles numbers:\n"; for (size_t i = 0, count = 0; count < 50 && i < ach.size(); ++i) if (binary_search(ach.begin(), ach.end(), totient(ach[i]))) std::cout << std::setw(6) << ach[i] << (++count % 10 == 0 ? '\n' : ' ');   int digits = 2; std::cout << "\nNumber of Achilles numbers with:\n"; for (uint128_t from = 1, to = 100; to <= limit; to *= 10, ++digits) { size_t count = achilles(from, to, pps).size(); std::cout << std::setw(2) << digits << " digits: " << count << '\n'; from = to; }   auto end = std::chrono::high_resolution_clock::now(); std::chrono::duration<double> duration(end - start); std::cout << "\nElapsed time: " << duration.count() << " seconds\n"; }
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
#Elixir
Elixir
defmodule Proper do def divisors(1), do: [] def divisors(n), do: [1 | divisors(2,n,:math.sqrt(n))] |> Enum.sort   defp divisors(k,_n,q) when k>q, do: [] defp divisors(k,n,q) when rem(n,k)>0, do: divisors(k+1,n,q) defp divisors(k,n,q) when k * k == n, do: [k | divisors(k+1,n,q)] defp divisors(k,n,q) , do: [k,div(n,k) | divisors(k+1,n,q)] end   defmodule Aliquot do def sequence(n, maxlen\\16, maxterm\\140737488355328) def sequence(0, _maxlen, _maxterm), do: "terminating" def sequence(n, maxlen, maxterm) do {msg, s} = sequence(n, maxlen, maxterm, [n]) {msg, Enum.reverse(s)} end   defp sequence(n, maxlen, maxterm, s) when length(s) < maxlen and n < maxterm do m = Proper.divisors(n) |> Enum.sum cond do m in s -> case {m, List.last(s), hd(s)} do {x,x,_} -> case length(s) do 1 -> {"perfect", s} 2 -> {"amicable", s} _ -> {"sociable of length #{length(s)}", s} end {x,_,x} -> {"aspiring", [m | s]} _ -> {"cyclic back to #{m}", [m | s]} end m == 0 -> {"terminating", [0 | s]} true -> sequence(m, maxlen, maxterm, [m | s]) end end defp sequence(_, _, _, s), do: {"non-terminating", s} end   Enum.each(1..10, fn n -> {msg, s} = Aliquot.sequence(n)  :io.fwrite("~7w:~21s: ~p~n", [n, msg, s]) end) IO.puts "" [11, 12, 28, 496, 220, 1184, 12496, 1264460, 790, 909, 562, 1064, 1488, 15355717786080] |> Enum.each(fn n -> {msg, s} = Aliquot.sequence(n) if n<10000000, do: :io.fwrite("~7w:~21s: ~p~n", [n, msg, s]), else: :io.fwrite("~w: ~s: ~p~n", [n, msg, s]) end)
http://rosettacode.org/wiki/Add_a_variable_to_a_class_instance_at_runtime
Add a variable to a class instance at runtime
Demonstrate how to dynamically add variables to an object (a class instance) at runtime. This is useful when the methods/variables of an instance are based on a data file that isn't available until runtime. Hal Fulton gives an example of creating an OO CSV parser at An Exercise in Metaprogramming with Ruby. This is referred to as "monkeypatching" by Pythonistas and some others.
#Julia
Julia
  {"phoneNumbers": [ { "type": "home", "number": "212 555-1234" }, { "type": "office", "number": "646 555-4567" }, { "type": "mobile", "number": "123 456-7890" }]}  
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.
#Kotlin
Kotlin
// version 1.1.2   class SomeClass { val runtimeVariables = mutableMapOf<String, Any>() }   fun main(args: Array<String>) { val sc = SomeClass() println("Create two variables at runtime: ") for (i in 1..2) { println(" Variable #$i:") print(" Enter name  : ") val name = readLine()!! print(" Enter value : ") val value = readLine()!! sc.runtimeVariables.put(name, value) println() } while (true) { print("Which variable do you want to inspect ? ") val name = readLine()!! val value = sc.runtimeVariables[name] if (value == null) { println("There is no variable of that name, try again") } else { println("Its value is '${sc.runtimeVariables[name]}'") return } } }
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.
#Latitude
Latitude
myObject := Object clone.   ;; Name known at compile-time. myObject foo := "bar".   ;; Name known at runtime. myObject slot '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.
#Lua
Lua
t = {} print(t) f = function() end print(f) c = coroutine.create(function() end) print(c) u = io.open("/dev/null","w") print(u) print(_G, _ENV) -- global/local environments (are same here) print(string.format("%p %p %p", print, string, string.format)) -- themselves formatted as pointers
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.
#Maple
Maple
> addressof( x ); 18446884674469911422
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.
#Modula-2
Modula-2
MODULE GetAddress;   FROM SYSTEM IMPORT ADR; FROM InOut IMPORT WriteInt, WriteLn;   VAR var : INTEGER; adr : LONGINT; BEGIN adr := ADR(var); (*get the address*) WriteInt(adr, 0); WriteLn; END GetAddress.
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.
#CoffeeScript
CoffeeScript
pascal = () -> a = [] return () -> if a.length is 0 then a = [1] else b = (a[i] + a[i+1] for i in [0 ... a.length - 1]) a = [1].concat(b).concat [1]   show = (a) -> show_x = (e) -> switch e when 0 then "" when 1 then "x" else "x^#{e}"   degree = a.length - 1 str = "(x - 1)^#{degree} =" sgn = 1   for i in [0...a.length] str += ' ' + (if sgn > 0 then "+" else "-") + ' ' + a[i] + show_x(degree - i) sgn = -sgn   return str   primerow = (row) -> degree = row.length - 1 row[1 ... degree].every (x) -> x % degree is 0   p = pascal() console.log show p() for i in [0..7]   p = pascal() p(); p() # skip 0 and 1   primes = (i+1 for i in [1..49] when primerow p())   console.log "" console.log "The primes upto 50 are: #{primes}"
http://rosettacode.org/wiki/Additive_primes
Additive primes
Definitions In mathematics, additive primes are prime numbers for which the sum of their decimal digits are also primes. Task Write a program to determine (and show here) all additive primes less than 500. Optionally, show the number of additive primes. Also see   the OEIS entry:   A046704 additive primes.   the prime-numbers entry:   additive primes.   the geeks for geeks entry: additive prime number.   the prime-numbers fandom: additive primes.
#Delphi
Delphi
proc sieve([*] bool prime) void: word max, p, c; max := dim(prime,1)-1; prime[0] := false; prime[1] := false; for p from 2 upto max do prime[p] := true od; for p from 2 upto max/2 do for c from p*2 by p upto max do prime[c] := false od od corp   proc digit_sum(word num) byte: byte sum; sum := 0; while sum := sum + num % 10; num := num / 10; num /= 0 do od; sum corp   proc main() void: word MAX = 500; word p, n; [MAX]bool prime; sieve(prime); n := 0; for p from 2 upto MAX-1 do if prime[p] and prime[digit_sum(p)] then write(p:4); n := n + 1; if n % 20 = 0 then writeln() fi fi od; writeln(); writeln("There are ", n, " additive primes below ", MAX) corp
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.
#Draco
Draco
proc sieve([*] bool prime) void: word max, p, c; max := dim(prime,1)-1; prime[0] := false; prime[1] := false; for p from 2 upto max do prime[p] := true od; for p from 2 upto max/2 do for c from p*2 by p upto max do prime[c] := false od od corp   proc digit_sum(word num) byte: byte sum; sum := 0; while sum := sum + num % 10; num := num / 10; num /= 0 do od; sum corp   proc main() void: word MAX = 500; word p, n; [MAX]bool prime; sieve(prime); n := 0; for p from 2 upto MAX-1 do if prime[p] and prime[digit_sum(p)] then write(p:4); n := n + 1; if n % 20 = 0 then writeln() fi fi od; writeln(); writeln("There are ", n, " additive primes below ", MAX) corp
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
#Racket
Racket
  #lang racket   ;; Using short names to make the code line up nicely (struct N (color left value right) #:prefab)   (define (balance t) (match t [(N 'B (N 'R (N 'R a x b) y c) z d) (N 'R (N 'B a x b) y (N 'B c z d))] [(N 'B (N 'R a x (N 'R b y c)) z d) (N 'R (N 'B a x b) y (N 'B c z d))] [(N 'B a x (N 'R (N 'R b y c) z d)) (N 'R (N 'B a x b) y (N 'B c z d))] [(N 'B a x (N 'R b y (N 'R c z d))) (N 'R (N 'B a x b) y (N 'B c z d))] [else t]))   (define (insert x s) (define (ins t) (match t ['empty (N 'R 'empty x 'empty)] [(N c l v r) (cond [(< x v) (balance (N c (ins l) v r))] [(> x v) (balance (N c l v (ins r)))] [else t])])) (match (ins s) [(N _ l v r) (N 'B l v r)]))   (define (visualize t0) (let loop ([t t0] [last? #t] [indent '()]) (define (I mid last) (cond [(eq? t t0) ""] [last? mid] [else last])) (for-each display (reverse indent)) (printf "~a~a[~a]\n" (I "\\-" "+-") (N-value t) (N-color t)) (define subs (filter N? (list (N-left t) (N-right t)))) (for ([s subs] [n (in-range (sub1 (length subs)) -1 -1)]) (loop s (zero? n) (cons (I " " "| ") indent)))))   (visualize (for/fold ([t 'empty]) ([i 16]) (insert i t)))  
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
#Raku
Raku
enum RedBlack <R B>;   multi balance(B,[R,[R,$a,$x,$b],$y,$c],$z,$d) { [R,[B,$a,$x,$b],$y,[B,$c,$z,$d]] } multi balance(B,[R,$a,$x,[R,$b,$y,$c]],$z,$d) { [R,[B,$a,$x,$b],$y,[B,$c,$z,$d]] } multi balance(B,$a,$x,[R,[R,$b,$y,$c],$z,$d]) { [R,[B,$a,$x,$b],$y,[B,$c,$z,$d]] } multi balance(B,$a,$x,[R,$b,$y,[R,$c,$z,$d]]) { [R,[B,$a,$x,$b],$y,[B,$c,$z,$d]] }   multi balance($col, $a, $x, $b) { [$col, $a, $x, $b] }   multi ins( $x, @s [$col, $a, $y, $b] ) { when $x before $y { balance $col, ins($x, $a), $y, $b } when $x after $y { balance $col, $a, $y, ins($x, $b) } default { @s } } multi ins( $x, Any:U ) { [R, Any, $x, Any] }   multi insert( $x, $s ) { [B, |ins($x,$s)[1..3]]; }   sub MAIN { my $t = Any; $t = insert($_, $t) for (1..10).pick(*); say $t.gist; }
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
#Go
Go
package main   import "fmt"   func kPrime(n, k int) bool { nf := 0 for i := 2; i <= n; i++ { for n%i == 0 { if nf == k { return false } nf++ n /= i } } return nf == k }   func gen(k, n int) []int { r := make([]int, n) n = 2 for i := range r { for !kPrime(n, k) { n++ } r[i] = n n++ } return r }   func main() { for k := 1; k <= 5; k++ { fmt.Println(k, gen(k, 10)) } }
http://rosettacode.org/wiki/Anagrams
Anagrams
When two or more words are composed of the same characters, but in a different order, they are called anagrams. Task[edit] Using the word list at   http://wiki.puzzlers.org/pub/wordlists/unixdict.txt, find the sets of words that share the same characters that contain the most words in them. Related tasks Word plays Ordered words Palindrome detection Semordnilap Anagrams Anagrams/Deranged anagrams Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#COBOL
COBOL
*> TECTONICS *> wget http://wiki.puzzlers.org/pub/wordlists/unixdict.txt *> or visit https://sourceforge.net/projects/souptonuts/files *> or snag ftp://ftp.openwall.com/pub/wordlists/all.gz *> for a 5 million all language word file (a few phrases) *> cobc -xj anagrams.cob [-DMOSTWORDS -DMOREWORDS -DALLWORDS] *> *************************************************************** identification division. program-id. anagrams.   environment division. configuration section. repository. function all intrinsic.   input-output section. file-control. select words-in assign to wordfile organization is line sequential status is words-status .   REPLACE ==:LETTERS:== BY ==42==.   data division. file section. fd words-in record is varying from 1 to :LETTERS: characters depending on word-length. 01 word-record. 05 word-data pic x occurs 0 to :LETTERS: times depending on word-length.   working-storage section. >>IF ALLWORDS DEFINED 01 wordfile constant as "/usr/local/share/dict/all.words". 01 max-words constant as 4802100.   >>ELSE-IF MOSTWORDS DEFINED 01 wordfile constant as "/usr/local/share/dict/linux.words". 01 max-words constant as 628000.   >>ELSE-IF MOREWORDS DEFINED 01 wordfile constant as "/usr/share/dict/words". 01 max-words constant as 100000.   >>ELSE 01 wordfile constant as "unixdict.txt". 01 max-words constant as 26000. >>END-IF   *> The 5 million word file needs to restrict the word length >>IF ALLWORDS DEFINED 01 max-letters constant as 26. >>ELSE 01 max-letters constant as :LETTERS:. >>END-IF   01 word-length pic 99 comp-5. 01 words-status pic xx. 88 ok-status values '00' thru '09'. 88 eof-status value '10'.   *> sortable word by letter table 01 letter-index usage index. 01 letter-table. 05 letters occurs 1 to max-letters times depending on word-length ascending key letter indexed by letter-index. 10 letter pic x.   *> table of words 01 sorted-index usage index. 01 word-table. 05 word-list occurs 0 to max-words times depending on word-tally ascending key sorted-word indexed by sorted-index. 10 match-count pic 999 comp-5. 10 this-word pic x(max-letters). 10 sorted-word pic x(max-letters). 01 sorted-display pic x(10).   01 interest-table. 05 interest-list pic 9(8) comp-5 occurs 0 to max-words times depending on interest-tally.   01 outer pic 9(8) comp-5. 01 inner pic 9(8) comp-5. 01 starter pic 9(8) comp-5. 01 ender pic 9(8) comp-5. 01 word-tally pic 9(8) comp-5. 01 interest-tally pic 9(8) comp-5. 01 tally-display pic zz,zzz,zz9.   01 most-matches pic 99 comp-5. 01 matches pic 99 comp-5. 01 match-display pic z9.   *> timing display 01 time-stamp. 05 filler pic x(11). 05 timer-hours pic 99. 05 filler pic x. 05 timer-minutes pic 99. 05 filler pic x. 05 timer-seconds pic 99. 05 filler pic x. 05 timer-subsec pic v9(6). 01 timer-elapsed pic 9(6)v9(6). 01 timer-value pic 9(6)v9(6). 01 timer-display pic zzz,zz9.9(6).   *> *************************************************************** procedure division. main-routine.   >>IF ALLWORDS DEFINED display "** Words limited to " max-letters " letters **" >>END-IF   perform show-time   perform load-words perform find-most perform display-result   perform show-time goback .   *> *************************************************************** load-words. open input words-in if not ok-status then display "error opening " wordfile upon syserr move 1 to return-code goback end-if   perform until exit read words-in if eof-status then exit perform end-if if not ok-status then display wordfile " read error: " words-status upon syserr end-if   if word-length equal zero then exit perform cycle end-if   >>IF ALLWORDS DEFINED move min(word-length, max-letters) to word-length >>END-IF   add 1 to word-tally move word-record to this-word(word-tally) letter-table sort letters ascending key letter move letter-table to sorted-word(word-tally) end-perform   move word-tally to tally-display display trim(tally-display) " words" with no advancing   close words-in if not ok-status then display "error closing " wordfile upon syserr move 1 to return-code end-if   *> sort word list by anagram check field sort word-list ascending key sorted-word .   *> first entry in a list will end up with highest match count find-most. perform varying outer from 1 by 1 until outer > word-tally move 1 to matches add 1 to outer giving starter perform varying inner from starter by 1 until sorted-word(inner) not equal sorted-word(outer) add 1 to matches end-perform if matches > most-matches then move matches to most-matches initialize interest-table all to value move 0 to interest-tally end-if move matches to match-count(outer) if matches = most-matches then add 1 to interest-tally move outer to interest-list(interest-tally) end-if end-perform .   *> only display the words with the most anagrams display-result. move interest-tally to tally-display move most-matches to match-display display ", most anagrams: " trim(match-display) ", with " trim(tally-display) " set" with no advancing if interest-tally not equal 1 then display "s" with no advancing end-if display " of interest"   perform varying outer from 1 by 1 until outer > interest-tally move sorted-word(interest-list(outer)) to sorted-display display sorted-display " [" trim(this-word(interest-list(outer))) with no advancing add 1 to interest-list(outer) giving starter add most-matches to interest-list(outer) giving ender perform varying inner from starter by 1 until inner = ender display ", " trim(this-word(inner)) with no advancing end-perform display "]" end-perform .   *> elapsed time show-time. move formatted-current-date("YYYY-MM-DDThh:mm:ss.ssssss") to time-stamp compute timer-value = timer-hours * 3600 + timer-minutes * 60 + timer-seconds + timer-subsec if timer-elapsed = 0 then display time-stamp move timer-value to timer-elapsed else if timer-value < timer-elapsed then add 86400 to timer-value end-if subtract timer-elapsed from timer-value move timer-value to timer-display display time-stamp ", " trim(timer-display) " seconds" end-if .   end program anagrams.
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
#Pascal
Pascal
  Program Bearings; { Reads pairs of angles from a file and subtracts them }   Const fileName = 'angles.txt';   Type degrees = real;   Var subtrahend, minuend: degrees; angleFile: text;   function Simplify(angle: degrees): degrees; { Returns an number in the range [-180.0, 180.0] } begin while angle > 180.0 do angle := angle - 360.0; while angle < -180.0 do angle := angle + 360.0; Simplify := angle end;   function Difference(b1, b2: degrees): degrees; { Subtracts b1 from b2 and returns a simplified result } begin Difference := Simplify(b2 - b1) end;   procedure Subtract(b1, b2: degrees); { Subtracts b1 from b2 and shows the whole equation onscreen } var b3: degrees; begin b3 := Difference(b1, b2); writeln(b2:20:11, ' - ', b1:20:11, ' = ', b3:20:11) end;   Begin assign(angleFile, fileName); reset(angleFile); while not eof(angleFile) do begin readln(angleFile, subtrahend, minuend); Subtract(subtrahend, minuend) end; close(angleFile) End.  
http://rosettacode.org/wiki/Anagrams/Deranged_anagrams
Anagrams/Deranged anagrams
Two or more words are said to be anagrams if they have the same characters, but in a different order. By analogy with derangements we define a deranged anagram as two words with the same characters, but in which the same character does not appear in the same position in both words. Task[edit] Use the word list at unixdict to find and display the longest deranged anagram. Related tasks Permutations/Derangements Best shuffle Word plays Ordered words Palindrome detection Semordnilap Anagrams Anagrams/Deranged anagrams Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#PureBasic
PureBasic
Structure anagram word.s letters.s EndStructure   Structure wordList List words.anagram() EndStructure   #True = 1 #False = 0   Procedure.s sortLetters(*word.Character, wordLength) ;returns a string with the letters of a word sorted Protected Dim letters.c(wordLength) Protected *letAdr = @letters() CopyMemoryString(*word, @*letAdr) SortArray(letters(), #PB_Sort_Ascending, 0, wordLength - 1) ProcedureReturn PeekS(@letters(), wordLength) EndProcedure   ;Compare a list of anagrams for derangement. Procedure isDeranged(List anagram.s()) ;If a pair of deranged anagrams is found return #True ;and and modify the list to include the pair of deranged anagrams. Protected i, length, word.s, *ptrAnagram, isDeranged Protected NewList deranged.s() FirstElement(anagram()) length = Len(anagram()) Repeat word = anagram() *ptrAnagram = @anagram()   While NextElement(anagram()) isDeranged = #True For i = 1 To length If Mid(word, i, 1) = Mid(anagram(), i, 1) isDeranged = #False Break ;exit for/next EndIf Next   If isDeranged AddElement(deranged()) deranged() = anagram() AddElement(deranged()) deranged() = word CopyList(deranged(), anagram()) ProcedureReturn #True ;deranged anagram found EndIf Wend ChangeCurrentElement(anagram(), *ptrAnagram) Until Not NextElement(anagram())   ProcedureReturn #False ;deranged anagram not found EndProcedure   If OpenConsole() ;word file is assumed to be in the same directory If Not ReadFile(0,"unixdict.txt"): End: EndIf   Define maxWordSize = 0, word.s, length Dim wordlists.wordList(maxWordSize)   ;Read word file and create separate lists of anagrams and their original ;words by length. While Not Eof(0) word = ReadString(0) length = Len(word) If length > maxWordSize maxWordSize = length Redim wordlists.wordList(maxWordSize) EndIf AddElement(wordlists(length)\words()) wordlists(length)\words()\word = word wordlists(length)\words()\letters = sortLetters(@word, length) Wend CloseFile(0)   Define offset = OffsetOf(anagram\letters), option = #PB_Sort_Ascending Define sortType = #PB_Sort_String Define letters.s, foundDeranged NewList anagram.s() ;start search from largest to smallest For length = maxWordSize To 2 Step -1   If FirstElement(wordlists(length)\words()) ;only examine lists with words ;sort words to place anagrams next to each other SortStructuredList(wordlists(length)\words(), option, offset, sortType)   With wordlists(length)\words() letters = \letters AddElement(anagram()): anagram() = \word   ;Compose sets of anagrams and check for derangement with remaining ;words in current list. While NextElement(wordlists(length)\words()) ;Check for end of a set of anagrams? If letters <> \letters   ;if more than one word in a set of anagrams check for derangement If ListSize(anagram()) > 1 If isDeranged(anagram()) foundDeranged = #True ;found deranged anagrams, stop processing Break 2 ;exit while/wend and for/next EndIf EndIf   letters = \letters ;setup for next set of anagrams ClearList(anagram()) EndIf   AddElement(anagram()): anagram() = \word Wend EndWith   EndIf   ClearList(anagram()) Next   ;report results If foundDeranged Print("Largest 'Deranged' anagrams found are of length ") PrintN(Str(length) + ":" + #CRLF$) ForEach anagram() PrintN(" " + anagram()) Next Else PrintN("No 'Deranged' anagrams were found." + #CRLF$) EndIf   Print(#CRLF$ + #CRLF$ + "Press ENTER to exit"): Input() CloseConsole() EndIf
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.
#Nemerle
Nemerle
using System; using System.Console;   module Fib { Fib(n : long) : long { def fib(m : long) { |0 => 1 |1 => 1 |_ => fib(m - 1) + fib(m - 2) }   match(n) { |n when (n < 0) => throw ArgumentException("Fib() not defined on negative numbers") |_ => fib(n) } }   Main() : void { foreach (i in [-2 .. 10]) { try {WriteLine("{0}", Fib(i));} catch {|e is ArgumentException => WriteLine(e.Message)} } } }
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.
#MAD
MAD
NORMAL MODE IS INTEGER DIMENSION DIVS(20000) PRINT COMMENT $ AMICABLE PAIRS$   R CALCULATE SUM OF DIVISORS OF N INTERNAL FUNCTION(N) ENTRY TO DIVSUM. DS = 0 THROUGH SUMMAT, FOR DIVC=1, 1, DIVC.GE.N SUMMAT WHENEVER N/DIVC*DIVC.E.N, DS = DS+DIVC FUNCTION RETURN DS END OF FUNCTION   R CALCULATE SUM OF DIVISORS FOR ALL NUMBERS 1..20000 THROUGH MEMO, FOR I=1, 1, I.GE.20000 MEMO DIVS(I) = DIVSUM.(I)   R FIND ALL MATCHING PAIRS THROUGH CHECK, FOR I=1, 1, I.GE.20000 THROUGH CHECK, FOR J=1, 1, J.GE.I CHECK WHENEVER DIVS(I).E.J .AND. DIVS(J).E.I, 0 PRINT FORMAT AMI,I,J   VECTOR VALUES AMI = $I6,I6*$ END OF PROGRAM
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.
#Tcl
Tcl
package require Tk set s "Hello World! " set dir 0 # Periodic animation callback proc animate {} { global dir s if {$dir} { set s [string range $s 1 end][string index $s 0] } else { set s [string index $s end][string range $s 0 end-1] } # We will run this code ~8 times a second (== 125ms delay) after 125 animate } # Make the label (constant width font looks better) pack [label .l -textvariable s -font {Courier 14}] # Make a mouse click reverse the direction bind .l <Button-1> {set dir [expr {!$dir}]} # Start the animation animate