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/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.
#Phix
Phix
-- -- demo\rosetta\animate_pendulum.exw -- ================================= -- -- Author Pete Lomax, March 2017 -- -- Port of animate_pendulum.exw from arwen to pGUI, which is now -- preserved as a comment below (in the distro version only). -- -- With help from lesterb, updates now in timer_cb not redraw_cb, -- variables better named, and velocity problem sorted, July 2018. -- constant full = false -- set true for full swing to near-vertical. -- false performs swing to horizontal only. -- (adjusts the starting angle, pivot point, -- and canvas size, only.) include pGUI.e Ihandle dlg, canvas, timer cdCanvas cdcanvas constant g = 50 atom angle = iff(full?PI-0.01:PI/2), -- (near_vertical | horiz) velocity = 0 integer w = 0, h = 0, len = 0 function redraw_cb(Ihandle /*ih*/, integer /*posx*/, /*posy*/) {w, h} = IupGetIntInt(canvas, "DRAWSIZE") cdCanvasActivate(cdcanvas) cdCanvasClear(cdcanvas) -- new suspension point: integer sX = floor(w/2) integer sY = floor(h/iff(full?2:16)) -- (mid | top) -- repaint: integer eX = floor(len*sin(angle)+sX) integer eY = floor(len*cos(angle)+sY) cdCanvasSetForeground(cdcanvas, CD_CYAN) cdCanvasLine(cdcanvas, sX, h-sY, eX, h-eY) cdCanvasSetForeground(cdcanvas, CD_DARK_GREEN) cdCanvasSector(cdcanvas, sX, h-sY, 5, 5, 0, 360) cdCanvasSetForeground(cdcanvas, CD_BLUE) cdCanvasSector(cdcanvas, eX, h-eY, 35, 35, 0, 360) cdCanvasFlush(cdcanvas) return IUP_DEFAULT end function function timer_cb(Ihandle /*ih*/) if w!=0 then integer newlen = floor(w/2)-30 if newlen!=len then len = newlen atom tmp = 2*g*len*(cos(angle)) velocity = iff(tmp<0?0:sqrt(tmp)*sign(velocity)) end if atom dt = 0.2/w atom acceleration = -len*sin(angle)*g velocity += dt*acceleration angle += dt*velocity IupUpdate(canvas) end if return IUP_IGNORE end function function map_cb(Ihandle ih) atom res = IupGetDouble(NULL, "SCREENDPI")/25.4 IupGLMakeCurrent(canvas) if platform()=JS then cdcanvas = cdCreateCanvas(CD_IUP, canvas) else cdcanvas = cdCreateCanvas(CD_GL, "10x10 %g", {res}) end if cdCanvasSetBackground(cdcanvas, CD_PARCHMENT) return IUP_DEFAULT end function function canvas_resize_cb(Ihandle /*canvas*/) integer {canvas_width, canvas_height} = IupGetIntInt(canvas, "DRAWSIZE") atom res = IupGetDouble(NULL, "SCREENDPI")/25.4 cdCanvasSetAttribute(cdcanvas, "SIZE", "%dx%d %g", {canvas_width, canvas_height, res}) return IUP_DEFAULT end function procedure main() IupOpen() canvas = IupGLCanvas() IupSetAttribute(canvas, "RASTERSIZE", iff(full?"640x640":"640x340")) -- (fit 360|180) IupSetCallback(canvas, "MAP_CB", Icallback("map_cb")) IupSetCallback(canvas, "ACTION", Icallback("redraw_cb")) IupSetCallback(canvas, "RESIZE_CB", Icallback("canvas_resize_cb")) timer = IupTimer(Icallback("timer_cb"), 20) dlg = IupDialog(canvas) IupSetAttribute(dlg, "TITLE", "Animated Pendulum") IupShow(dlg) IupSetAttribute(canvas, "RASTERSIZE", NULL) if platform()!=JS then IupMainLoop() IupClose() end if end procedure main()
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.
#Factor
Factor
USING: backtrack continuations kernel prettyprint sequences ; IN: amb   CONSTANT: words { { "the" "that" "a" } { "frog" "elephant" "thing" } { "walked" "treaded" "grows" } { "slowly" "quickly" } }   : letters-match? ( str1 str2 -- ? ) [ last ] [ first ] bi* = ;   : sentence-match? ( seq -- ? ) dup rest [ letters-match? ] 2all? ;   : select ( seq -- seq' ) [ amb-lazy ] map ;   : search ( -- ) words select dup sentence-match? [ " " join ] [ fail ] if . ;   MAIN: search
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.
#smart_BASIC
smart BASIC
PRINT "Current directory: ";CURRENT_DIR$() PRINT PRINT "Folders:" PRINT DIR "/" LIST DIRS a$,c FOR n = 0 TO c-1 PRINT ,a$(n) NEXT n PRINT PRINT "Files:" PRINT DIR "/" LIST FILES a$,c FOR n = 0 TO c-1 PRINT ,a$(n) NEXT n
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.
#Tcl
Tcl
package require ldap set conn [ldap::connect $host $port] ldap::bind $conn $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.
#VBScript
VBScript
Set objConn = CreateObject("ADODB.Connection") Set objCmd = CreateObject("ADODB.Command") objConn.Provider = "ADsDSOObject" objConn.Open
http://rosettacode.org/wiki/Active_Directory/Connect
Active Directory/Connect
The task is to establish a connection to an Active Directory or Lightweight Directory Access Protocol server.
#Wren
Wren
/* active_directory_connect.wren */   foreign class LDAP { construct init(host, port) {}   foreign simpleBindS(name, password)   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)   // do something here   ld.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.
#ActionScript
ActionScript
//Throw an error if a non-number argument is used. (typeof evaluates to // "number" for both integers and reals) function checkType(obj:Object):void { if(typeof obj != "number") throw new ArgumentError("Expected integer or float argument. Recieved " + typeof obj); } function accumulator(sum:Object):Function { checkType(sum); return function(n:Object):Object {checkType(n); return sum += n}; } var acc:Function=accumulator(2); trace(acc(10)); trace(acc(4)); trace(acc("123")); //This causes an ArgumentError to be thrown.
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.
#Ada
Ada
with Accumulator; with Ada.Text_IO; use Ada.Text_IO;   procedure Example is package A is new Accumulator; package B is new Accumulator; begin Put_Line (Integer'Image (A.The_Function (5))); Put_Line (Integer'Image (B.The_Function (3))); Put_Line (Float'Image (A.The_Function (2.3))); end;
http://rosettacode.org/wiki/Align_columns
Align columns
Given a text file of many lines, where fields within a line are delineated by a single 'dollar' character, write a program that aligns each column of fields by ensuring that words in each column are separated by at least one space. Further, allow for each word in a column to be either left justified, right justified, or center justified within its column. Use the following text to test your programs: Given$a$text$file$of$many$lines,$where$fields$within$a$line$ are$delineated$by$a$single$'dollar'$character,$write$a$program that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$ column$are$separated$by$at$least$one$space. Further,$allow$for$each$word$in$a$column$to$be$either$left$ justified,$right$justified,$or$center$justified$within$its$column. Note that:   The example input texts lines may, or may not, have trailing dollar characters.   All columns should share the same alignment.   Consecutive space characters produced adjacent to the end of lines are insignificant for the purposes of the task.   Output text will be viewed in a mono-spaced font on a plain text editor or basic terminal.   The minimum space between columns should be computed from the text and not hard-coded.   It is not a requirement to add separating characters between or around columns. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#ABAP
ABAP
report z_align no standard page header. start-of-selection.   data: lt_strings type standard table of string, lv_strings type string. append: 'Given$a$text$file$of$many$lines,$where$fields$within$a$line$' to lt_strings, 'are$delineated$by$a$single$''dollar''$character,$write$a$program' to lt_strings, 'that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$' to lt_strings, 'column$are$separated$by$at$least$one$space.' to lt_strings, 'Further,$allow$for$each$word$in$a$column$to$be$either$left$' to lt_strings, 'justified,$right$justified,$or$center$justified$within$its$column.' to lt_strings. types ty_strings type standard table of string.   perform align_col using 'LEFT' lt_strings. skip. perform align_col using 'RIGHT' lt_strings. skip. perform align_col using 'CENTER' lt_strings.     form align_col using iv_just type string iv_strings type ty_strings. constants: c_del value '$'. data: lv_string type string, lt_strings type table of string, lt_tables like table of lt_strings, lv_first type string, lv_second type string, lv_longest type i value 0, lv_off type i value 0, lv_len type i. " Loop through the supplied text. It is expected at the input is a table of strings, with each " entry in the table representing a new line of the input. loop at iv_strings into lv_string. " Split the current line at the delimiter. split lv_string at c_del into lv_first lv_second. " Loop through the line splitting at every delimiter. do. append lv_first to lt_strings. lv_len = strlen( lv_first ). " Check if the length of the new string is greater than the currently stored length. if lv_len > lv_longest. lv_longest = lv_len. endif. if lv_second na c_del. " Check if the string is longer than the recorded maximum. lv_len = strlen( lv_second ). if lv_len > lv_longest. lv_longest = lv_len. endif. append lv_second to lt_strings. exit. endif. split lv_second at c_del into lv_first lv_second. enddo.   append lt_strings to lt_tables. clear lt_strings. endloop.   " Loop through each line of input. loop at lt_tables into lt_strings. " Loop through each word in the line (Separated by specified delimiter). loop at lt_strings into lv_string. lv_off = ( sy-tabix - 1 ) * ( lv_longest + 2 ). case iv_just. when 'LEFT'. write : at (lv_longest) lv_string left-justified. when 'RIGHT'. write at (lv_longest) lv_string right-justified. when 'CENTER'. write at (lv_longest) lv_string centered. endcase. endloop. skip. sy-linno = sy-linno - 1. endloop. endform.
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.
#Clojure
Clojure
(ns active-object (:import (java.util Timer TimerTask)))   (defn input [integrator k] (send integrator assoc :k k))   (defn output [integrator] (:s @integrator))   (defn tick [integrator t1] (send integrator (fn [{:keys [k s t0] :as m}] (assoc m :s (+ s (/ (* (+ (k t1) (k t0)) (- t1 t0)) 2.0)) :t0 t1))))   (defn start-timer [integrator interval] (let [timer (Timer. true) start (System/currentTimeMillis)] (.scheduleAtFixedRate timer (proxy [TimerTask] [] (run [] (tick integrator (double (/ (- (System/currentTimeMillis) start) 1000))))) (long 0) (long interval)) #(.cancel timer)))   (defn test-integrator [] (let [integrator (agent {:k (constantly 0.0) :s 0.0 :t0 0.0}) stop-timer (start-timer integrator 10)] (input integrator #(Math/sin (* 2.0 Math/PI 0.5 %))) (Thread/sleep 2000) (input integrator (constantly 0.0)) (Thread/sleep 500) (println (output integrator)) (stop-timer)))   user> (test-integrator) 1.414065859052494E-5  
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
#FreeBASIC
FreeBASIC
Function GCD(n As Uinteger, d As Uinteger) As Uinteger Return Iif(d = 0, n, GCD(d, n Mod d)) End Function   Function Totient(n As Integer) As Integer Dim As Integer m, tot = 0 For m = 1 To n If GCD(m, n) = 1 Then tot += 1 Next m Return tot End Function   Function isPowerful(m As Integer) As Boolean Dim As Integer n = m, f = 2, q, l = Sqr(m)   If m <= 1 Then Return false Do q = n/f If (n Mod f) = 0 Then If (m Mod(f*f)) Then Return false n = q If f > n Then Exit Do Else f += 1 If f > l Then If (m Mod (n*n)) Then Return false Exit Do End If End If Loop Return true End Function   Function isAchilles(n As Integer) As Boolean If Not isPowerful(n) Then Return false Dim As Integer m = 2, a = m*m Do Do If a = n Then Return false If a > n Then Exit Do a *= m Loop m += 1 a = m*m Loop Until a > n Return true End Function   Dim As Integer num, n, i Dim As Single inicio Dim As Double t0 = Timer   Print "First 50 Achilles numbers:" num = 0 n = 1 Do If isAchilles(n) Then Print Using "#####"; n; num += 1 If num >= 50 Then Exit Do If (num Mod 10) Then Print Space(3); Else Print End If n += 1 Loop   Print !"\n\nFirst 20 strong Achilles numbers:" num = 0 n = 1 Do If isAchilles(n) And isAchilles(Totient(n)) Then Print Using "#####"; n; num += 1 If num >= 20 Then Exit Do If (num Mod 10) Then Print Space(3); Else Print End If n += 1 Loop   Print !"\n\nNumber of Achilles numbers with:" For i = 2 To 6 inicio = Fix(10.0 ^ (i-1)) num = 0 For n = inicio To inicio*10-1 If isAchilles(n) Then num += 1 Next n Print i; " digits:"; num Next i Sleep
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
#Factor
Factor
USING: combinators combinators.short-circuit formatting kernel literals locals math math.functions math.primes.factors math.ranges namespaces pair-rocket sequences sets ; FROM: namespaces => set ; IN: rosetta-code.aliquot   SYMBOL: terms CONSTANT: 2^47 $[ 2 47 ^ ] CONSTANT: test-cases { 11 12 28 496 220 1184 12496 1264460 790 909 562 1064 1488 15355717786080 }   : next-term ( n -- m ) dup divisors sum swap - ;   : continue-aliquot? ( hs term -- hs term ? ) { [ terms get 15 < ] [ swap in? not ] [ nip zero? not ] [ nip 2^47 < ] } 2&& ;   : next-aliquot ( hs term -- hs next-term term ) [ swap [ adjoin ] keep ] [ dup [ next-term ] dip ] bi terms inc ;   : aliquot ( k -- seq ) 0 terms set HS{ } clone swap [ continue-aliquot? ] [ next-aliquot ] produce [ drop ] 2dip swap suffix ;   : non-terminating? ( seq -- ? ) { [ length 15 > ] [ [ 2^47 > ] any? ] } 1|| ;   :: classify ( seq -- classification-str ) { [ seq non-terminating? ] => [ "non-terminating" ] [ seq last zero? ] => [ "terminating" ] [ seq length 2 = ] => [ "perfect" ] [ seq length 3 = ] => [ "amicable" ] [ seq first seq last = ] => [ "sociable" ] [ seq 2 tail* first2 = ] => [ "aspiring" ] [ "cyclic" ] } cond ;   : .classify ( k -- ) dup aliquot [ classify ] keep "%14u: %15s: %[%d, %]\n" printf ;   : main ( -- ) 10 [1,b] test-cases append [ .classify ] each ;   MAIN: main
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.
#Lingo
Lingo
obj = script("MyClass").new()   put obj.foo -- "FOO"   -- add new property 'bar' obj.setProp(#bar, "BAR") put obj.bar -- "BAR"
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.
#Logtalk
Logtalk
  % we start by defining an empty object :- object(foo).   % ensure that complementing categories are allowed :- set_logtalk_flag(complements, allow).   :- end_object.   % define a complementing category, adding a new predicate :- category(bar, complements(foo)).   :- public(bar/1). bar(1). bar(2). bar(3).   :- end_category.  
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.
#LOLCODE
LOLCODE
HAI 1.3   I HAS A object ITZ A BUKKIT I HAS A name, I HAS A value   IM IN YR interface VISIBLE "R U WANTIN 2 (A)DD A VAR OR (P)RINT 1? "! I HAS A option, GIMMEH option   option, WTF? OMG "A" VISIBLE "NAME: "!, GIMMEH name VISIBLE "VALUE: "!, GIMMEH value object HAS A SRS name ITZ value, GTFO OMG "P" VISIBLE "NAME: "!, GIMMEH name VISIBLE object'Z SRS name OIC IM OUTTA YR interface   KTHXBYE
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.
#Nanoquery
Nanoquery
import native   a = 5   println format("0x%08x", native.address(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.
#NewLISP
NewLISP
  (set 'a '(1 2 3)) (address 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.
#Nim
Nim
var x = 12 var xptr = addr(x) # Get address of variable echo cast[int](xptr) # and print it xptr = cast[ptr int](0xFFFE) # Set the address
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.
#Common_Lisp
Common Lisp
(defun coefficients (p) (cond ((= p 0) #(1))   (t (loop for i from 1 upto p for result = #(1 -1) then (map 'vector #'- (concatenate 'vector result #(0)) (concatenate 'vector #(0) result)) finally (return result)))))   (defun primep (p) (cond ((< p 2) nil)   (t (let ((c (coefficients p))) (decf (elt c 0)) (loop for i from 0 upto (/ (length c) 2) for x across c never (/= (mod x p) 0))))))   (defun main () (format t "# p: (x-1)^p for small p:~%") (loop for p from 0 upto 7 do (format t "~D: " p) (loop for i from 0 for x across (reverse (coefficients p)) do (when (>= x 0) (format t "+")) (format t "~D" x) (if (> i 0) (format t "X^~D " i) (format t " "))) (format t "~%")) (loop for i from 0 to 50 do (when (primep i) (format t "~D " i))) (format t "~%"))
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.
#Erlang
Erlang
  main(_) -> AddPrimes = [N || N <- lists:seq(2,500), isprime(N) andalso isprime(digitsum(N))], io:format("The additive primes up to 500 are:~n~p~n~n", [AddPrimes]), io:format("There are ~b of them.~n", [length(AddPrimes)]).   isprime(N) when N < 2 -> false; isprime(N) -> isprime(N, 2, 0, <<1, 2, 2, 4, 2, 4, 2, 4, 6, 2, 6>>).   isprime(N, D, J, Wheel) when J =:= byte_size(Wheel) -> isprime(N, D, 3, Wheel); isprime(N, D, _, _) when D*D > N -> true; isprime(N, D, _, _) when N rem D =:= 0 -> false; isprime(N, D, J, Wheel) -> isprime(N, D + binary:at(Wheel, J), J + 1, Wheel).   digitsum(N) -> digitsum(N, 0). digitsum(0, S) -> S; digitsum(N, S) -> digitsum(N div 10, S + N rem 10).  
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
#Rascal
Rascal
  // Literal rascal>123 := 123 bool: true   // VariableDeclaration rascal>if(str S := "abc") >>>>>>> println("Match succeeds, S == \"<S>\""); Match succeeds, S == "abc" ok   // MultiVariable rascal>if([10, N*, 50] := [10, 20, 30, 40, 50]) >>>>>>> println("Match succeeds, N == <N>"); Match succeeds, N == [20,30,40] ok   // Variable rascal>N = 10; int: 10 rascal>N := 10; bool: true rascal>N := 20; bool: false   // Set and List rascal>if({10, set[int] S, 50} := {50, 40, 30, 20, 10}) >>>>>>> println("Match succeeded, S = <S>"); Match succeeded, S = {30,40,20} ok   rascal>for([L1*, L2*] := [10, 20, 30, 40, 50]) >>>>>>> println("<L1> and <L2>"); [] and [10,20,30,40,50] [10] and [20,30,40,50] [10,20] and [30,40,50] [10,20,30] and [40,50] [10,20,30,40] and [50] [10,20,30,40,50] and [] list[void]: []   // Descendant rascal>T = red(red(black(leaf(1), leaf(2)), black(leaf(3), leaf(4))), black(leaf(5), leaf(4))); rascal>for(/black(_,leaf(4)) := T) >>>>>>> println("Match!"); Match! Match! list[void]: []   rascal>for(/black(_,leaf(int N)) := T) >>>>>>> println("Match <N>"); Match 2 Match 4 Match 4 list[void]: []   rascal>for(/int N := T) >>>>>>> append N; list[int]: [1,2,3,4,5,4]   // Labelled rascal>for(/M:black(_,leaf(4)) := T) >>>>>>> println("Match <M>"); Match black(leaf(3),leaf(4)) Match black(leaf(5),leaf(4)) list[void]: []
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
#REXX
REXX
/*REXX pgm builds a red/black tree (with verification & validation), balanced as needed.*/ parse arg nodes '/' insert /*obtain optional arguments from the CL*/ if nodes='' then nodes = 13.8.17 8.1.11 17.15.25 1.6 25.22.27 /*default nodes. */ if insert='' then insert= 22.44 44.66 /* " inserts.*/ top= . /*define the default for the TOP var.*/ call Dnodes nodes /*define nodes, balance them as added. */ call Dnodes insert /*insert " " " " needed.*/ call Lnodes /*list the nodes (with indentations). */ exit /*stick a fork in it, we're all done. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ err: say; say '***error***: ' arg(1); say; exit 13 /*──────────────────────────────────────────────────────────────────────────────────────*/ Dnodes: arg $d; do j=1 for words($d); t= word($d, j) /*color: encoded into L. */ parse var t p '.' a "." b '.' x 1 . . . xx call Vnodes p a b if x\=='' then call err "too many nodes specified: " xx if p\==top then if @.p==. then call err "node isn't defined: " p if p ==top then do;  !.p=1; L.1=p; end /*assign the top node. */ @.p= a b; n= !.p + 1 /*assign node; bump level.*/ if a\=='' then do;  !.a= n; @.a=; maxL= max(maxL, !.a); end if b\=='' then do;  !.b= n; @.b=; maxL= max(maxL, !.b); end L.n= space(L.n a b) /*append to the level list*/ end /*j*/ return /*──────────────────────────────────────────────────────────────────────────────────────*/ Lnodes: do L=1 for maxL; w= length(maxL); rb= word('(red) (black)', 1+L//2) say "level:" right(L, w) left('', L+L) " ───► " rb ' ' L.L end /*lev*/ return /*──────────────────────────────────────────────────────────────────────────────────────*/ Vnodes: arg $v; do v=1 for words($v); y= word($v, v) if \datatype(y, 'W') then call err "node isn't a whole number: " y y= y / 1 /*normalize Y int.: no LZ, dot*/ if top==. then do; LO=y; top=y; HI=y; L.=; @.=; maxL=1; end LO= min(LO, y); HI= max(HI, y) if @.y\==. & @.y\=='' then call err "node is already defined: " y end /*v*/ return
http://rosettacode.org/wiki/Almost_prime
Almost prime
A   k-Almost-prime   is a natural number   n {\displaystyle n}   that is the product of   k {\displaystyle k}   (possibly identical) primes. Example 1-almost-primes,   where   k = 1 {\displaystyle k=1} ,   are the prime numbers themselves. 2-almost-primes,   where   k = 2 {\displaystyle k=2} ,   are the   semiprimes. Task Write a function/method/subroutine/... that generates k-almost primes and use it to create a table here of the first ten members of k-Almost primes for   1 <= K <= 5 {\displaystyle 1<=K<=5} . Related tasks   Semiprime   Category:Prime Numbers
#Groovy
Groovy
  public class almostprime { public static boolean kprime(int n,int k) { int i,div=0; for(i=2;(i*i <= n) && (div<k);i++) { while(n%i==0) { n = n/i; div++; } } return div + ((n > 1)?1:0) == k; } public static void main(String[] args) { int i,l,k; for(k=1;k<=5;k++) { println("k = " + k + ":"); l = 0; for(i=2;l<10;i++) { if(kprime(i,k)) { print(i + " "); l++; } } println(); } } }​  
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
#CoffeeScript
CoffeeScript
http = require 'http'   show_large_anagram_sets = (word_lst) -> anagrams = {} max_size = 0   for word in word_lst key = word.split('').sort().join('') anagrams[key] ?= [] anagrams[key].push word size = anagrams[key].length max_size = size if size > max_size   for key, variations of anagrams if variations.length == max_size console.log variations.join ' '   get_word_list = (process) -> options = host: "wiki.puzzlers.org" path: "/pub/wordlists/unixdict.txt"   req = http.request options, (res) -> s = '' res.on 'data', (chunk) -> s += chunk res.on 'end', -> process s.split '\n' req.end()   get_word_list show_large_anagram_sets
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
#Perl
Perl
use POSIX 'fmod';   sub angle { my($b1,$b2) = @_; my $b = fmod( ($b2 - $b1 + 720) , 360); $b -= 360 if $b > 180; $b += 360 if $b < -180; return $b; }   @bearings = ( 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 );   while(my ($b1,$b2) = splice(@bearings,0,2)) { printf "%10.2f %10.2f = %8.2f\n", $b1, $b2, angle($b1,$b2); }  
http://rosettacode.org/wiki/Anagrams/Deranged_anagrams
Anagrams/Deranged anagrams
Two or more words are said to be anagrams if they have the same characters, but in a different order. By analogy with derangements we define a deranged anagram as two words with the same characters, but in which the same character does not appear in the same position in both words. Task[edit] Use the word list at unixdict to find and display the longest deranged anagram. Related tasks Permutations/Derangements Best shuffle Word plays Ordered words Palindrome detection Semordnilap Anagrams Anagrams/Deranged anagrams Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#Python
Python
import urllib.request from collections import defaultdict from itertools import combinations   def getwords(url='http://www.puzzlers.org/pub/wordlists/unixdict.txt'): return list(set(urllib.request.urlopen(url).read().decode().split()))   def find_anagrams(words): anagram = defaultdict(list) # map sorted chars to anagrams for word in words: anagram[tuple(sorted(word))].append( word ) return dict((key, words) for key, words in anagram.items() if len(words) > 1)   def is_deranged(words): 'returns pairs of words that have no character in the same position' return [ (word1, word2) for word1,word2 in combinations(words, 2) if all(ch1 != ch2 for ch1, ch2 in zip(word1, word2)) ]   def largest_deranged_ana(anagrams): ordered_anagrams = sorted(anagrams.items(), key=lambda x:(-len(x[0]), x[0])) for _, words in ordered_anagrams: deranged_pairs = is_deranged(words) if deranged_pairs: return deranged_pairs return []   if __name__ == '__main__': words = getwords('http://www.puzzlers.org/pub/wordlists/unixdict.txt') print("Word count:", len(words))   anagrams = find_anagrams(words) print("Anagram count:", len(anagrams),"\n")   print("Longest anagrams with no characters in the same position:") print(' ' + '\n '.join(', '.join(pairs) for pairs in largest_deranged_ana(anagrams)))
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.
#Nim
Nim
# Using scoped function fibI inside fib proc fib(x: int): int = proc fibI(n: int): int = if n < 2: n else: fibI(n-2) + fibI(n-1) if x < 0: raise newException(ValueError, "Invalid argument") return fibI(x)   for i in 0..4: echo fib(i)   # fibI(10) # undeclared identifier 'fibI'
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.
#Maple
Maple
  with(NumberTheory): pairs:=[]; for i from 1 to 20000 do for j from i+1 to 20000 do sum1:=SumOfDivisors(j)-j; sum2:=SumOfDivisors(i)-i; if sum1=i and sum2=j and i<>j then pairs:=[op(pairs),[i,j]]; printf("%a", pairs); end if; end do; end do; pairs;  
http://rosettacode.org/wiki/Animation
Animation
Animation is integral to many parts of GUIs, including both the fancy effects when things change used in window managers, and of course games.   The core of any animation system is a scheme for periodically changing the display while still remaining responsive to the user.   This task demonstrates this. Task Create a window containing the string "Hello World! " (the trailing space is significant). Make the text appear to be rotating right by periodically removing one letter from the end of the string and attaching it to the front. When the user clicks on the (windowed) text, it should reverse its direction.
#TI-89_BASIC
TI-89 BASIC
rcanimat() Prgm Local leftward,s,i,k,x,y false → leftward "Hello World! " → s 0 → k © last keypress found 6*3 → x © cursor position 5 → y ClrIO While k ≠ 4360 and k ≠ 277 and k ≠ 264 © QUIT,HOME,ESC keys © Handle Enter key If k = 13 Then If x ≥ 40 and x < 40+6*dim(s) and y ≥ 25 and y < 35 Then © On text? not leftward → leftward ElseIf x ≥ 5 and x < 5+6*dim("[Quit]") and y ≥ 55 and y < 65 Then © On quit? Exit EndIf EndIf © Cursor movement keys If k=338 or k=340 or k=344 or k=337 or k=339 or k=342 or k=345 or k=348 Then Output y, x, " " © Blank old cursor pos If k = 338 or k = 339 or k = 342 Then: y-6→y ElseIf k = 344 or k = 345 or k = 348 Then: y+6→y :EndIf If k = 337 or k = 339 or k = 345 Then: x-6→x ElseIf k = 340 or k = 342 or k = 348 Then: x+6→x :EndIf min(max(y, 0), 64)→y min(max(x, 0), 152)→x EndIf © Drawing Output 0, 0, "Use arrows, ENTER key" Output 60, 5, "[Quit]" Output 30, 40, s Output y, x, "Ŵ" © should be diamond symbol © Animation If leftward Then right(s, dim(s)-1) & left(s, 1) → s Else right(s, 1) & left(s, dim(s)-1) → s EndIf 0 → i getKey() → k © reads most recent keypress or 0 While i < 2 and k = 0 © Delay loop. Better solution? getKey() → k i + 1 → i EndWhile EndWhile DispHome EndPrgm
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.
#Vedit_macro_language
Vedit macro language
Buf_Switch(Buf_Free) Win_Create(Buf_Num, 1, 1, 2, 14) Ins_Text("Hello World! ") #2 = Cur_Pos Repeat(ALL) { if (Key_Shift_Status & 64) { BOL Block_Copy(#2-1, #2, DELETE) } else { Block_Copy(0, 1, DELETE) } EOL Update() Sleep(2) }
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.
#PicoLisp
PicoLisp
(load "@lib/math.l")   (de pendulum (X Y Len) (let (Angle pi/2 V 0) (call 'clear) (call 'tput "cup" Y X) (prin '+) (call 'tput "cup" 1 (+ X Len)) (until (key 25) # 25 ms (let A (*/ (sin Angle) -9.81 1.0) (inc 'V (*/ A 40)) # DT = 25 ms = 1/40 sec (inc 'Angle (*/ V 40)) ) (call 'tput "cup" (+ Y (*/ Len (cos Angle) 2.2)) # Compensate for aspect ratio (+ X (*/ Len (sin Angle) 1.0)) ) ) ) )
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.
#FreeBASIC
FreeBASIC
  Function wordsOK(string1 As String, string2 As String) As boolean If Mid(string1, Len(string1), 1) = Mid(string2, 1, 1) Then Return True End If Return False End Function   Function Amb(A() As String, B() As String, C() As String, D() As String) As String Dim As Integer a2, b2, c2, d2 For a2 = 0 To Ubound(A) For b2 = 0 To Ubound(B) For c2 = 0 To Ubound(C) For d2 = 0 To Ubound(D) If wordsOK(A(a2),B(b2)) And wordsOK(B(b2),C(c2)) And wordsOK(C(c2),D(d2)) Then Return A(a2) + " " + B(b2) + " " + C(c2) + " " + D(d2) End If Next d2 Next c2 Next b2 Next a2 Return "" 'Cadena vacía, por ejemplo, falla End Function   Dim As String set1(2), set2(2), set3(2), set4(1) 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"   Dim As String text = Amb(set1(), set2(), set3(), set4())   If text <> "" Then Print !"Correct sentence would be:\n" + text Else Print "Failed to fine a correct sentence." End If Sleep  
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.
#Aikido
Aikido
function accumulator (sum:real) { return function(n:real) { return sum += n } }   var x = accumulator(1) x(5) println (accumulator) println (x(2.3))
http://rosettacode.org/wiki/Accumulator_factory
Accumulator factory
A problem posed by Paul Graham is that of creating a function that takes a single (numeric) argument and which returns another function that is an accumulator. The returned accumulator function in turn also takes a single numeric argument, and returns the sum of all the numeric values passed in so far to that accumulator (including the initial value passed when the accumulator was created). Rules The detailed rules are at http://paulgraham.com/accgensub.html and are reproduced here for simplicity (with additions in small italic text). Before you submit an example, make sure the function Takes a number n and returns a function (lets call it g), that takes a number i, and returns n incremented by the accumulation of i from every call of function g(i). Although these exact function and parameter names need not be used Works for any numeric type-- i.e. can take both ints and floats and returns functions that can take both ints and floats. (It is not enough simply to convert all input to floats. An accumulator that has only seen integers must return integers.) (i.e., if the language doesn't allow for numeric polymorphism, you have to use overloading or something like that) Generates functions that return the sum of every number ever passed to them, not just the most recent. (This requires a piece of state to hold the accumulated value, which in turn means that pure functional languages can't be used for this task.) Returns a real function, meaning something that you can use wherever you could use a function you had defined in the ordinary way in the text of your program. (Follow your language's conventions here.) Doesn't store the accumulated value or the returned functions in a way that could cause them to be inadvertently modified by other code. (No global variables or other such things.) E.g. if after the example, you added the following code (in a made-up language) where the factory function is called foo: x = foo(1); x(5); foo(3); print x(2.3); It should print 8.3. (There is no need to print the form of the accumulator function returned by foo(3); it's not part of the task at all.) Task Create a function that implements the described rules. It need not handle any special error cases not described above. The simplest way to implement the task as described is typically to use a closure, providing the language supports them. Where it is not possible to hold exactly to the constraints above, describe the deviations.
#Aime
Aime
af(list l, object o) { l[0] = l[0] + o; }   main(void) { object (*f)(object);   f = af.apply(list(1));   f(5); af.apply(list(3)); o_(f(2.3), "\n");   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
#Action.21
Action!
DEFINE LINES_COUNT="10" DEFINE COLUMNS_COUNT="20" DEFINE WORDS_COUNT="100" DEFINE BUFFER_SIZE="2000" DEFINE LINE_WIDTH="40" DEFINE PTR="CARD"   PTR ARRAY lines(LINES_COUNT) BYTE ARRAY wordStart(WORDS_COUNT) BYTE ARRAY wordLen(WORDS_COUNT) BYTE ARRAY firstWordInLine(LINES_COUNT) BYTE ARRAY wordsInLine(LINES_COUNT) BYTE ARRAY colWidths(COLUMNS_COUNT) BYTE ARRAY buffer(BUFFER_SIZE) BYTE lineCount,colCount,wordCount   CHAR sep=['$]   PROC AddLine(CHAR ARRAY line) lines(lineCount)=line lineCount==+1 RETURN   PROC InitData() lineCount=0 AddLine("Given$a$text$file$of$many$lines,$where$fields$within$a$line$") AddLine("are$delineated$by$a$single$'dollar'$character,$write$a$program") AddLine("that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$") AddLine("column$are$separated$by$at$least$one$space.") AddLine("Further,$allow$for$each$word$in$a$column$to$be$either$left$") AddLine("justified,$right$justified,$or$center$justified$within$its$column.") RETURN   PROC ProcessData() BYTE i,pos,len,start,w,col CHAR ARRAY line   colCount=0 wordCount=0 FOR i=0 TO lineCount-1 DO line=lines(i) len=line(0) firstWordInLine(i)=wordCount wordsInLine(i)=0 pos=1 col=0 WHILE pos<=len DO start=pos WHILE pos<=len AND line(pos)#sep DO pos==+1 OD w=pos-start wordStart(wordCount)=start wordLen(wordCount)=w wordCount==+1 wordsInLine(i)==+1 IF col=colCount THEN colWidths(col)=w colCount==+1 ELSEIF w>colWidths(col) THEN colWidths(col)=w FI col==+1 pos==+1 OD OD RETURN   BYTE FUNC GetBufLineLength() BYTE i,res   res=0 FOR i=0 TO colCount-1 DO res==+colWidths(i)+1 OD res==+1 RETURN (res)   BYTE FUNC AtasciiToInternal(CHAR c) BYTE c2   c2=c&$7F IF c2<32 THEN RETURN (c+64) ELSEIF c2<96 THEN RETURN (c-32) FI RETURN (c)   PROC GenerateLine(BYTE index BYTE align BYTE POINTER p) BYTE wordIndex,last,left,right,start,len,colW INT i,j CHAR ARRAY line   line=lines(index) wordIndex=firstWordInLine(index) last=wordIndex+wordsInLine(index)-1 FOR i=0 TO colCount-1 DO colW=colWidths(i)   p^=124 p==+1 IF wordIndex<=last THEN start=wordStart(wordIndex) len=wordLen(wordIndex)   IF align=0 THEN left=0 right=colW-len ELSEIF align=1 THEN left=(colW-len)/2 right=colW-left-len ELSE left=colW-len right=0 FI   p==+left for j=start TO start+len-1 DO p^=AtasciiToInternal(line(j)) p==+1 OD p==+right ELSE p==+colW FI   wordIndex==+1 OD p^=124 RETURN   PROC FillBuffer(BYTE lineWidth) BYTE i,align BYTE POINTER p   p=buffer Zero(p,BUFFER_SIZE) FOR align=0 TO 2 DO FOR i=0 TO lineCount-1 DO GenerateLine(i,align,p) p==+lineWidth OD OD RETURN   BYTE FUNC GetMaxOffset() BYTE res   res=GetBufLineLength()-LINE_WIDTH RETURN (res)   PROC Update(BYTE offset,lineWidth) BYTE POINTER srcPtr,dstPtr BYTE i   srcPtr=buffer+offset dstPtr=PeekC(88)+3*LINE_WIDTH FOR i=0 TO 3*lineCount-1 DO MoveBlock(dstPtr,srcPtr,LINE_WIDTH) srcPtr==+lineWidth dstPtr==+LINE_WIDTH IF i=lineCount-1 OR i=2*lineCount-1 THEN dstPtr==+LINE_WIDTH FI OD RETURN   PROC Main() BYTE lineWidth,offset,maxOffset,k, CH=$02FC, ;Internal hardware value for last key pressed CRSINH=$02F0 ;Controls visibility of cursor   CRSINH=1 ;hide cursor   InitData() ProcessData() lineWidth=GetBufLineLength() FillBuffer(lineWidth)   Position(2,1) Print("Press left/right arrow key to scroll")   maxOffset=lineWidth-LINE_WIDTH offset=0 Update(offset,lineWidth) DO k=CH IF k#$FF THEN CH=$FF FI   IF k=134 AND offset>0 THEN offset==-1 Update(offset,lineWidth) ELSEIF k=135 AND offset<maxOffset THEN offset==+1 Update(offset,lineWidth) ELSEIF k=28 THEN EXIT FI OD   RETURN
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.
#Common_Lisp
Common Lisp
  (defclass integrator () ((input :initarg :input :writer input :reader %input) (lock :initform (bt:make-lock) :reader lock) (start-time :initform (get-internal-real-time) :reader start-time) (interval :initarg :interval :reader interval) (thread :reader thread :writer %set-thread) (area :reader area :initform 0 :accessor %area)))   (defmethod shared-initialize ((integrator integrator) slot-names &key (interval nil interval-s-p) &allow-other-keys) (declare (ignore interval)) (cond ;; Restart the thread if any unsynchronized slots are ;; being initialized ((or (eql slot-names t) (member 'thread slot-names) (member 'interval slot-names) (member 'start-time slot-names) (member 'lock slot-names) interval-s-p) ;; If the instance already has a thread, stop it and wait for it ;; to stop before initializing any slots (when (slot-boundp integrator 'thread) (input nil integrator) (bt:join-thread (thread integrator))) (call-next-method) (let* ((now (get-internal-real-time)) (current-value (funcall (%input integrator) (- (start-time integrator) now)))) (%set-thread (bt:make-thread (lambda () (loop ;; Sleep for the amount required to reach the next interval; ;; mitigates drift from theoretical interval times (sleep (mod (/ (- (start-time integrator) (get-internal-real-time)) internal-time-units-per-second) (interval integrator))) (let* ((input (bt:with-lock-held ((lock integrator)) ;; If input is nil, exit the thread (or (%input integrator) (return)))) (previous-time (shiftf now (get-internal-real-time))) (previous-value (shiftf current-value (funcall input (/ (- now (start-time integrator)) internal-time-units-per-second))))) (bt:with-lock-held ((lock integrator)) (incf (%area integrator) (* (/ (- now previous-time) internal-time-units-per-second) (/ (+ previous-value current-value) 2))))))) :name "integrator-thread") integrator))) (t ;; If lock is not in SLOT-NAMES, it must already be initialized, ;; so it can be taken while slots synchronized to it are set (bt:with-lock-held ((lock integrator)) (call-next-method)))))   (defmethod input :around (new-value (integrator integrator)) (bt:with-lock-held ((lock integrator)) (call-next-method)))   (defmethod area :around ((integrator integrator)) (bt:with-lock-held ((lock integrator)) (call-next-method)))   (let ((integrator (make-instance 'integrator :input (lambda (time) (sin (* 2 pi 0.5 time))) :interval 1/1000))) (unwind-protect (progn (sleep 2) (input (constantly 0) integrator) (sleep 0.5) (format t "~F~%" (area integrator))) (input nil integrator)))  
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
#Go
Go
package main   import ( "fmt" "math" "sort" )   func totient(n int) int { tot := n i := 2 for i*i <= n { if n%i == 0 { for n%i == 0 { n /= i } tot -= tot / i } if i == 2 { i = 1 } i += 2 } if n > 1 { tot -= tot / n } return tot }   var pps = make(map[int]bool)   func getPerfectPowers(maxExp int) { upper := math.Pow(10, float64(maxExp)) for i := 2; i <= int(math.Sqrt(upper)); i++ { fi := float64(i) p := fi for { p *= fi if p >= upper { break } pps[int(p)] = true } } }   func getAchilles(minExp, maxExp int) map[int]bool { lower := math.Pow(10, float64(minExp)) upper := math.Pow(10, float64(maxExp)) achilles := make(map[int]bool) for b := 1; b <= int(math.Cbrt(upper)); b++ { b3 := b * b * b for a := 1; a <= int(math.Sqrt(upper)); a++ { p := b3 * a * a if p >= int(upper) { break } if p >= int(lower) { if _, ok := pps[p]; !ok { achilles[p] = true } } } } return achilles }   func main() { maxDigits := 15 getPerfectPowers(maxDigits) achillesSet := getAchilles(1, 5) // enough for first 2 parts achilles := make([]int, len(achillesSet)) i := 0 for k := range achillesSet { achilles[i] = k i++ } sort.Ints(achilles)   fmt.Println("First 50 Achilles numbers:") for i = 0; i < 50; i++ { fmt.Printf("%4d ", achilles[i]) if (i+1)%10 == 0 { fmt.Println() } }   fmt.Println("\nFirst 30 strong Achilles numbers:") var strongAchilles []int count := 0 for n := 0; count < 30; n++ { tot := totient(achilles[n]) if _, ok := achillesSet[tot]; ok { strongAchilles = append(strongAchilles, achilles[n]) count++ } } for i = 0; i < 30; i++ { fmt.Printf("%5d ", strongAchilles[i]) if (i+1)%10 == 0 { fmt.Println() } }   fmt.Println("\nNumber of Achilles numbers with:") for d := 2; d <= maxDigits; d++ { ac := len(getAchilles(d-1, d)) fmt.Printf("%2d digits: %d\n", d, ac) } }
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
#Fortran
Fortran
After 1, terminates! 1 After 2, terminates! 2,1 After 2, terminates! 3,1 After 3, terminates! 4,3,1 After 2, terminates! 5,1 Perfect! 6 After 2, terminates! 7,1 After 3, terminates! 8,7,1 After 4, terminates! 9,4,3,1 After 4, terminates! 10,8,7,1 After 2, terminates! 11,1 After 7, terminates! 12,16,15,9,4,3,1 Perfect! 28 Perfect! 496 Amicable: 220,284 Amicable: 1184,1210 Sociable 5: 12496,14288,15472,14536,14264 Sociable 4: 1264460,1547860,1727636,1305184 Aspiring: 790,650,652,496 Aspiring: 909,417,143,25,6 Cyclic end 2, to 284: 562,284,220 Cyclic end 2, to 1184: 1064,1336,1184,1210 After 16, non-terminating? 1488,2480,3472,4464,8432,9424,10416,21328,22320,55056,95728,96720, 236592,459792,881392,882384 After 2, overflows! 15355717786080,44534663601120
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.
#Lua
Lua
empty = {} empty.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.
#M2000_Interpreter
M2000 Interpreter
  Module checkit { class alfa { x=5 } \\ a class is a global function which return a group Dim a(5)=alfa() Print a(3).x=5 For a(3) { group anyname { y=10} \\ merge anyname to this (a(3)) this=anyname } Print a(3).y=10 Print Valid(a(2).y)=false \\ make a copy of a(3) to m m=a(3) m.y*=2 Print m.y=20, a(3).y=10 \\ make a pointer to a(3) in n n->a(3) Print n=>y=10 n=>y+=20 Print a(3).y=30 \\ now n points to a(2) n->a(2) Print Valid(n=>y)=false ' y not exist in a(2) Print n is a(2) ' true \\ we don't have types for groups Print valid(@n as m)=false ' n haven't all members of m Print valid(@m as n)=true ' m have all members of n } checkit  
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.
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
  f[a]=1; f[b]=2; f[a]=3; ? f
http://rosettacode.org/wiki/Address_of_a_variable
Address of a variable
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation | Comparison | Matching Memory Operations Pointers & references | Addresses Task Demonstrate how to get the address of a variable and how to set the address of a variable.
#Oberon-2
Oberon-2
VAR a: LONGINT; VAR b: INTEGER; b := 10; a := SYSTEM.ADR(b); (* Sets variable a to the address of variable b *)
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.
#OCaml
OCaml
let address_of (x:'a) : nativeint = if Obj.is_block (Obj.repr x) then Nativeint.shift_left (Nativeint.of_int (Obj.magic x)) 1 (* magic *) else invalid_arg "Can only find address of boxed values.";;   let () = let a = 3.14 in Printf.printf "%nx\n" (address_of a);; let b = ref 42 in Printf.printf "%nx\n" (address_of b);; let c = 17 in Printf.printf "%nx\n" (address_of c);; (* error, because int is unboxed *)
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.
#Crystal
Crystal
def x_minus_1_to_the(p) p.times.reduce([1]) do |ex, _| ([0_i64] + ex).zip(ex + [0]).map { |x, y| x - y } end end   def prime?(p) return false if p < 2 coeff = x_minus_1_to_the(p)[1..p//2] # only need half of coeff terms coeff.all?{ |n| n%p == 0 } end   8.times do |n| puts "(x-1)^#{n} = " + x_minus_1_to_the(n).map_with_index{ |c, p| p.zero? ? c.to_s : (c < 0 ? " - " : " + ") + (c.abs == 1 ? "x" : "#{c.abs}x") + (p == 1 ? "" : "^#{p}") }.join end   puts "\nPrimes below 50:", 50.times.select { |n| prime? n }.join(',')  
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.
#F.23
F#
  // Additive Primes. Nigel Galloway: March 22nd., 2021 let rec fN g=function n when n<10->n+g |n->fN(g+n%10)(n/10) primes32()|>Seq.takeWhile((>)500)|>Seq.filter(fN 0>>isPrime)|>Seq.iter(printf "%d "); printfn ""  
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.
#Factor
Factor
USING: formatting grouping io kernel math math.primes prettyprint sequences ;   : sum-digits ( n -- sum ) 0 swap [ 10 /mod rot + swap ] until-zero ;   499 primes-upto [ sum-digits prime? ] filter [ 9 group simple-table. nl ] [ length "Found  %d additive primes < 500.\n" printf ] bi
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
#Rust
Rust
#![feature(box_patterns, box_syntax)] use self::Color::*; use std::cmp::Ordering::*;   enum Color {R,B}   type Link<T> = Option<Box<N<T>>>; struct N<T> { c: Color, l: Link<T>, val: T, r: Link<T>, }     impl<T: Ord> N<T> { fn balance(col: Color, n1: Link<T>, z: T, n2: Link<T>) -> Link<T> { Some(box match (col,n1,n2) { (B, Some(box N {c: R, l: Some(box N {c: R, l: a, val: x, r: b}), val: y, r: c}), d) | (B, Some(box N {c: R, l: a, val: x, r: Some (box N {c: R, l: b, val: y, r: c})}), d) => N {c: R, l: Some(box N {c: B, l: a, val: x, r: b}), val: y, r: Some(box N {c: B, l: c, val: z, r: d})}, (B, a, Some(box N {c: R, l: Some(box N {c: R, l: b, val: y, r: c}), val: v, r: d})) | (B, a, Some(box N {c: R, l: b, val: y, r: Some(box N {c: R, l: c, val: v, r: d})})) => N {c: R, l: Some(box N {c: B, l: a, val: z, r: b}), val: y, r: Some(box N {c: B, l: c, val: v, r: d})}, (col, a, b) => N {c: col, l: a, val: z, r: b}, }) } fn insert(x: T, n: Link<T>) -> Link<T> { match n { None => Some(box N { c: R, l: None, val: x, r: None }), Some(n) => { let n = *n; let N {c: col, l: a, val: y, r: b} = n; match x.cmp(&y) { Greater => Self::balance(col, a,y,Self::insert(x,b)), Less => Self::balance(col, Self::insert(x,a),y,b), Equal => Some(box N {c: col, l: a, val: y, r: 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
#Scala
Scala
class RedBlackTree[A](implicit ord: Ordering[A]) { sealed abstract class Color case object R extends Color case object B extends Color   sealed abstract class Tree { def insert(x: A): Tree = ins(x) match { case T(_, a, y, b) => T(B, a, y, b) case E => E } def ins(x: A): Tree }   case object E extends Tree { override def ins(x: A): Tree = T(R, E, x, E) }   case class T(c: Color, left: Tree, a: A, right: Tree) extends Tree { private def balance: Tree = (c, left, a, right) match { case (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)) case (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)) case (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)) case (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)) case _ => this }   override def ins(x: A): Tree = ord.compare(x, a) match { case -1 => T(c, left ins x, a, right ).balance case 1 => T(c, left, a, right ins x).balance case 0 => this } } }
http://rosettacode.org/wiki/Almost_prime
Almost prime
A   k-Almost-prime   is a natural number   n {\displaystyle n}   that is the product of   k {\displaystyle k}   (possibly identical) primes. Example 1-almost-primes,   where   k = 1 {\displaystyle k=1} ,   are the prime numbers themselves. 2-almost-primes,   where   k = 2 {\displaystyle k=2} ,   are the   semiprimes. Task Write a function/method/subroutine/... that generates k-almost primes and use it to create a table here of the first ten members of k-Almost primes for   1 <= K <= 5 {\displaystyle 1<=K<=5} . Related tasks   Semiprime   Category:Prime Numbers
#GW-BASIC
GW-BASIC
10 'Almost prime 20 FOR K% = 1 TO 5 30 PRINT "k = "; K%; ":"; 40 LET I% = 2 50 LET C% = 0 60 WHILE C% < 10 70 LET AN% = I%: GOSUB 1000 80 IF ISKPRIME <> 0 THEN PRINT USING " ###"; I%;: LET C% = C% + 1 90 LET I% = I% + 1 100 WEND 110 PRINT 120 NEXT K% 130 END 995 ' Check if n (AN%) is a k (K%) prime 1000 LET F% = 0 1010 FOR J% = 2 TO AN% 1020 WHILE AN% MOD J% = 0 1030 IF F% = K% THEN LET ISKPRIME = 0: RETURN 1040 LET F% = F% + 1 1050 LET AN% = AN% \ J% 1060 WEND 1070 NEXT J% 1080 LET ISKPRIME = (F% = K%) 1090 RETURN  
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
#Common_Lisp
Common Lisp
(defun anagrams (&optional (url "http://wiki.puzzlers.org/pub/wordlists/unixdict.txt")) (let ((words (drakma:http-request url :want-stream t)) (wordsets (make-hash-table :test 'equalp))) ;; populate the wordsets and close stream (do ((word (read-line words nil nil) (read-line words nil nil))) ((null word) (close words)) (let ((letters (sort (copy-seq word) 'char<))) (multiple-value-bind (pair presentp) (gethash letters wordsets) (if presentp (setf (car pair) (1+ (car pair)) (cdr pair) (cons word (cdr pair))) (setf (gethash letters wordsets) (cons 1 (list word))))))) ;; find and return the biggest wordsets (loop with maxcount = 0 with maxwordsets = '() for pair being each hash-value of wordsets if (> (car pair) maxcount) do (setf maxcount (car pair) maxwordsets (list (cdr pair))) else if (eql (car pair) maxcount) do (push (cdr pair) maxwordsets) finally (return (values maxwordsets maxcount)))))
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
#Phix
Phix
function tz(atom a) -- trim trailing zeroes and decimal point string res = sprintf("%16f",a) for i=length(res) to 1 by -1 do integer ch = res[i] if ch='0' or ch='.' then res[i] = ' ' end if if ch!='0' then exit end if end for return res end function procedure test(atom b1, b2) atom diff = mod(b2-b1,360) diff -= iff(diff>180?360:0) printf(1,"%s %s %s\n",{tz(b1),tz(b2),tz(diff)}) end procedure puts(1," b1 b2 diff\n") puts(1,"---------------- ---------------- ----------------\n") test(20,45) test(-45,45) test(-85,90) test(-95,90) test(-45,125) test(-45,145) test(29.4803,-88.6381) test(-78.3251,-159.036) test(-70099.74233810938,29840.67437876723) test(-165313.6666297357,33693.9894517456) test(1174.8380510598456,-154146.66490124757) test(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
#Quackery
Quackery
[ over size over size != iff [ 2drop false ] done over sort over sort != iff [ 2drop false ] done true unrot witheach [ dip behead = if [ dip not conclude ] ] drop ] is deranged ( $ $ --> b )   $ 'rosetta/unixdict.txt' sharefile drop nest$ [] temp put dup size times [ behead over witheach [ 2dup deranged iff [ over nested swap nested join nested temp take join temp put ] else drop ] drop ] drop temp take sortwith [ 0 peek size swap 0 peek size > ] 0 peek witheach [ echo$ sp ]
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.
#Objective-C
Objective-C
#import <Foundation/Foundation.h>   @interface AnonymousRecursion : NSObject { } - (NSNumber *)fibonacci:(NSNumber *)n; @end   @implementation AnonymousRecursion - (NSNumber *)fibonacci:(NSNumber *)n { int i = [n intValue]; if (i < 0) @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"fibonacci: no negative numbers" userInfo:nil]; int result; if (i < 2) result = 1; else result = [[self performSelector:_cmd withObject:@(i-1)] intValue] + [[self performSelector:_cmd withObject:@(i-2)] intValue]; return @(result); } @end   int main (int argc, const char *argv[]) { @autoreleasepool {   AnonymousRecursion *dummy = [[AnonymousRecursion alloc] init]; NSLog(@"%@", [dummy fibonacci:@8]);   } return 0; }
http://rosettacode.org/wiki/Amicable_pairs
Amicable pairs
Two integers N {\displaystyle N} and M {\displaystyle M} are said to be amicable pairs if N ≠ M {\displaystyle N\neq M} and the sum of the proper divisors of N {\displaystyle N} ( s u m ( p r o p D i v s ( N ) ) {\displaystyle \mathrm {sum} (\mathrm {propDivs} (N))} ) = M {\displaystyle =M} as well as s u m ( p r o p D i v s ( M ) ) = N {\displaystyle \mathrm {sum} (\mathrm {propDivs} (M))=N} . Example 1184 and 1210 are an amicable pair, with proper divisors:   1, 2, 4, 8, 16, 32, 37, 74, 148, 296, 592   and   1, 2, 5, 10, 11, 22, 55, 110, 121, 242, 605   respectively. Task Calculate and show here the Amicable pairs below 20,000; (there are eight). Related tasks Proper divisors Abundant, deficient and perfect number classifications Aliquot sequence classifications and its amicable classification.
#Mathematica_.2F_Wolfram_Language
Mathematica / Wolfram Language
amicableQ[n_] := Module[{sum = Total[Most@Divisors@n]}, sum != n && n == Total[Most@Divisors@sum]]   Grid@Partition[Cases[Range[4, 20000], _?(amicableQ@# &)], 2]
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.
#Visual_Basic
Visual Basic
VERSION 5.00 Begin VB.Form Form1 Begin VB.Timer Timer1 Interval = 250 End Begin VB.Label Label1 AutoSize = -1 'True Caption = "Hello World! " End End Attribute VB_Name = "Form1" Attribute VB_GlobalNameSpace = False Attribute VB_Creatable = False Attribute VB_PredeclaredId = True Attribute VB_Exposed = False 'Everything above this line is hidden when in the IDE. Private goRight As Boolean   Private Sub Label1_Click() goRight = Not goRight End Sub   Private Sub Timer1_Timer() If goRight Then x = Mid(Label1.Caption, 2) & Left(Label1.Caption, 1) Else x = Right(Label1.Caption, 1) & Left(Label1.Caption, Len(Label1.Caption) - 1) End If Label1.Caption = x End Sub
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.
#Wren
Wren
import "graphics" for Canvas, Color import "dome" for Window import "input" for Mouse   var RIGHT = true   class Animation { construct new() { Window.title = "Animation" _fore = Color.white }   init() { _text = "Hello World! " _frame = 0 Canvas.print(_text, 10, 10, _fore) }   update() { _frame = _frame + 1 if (_frame == 1200) _frame = 0 if (!Mouse.hidden && Mouse.isButtonPressed("left")) { Mouse.hidden = true RIGHT = !RIGHT } if (_frame % 60 == 0) { if (RIGHT) { _text = _text[-1] + _text[0..-2] } else { _text = _text[1..-1] + _text[0] } Mouse.hidden = false } }   draw(alpha) { Canvas.cls() Canvas.print(_text, 10, 10, _fore) } }   var Game = Animation.new()
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.
#Portugol
Portugol
  programa { inclua biblioteca Matematica --> math // math library inclua biblioteca Util --> u // util library inclua biblioteca Graficos --> g // graphics library inclua biblioteca Teclado --> t // keyboard library   real accel, bx, by real theta = math.PI * 0.5 real g = 9.81 real l = 1.0 real speed = 0.0 real px = 320.0 real py = 10.0 inteiro w = 10 // circle width and height (radius)   // main entry funcao inicio() {   g.iniciar_modo_grafico(verdadeiro) g.definir_dimensoes_janela(640, 400)   // while ESC key not pressed enquanto (nao t.tecla_pressionada(t.TECLA_ESC)) { bx = px + l * 300.0 * math.seno(theta) by = py - l * 300.0 * math.cosseno(theta)   g.definir_cor(g.COR_PRETO) g.limpar()   g.definir_cor(g.COR_BRANCO) g.desenhar_linha(px, py, bx, by) g.desenhar_elipse(bx - w, by - w, w * 2, w * 2, verdadeiro)   accel = g * math.seno(theta) / l / 100.0 speed = speed + accel / 100.0 theta = theta + speed   g.desenhar_texto(0, 370, "Pendulum") g.desenhar_texto(0, 385, "Press ESC to quit")   g.renderizar() u.aguarde(10) } } }    
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.
#Go
Go
package main   import ( "fmt" "sync" )   func ambStrings(ss []string) chan []string { c := make(chan []string) go func() { for _, s := range ss { c <- []string{s} } close(c) }() return c }   func ambChain(ss []string, cIn chan []string) chan []string { cOut := make(chan []string) go func() { var w sync.WaitGroup for chain := range cIn { w.Add(1) go func(chain []string) { for s1 := range ambStrings(ss) { if s1[0][len(s1[0])-1] == chain[0][0] { cOut <- append(s1, chain...) } } w.Done() }(chain) } w.Wait() close(cOut) }() return cOut }   func main() { s1 := []string{"the", "that", "a"} s2 := []string{"frog", "elephant", "thing"} s3 := []string{"walked", "treaded", "grows"} s4 := []string{"slowly", "quickly"} c := ambChain(s1, ambChain(s2, ambChain(s3, ambStrings(s4)))) for s := range c { fmt.Println(s) } }
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.
#ALGOL_68
ALGOL 68
MODE NUMBER = UNION(INT,REAL,COMPL);   PROC plus = (NUMBER in a, in b)NUMBER: ( CASE in a IN (INT a): CASE in b IN (INT b): a+b, (REAL b): a+b, (COMPL b): a+b ESAC, (REAL a): CASE in b IN (INT b): a+b, (REAL b): a+b, (COMPL b): a+b ESAC, (COMPL a): CASE in b IN (INT b): a+b, (REAL b): a+b, (COMPL b): a+b ESAC ESAC );   main: (   # now override the + and +:= OPerators # OP + = (NUMBER a, b)NUMBER: plus(a,b);   OP +:= = (REF NUMBER lhs, NUMBER rhs)NUMBER: lhs := lhs + rhs;   PROC accumulator = (REF NUMBER sum)PROC(NUMBER)NUMBER: (NUMBER n)NUMBER: sum +:= n;   PROC (NUMBER)NUMBER x = accumulator(LOC NUMBER := 1); x(5); print(("x:",x(2.3), new line));   PROC (NUMBER)NUMBER y = accumulator(LOC NUMBER := 100); y(500); print(("y:",y(230), new line));   print(("x:",x(0), new line))   )
http://rosettacode.org/wiki/Abundant,_deficient_and_perfect_number_classifications
Abundant, deficient and perfect number classifications
These define three classifications of positive integers based on their   proper divisors. Let   P(n)   be the sum of the proper divisors of   n   where the proper divisors are all positive divisors of   n   other than   n   itself. if P(n) < n then n is classed as deficient (OEIS A005100). if P(n) == n then n is classed as perfect (OEIS A000396). if P(n) > n then n is classed as abundant (OEIS A005101). Example 6   has proper divisors of   1,   2,   and   3. 1 + 2 + 3 = 6,   so   6   is classed as a perfect number. Task Calculate how many of the integers   1   to   20,000   (inclusive) are in each of the three classes. Show the results here. Related tasks   Aliquot sequence classifications.   (The whole series from which this task is a subset.)   Proper divisors   Amicable pairs
#11l
11l
F sum_proper_divisors(n) R I n < 2 {0} E sum((1 .. n I/ 2).filter(it -> (@n % it) == 0))   V deficient = 0 V perfect = 0 V abundant = 0   L(n) 1..20000 V sp = sum_proper_divisors(n) I sp < n deficient++ E I sp == n perfect++ E I sp > n abundant++   print(‘Deficient = ’deficient) print(‘Perfect = ’perfect) print(‘Abundant = ’abundant)
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
#Ada
Ada
with Ada.Characters.Latin_1; use Ada.Characters.Latin_1; with Ada.Text_IO; use Ada.Text_IO; with Strings_Edit; use Strings_Edit;   procedure Column_Aligner is Text : constant String := "Given$a$text$file$of$many$lines,$where$fields$within$a$line$" & NUL & "are$delineated$by$a$single$'dollar'$character,$write$a$program" & NUL & "that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$" & NUL & "column$are$separated$by$at$least$one$space." & NUL & "Further,$allow$for$each$word$in$a$column$to$be$either$left$" & NUL & "justified,$right$justified,$or$center$justified$within$its$column." & NUL; File  : File_Type; Width  : array (1..1_000) of Natural := (others => 0); Line  : String (1..200); Column  : Positive := 1; Start  : Positive := 1; Pointer : Positive; begin Create (File, Out_File, "columned.txt"); -- Determining the widths of columns for I in Text'Range loop case Text (I) is when '$' | NUL => Width (Column) := Natural'Max (Width (Column), I - Start + 1); Start  := I + 1; if Text (I) = NUL then Column := 1; else Column := Column + 1; end if; when others => null; end case; end loop; -- Formatting for Align in Alignment loop Column  := 1; Start  := 1; Pointer := 1; for I in Text'Range loop case Text (I) is when '$' | NUL => Put -- Formatted output of a word ( Destination => Line, Pointer => Pointer, Value => Text (Start..I - 1), Field => Width (Column), Justify => Align ); Start  := I + 1; if Text (I) = NUL then Put_Line (File, Line (1..Pointer - 1)); Pointer := 1; Column := 1; else Column := Column + 1; end if; when others => null; end case; end loop; end loop; Close (File); end Column_Aligner;
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.
#Crystal
Crystal
require "math" require "time"   # this enum allows us to specify what type of message the proc_chan received. # this trivial example only has one action, but more enum members can be added # to update the proc, or take other actions enum Action Finished # we've waited long enough, and are asking for our result # Update # potential member representing an update to the integrator function end   class Integrator property interval : Float64 getter s : Float64 = 0f64   # initialize our k function as a proc that takes a float and just returns 0 getter k : Proc(Float64, Float64) = ->(t : Float64) { 0f64 }   # channels used for communicating with the main fiber @proc_chan : Channel(Tuple(Action, Proc(Float64, Float64)|Nil)) @result_chan : Channel(Float64)   def initialize(@k, @proc_chan, @result_chan, @interval = 1e-4) # use a monotonic clock for accuracy start = Time.monotonic.total_seconds t0, k0 = 0f64, @k.call(0f64)   loop do # this sleep returns control to the main fiber. if the main fiber hasn't finished sleeping, # control will be returned to this loop sleep interval.seconds # check the channel to see if the function has changed self.check_channel() t1 = Time.monotonic.total_seconds - start k1 = @k.call(t1) @s += (k1 + k0) * (t1 - t0) / 2.0 t0, k0 = t1, k1 end end   # check the proc_chan for messages, update the integrator function or send the result as needed def check_channel select when message = @proc_chan.receive action, new_k = message case action when Action::Finished @result_chan.send @s @k = new_k unless new_k.nil? end else nil end end end   # this channel allows us to update the integrator function, # and inform the integrator to send the result over the result channel proc_chan = Channel(Tuple(Action, Proc(Float64, Float64)|Nil)).new   # channel used to return the result from the integrator result_chan = Channel(Float64).new   # run everything in a new top-level fiber to avoid shared memory issues. # since the fiber immediately sleeps, control is returned to the main code. # the main code then sleeps for two seconds, returning control to our state_clock fiber. # when two seconds is up, this state_clock fiber will return control # to the main code on the next `sleep interval.seconds` spawn name: "state_clock" do ai = Integrator.new ->(t : Float64) { Math.sin(Math::PI * t) }, proc_chan, result_chan end   sleep 2.seconds proc_chan.send({Action::Finished, ->(t : Float64) { 0f64 }}) sleep 0.5.seconds puts result_chan.receive
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
#J
J
achilles=: (*/ .>&1 * 1 = +./)@(1{__&q:)"0 strong=: achilles@(5&p:)
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
#Julia
Julia
using Primes   isAchilles(n) = (p = [x[2] for x in factor(n).pe]; all(>(1), p) && gcd(p) == 1)   isstrongAchilles(n) = isAchilles(n) && isAchilles(totient(n))   function teststrongachilles(nachilles = 50, nstrongachilles = 100) # task 1 println("First $nachilles Achilles numbers:") n, found = 0, 0 while found < nachilles if isAchilles(n) found += 1 print(rpad(n, 5), found % 10 == 0 ? "\n" : "") end n += 1 end # task 2 println("\nFirst $nstrongachilles strong Achilles numbers:") n, found = 0, 0 while found < nstrongachilles if isstrongAchilles(n) found += 1 print(rpad(n, 7), found % 10 == 0 ? "\n" : "") end n += 1 end # task 3 println("\nCount of Achilles numbers for various intervals:") intervals = [10:99, 100:999, 1000:9999, 10000:99999, 100000:999999] for interval in intervals println(lpad(interval, 15), " ", count(isAchilles, interval)) end end   teststrongachilles()  
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
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
ClearAll[PowerfulNumberQ, StrongAchillesNumberQ] PowerfulNumberQ[n_Integer] := AllTrue[FactorInteger[n][[All, 2]], GreaterEqualThan[2]] AchillesNumberQ[n_Integer] := Module[{divs}, If[PowerfulNumberQ[n], divs = Divisors[n]; If[Length[divs] > 2, divs = divs[[2 ;; -2]];  !AnyTrue[Log[#, n] & /@ divs, IntegerQ] , True ] , False ] ] StrongAchillesNumberQ[n_] := AchillesNumberQ[n] \[And] AchillesNumberQ[EulerPhi[n]]   n = 0; i = 0; Reap[While[n < 50, i++; If[AchillesNumberQ[i], n++; Sow[i]] ]][[2, 1]]   n = 0; i = 0; Reap[While[n < 20, i++; If[StrongAchillesNumberQ[i], n++; Sow[i]] ]][[2, 1]]   Tally[IntegerLength /@ Select[Range[9999999], AchillesNumberQ]] // Grid
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
#FreeBASIC
FreeBASIC
function raiseTo( bas as ulongint, power as ulongint ) as ulongint dim as ulongint result = 1, i for i = 1 to power result*=bas next i return result end function   function properDivisorSum( n as ulongint ) as ulongint dim as ulongint prod = 1, temp = n, i = 3, count = 0 while n mod 2 = 0 count += 1 n /= 2 wend if count<>0 then prod *= (raiseTo(2,count + 1) - 1) while i*i <= n count = 0 while n mod i = 0 count += 1 n /= i wend if count = 1 then prod *= (i+1) elseif count > 1 then prod *= ((raiseTo(i,count + 1) - 1)/(i-1)) end if i += 2 wend if n>2 then prod *= (n+1) return prod - temp end function   sub printSeries( arr() as ulongint ptr, size as integer, ty as string) dim as integer i dim as string outstr = "Integer: "+str(arr(0))+", Type: "+ty+", Series: " for i=0 to size-2 outstr = outstr + str(arr(i))+", " next i outstr = outstr + str(arr(i)) print outstr end sub   sub aliquotClassifier(n as ulongint) dim as ulongint arr(0 to 15) dim as integer i, j dim as string ty = "Sociable" arr(0) = n for i = 1 to 15 arr(i) = properDivisorSum(arr(i-1)) if arr(i)=0 orelse arr(i)=n orelse (arr(i) = arr(i-1) and arr(i)<>n) then if arr(i) = 0 then ty = "Terminating" elseif arr(i) = n and i = 1 then ty = "Perfect" elseif arr(i) = n and i = 2 then ty = "Amicable" elseif arr(i) = arr(i-1) and arr(i)<>n then ty = "Aspiring" end if printSeries(arr(),i+1,ty) return end if for j = 1 to i-1 if arr(j) = arr(i) then printSeries(arr(),i+1,"Cyclic") return end if next j next i printSeries(arr(),i+1,"Non-Terminating") end sub   dim as ulongint nums(0 to 22) = {_ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 28, 496, 220, 1184,_ 12496, 1264460, 790, 909, 562, 1064, 1488}   for n as ubyte = 0 to 22 aliquotClassifier(nums(n)) next n
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.
#MiniScript
MiniScript
empty = {} empty.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.
#Morfa
Morfa
  import morfa.base;   template <T> public struct Dynamic { var data: Dict<text, T>; }   // convenience to create new Dynamic instances template <T> public property dynamic(): Dynamic<T> { return Dynamic<T>(new Dict<text,T>()); }   // introduce replacement operator for . - a quoting ` operator public operator ` { kind = infix, precedence = max, associativity = left, quoting = right } template <T> public func `(d: Dynamic<T>, name: text): DynamicElementAccess<T> { return DynamicElementAccess<T>(d, name); }   // to allow implicit cast from the wrapped instance of T (on access) template <T> public func convert(dea: DynamicElementAccess<T>): T { return dea.holder.data[dea.name]; }   // cannot overload assignment - introduce special assignment operator public operator <- { kind = infix, precedence = assign } template <T> public func <-(access: DynamicElementAccess<T>, newEl: T): void { access.holder.data[access.name] = newEl; }   func main(): void { var test = dynamic<int>;   test`a <- 10; test`b <- 20; test`a <- 30;   println(test`a, test`b); }   // private helper structure template <T> struct DynamicElementAccess { var holder: Dynamic<T>; var name: text;   import morfa.io.format.Formatter; public func format(formatt: text, formatter: Formatter): text { return getFormatFunction(holder.data[name])(formatt, formatter); } }  
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.
#Nim
Nim
import json {.experimental: "dotOperators".} template `.=`(js: JsonNode, field: untyped, value: untyped) = js[astToStr(field)] = %value template `.`(js: JsonNode, field: untyped): JsonNode = js[astToStr(field)] var obj = newJObject() obj.foo = "bar" echo(obj.foo) obj.key = 3 echo(obj.key)
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.
#Objective-C
Objective-C
#import <Foundation/Foundation.h> #import <objc/runtime.h>   static void *fooKey = &fooKey; // one way to define a unique key is a pointer variable that points to itself   int main (int argc, const char *argv[]) { @autoreleasepool {   id e = [[NSObject alloc] init];   // set objc_setAssociatedObject(e, fooKey, @1, OBJC_ASSOCIATION_RETAIN);   // get NSNumber *associatedObject = objc_getAssociatedObject(e, fooKey); NSLog(@"associatedObject: %@", associatedObject);   } return 0; }
http://rosettacode.org/wiki/Address_of_a_variable
Address of a variable
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation | Comparison | Matching Memory Operations Pointers & references | Addresses Task Demonstrate how to get the address of a variable and how to set the address of a variable.
#Oforth
Oforth
tvar: A 10 to A   tvar: B #A to B B .s [1] (Variable) #A >ok   12 B put A .s [1] (Integer) 12 [2] (Variable) #A >ok
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.
#Ol
Ol
'GETTING ADDRESS OF VARIABLE int a=1,b=2,c=3 print "Adrress of b: " @b 'SETTING ADDRESS OF INDIRECT (BYREF) VARIABLE int *aa,*bb,*cc @bb=@b 'setting address of bb to address of b print "Value of bb: " bb 'result: 2
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.
#ooRexx
ooRexx
'GETTING ADDRESS OF VARIABLE int a=1,b=2,c=3 print "Adrress of b: " @b 'SETTING ADDRESS OF INDIRECT (BYREF) VARIABLE int *aa,*bb,*cc @bb=@b 'setting address of bb to address of b print "Value of bb: " bb 'result: 2
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.
#OxygenBasic
OxygenBasic
'GETTING ADDRESS OF VARIABLE int a=1,b=2,c=3 print "Adrress of b: " @b 'SETTING ADDRESS OF INDIRECT (BYREF) VARIABLE int *aa,*bb,*cc @bb=@b 'setting address of bb to address of b print "Value of bb: " bb 'result: 2
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.
#D
D
import std.stdio, std.range, std.algorithm, std.string, std.bigint;   BigInt[] expandX1(in uint p) pure /*nothrow*/ { if (p == 0) return [1.BigInt]; typeof(return) r = [1.BigInt, BigInt(-1)]; foreach (immutable _; 1 .. p) r = zip(r~0.BigInt, 0.BigInt~r).map!(xy => xy[0]-xy[1]).array; r.reverse(); return r; }   bool aksTest(in uint p) pure /*nothrow*/ { if (p < 2) return false; auto ex = p.expandX1; ex[0]++; return !ex[0 .. $ - 1].any!(mult => mult % p); }   void main() { "# p: (x-1)^p for small p:".writeln; foreach (immutable p; 0 .. 12) writefln("%3d: %s", p, p.expandX1.zip(iota(p + 1)).retro .map!q{"%+dx^%d ".format(a[])}.join.replace("x^0", "") .replace("^1 ", " ").replace("+", "+ ") .replace("-", "- ").replace(" 1x", " x")[2 .. $]);   "\nSmall primes using the AKS test:".writeln; 101.iota.filter!aksTest.writeln; }
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.
#Fermat
Fermat
Function Digsum(n) = digsum := 0; while n>0 do digsum := digsum + n|10; n:=n\10; od; digsum.;   nadd := 0; !!'Additive primes below 500 are';   for p=1 to 500 do if Isprime(p) and Isprime(Digsum(p)) then  !!(p,' -> ',Digsum(p)); nadd := nadd+1; fi od;   !!('There were ',nadd);
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.
#Forth
Forth
: prime? ( n -- ? ) here + c@ 0= ; : notprime! ( n -- ) here + 1 swap c! ;   : prime_sieve ( n -- ) here over erase 0 notprime! 1 notprime! 2 begin 2dup dup * > while dup prime? if 2dup dup * do i notprime! dup +loop then 1+ repeat 2drop ;   : digit_sum ( u -- u ) dup 10 < if exit then 10 /mod recurse + ;   : print_additive_primes ( n -- ) ." Additive primes less than " dup 1 .r ." :" cr dup prime_sieve 0 swap 1 do i prime? if i digit_sum prime? if i 3 .r 1+ dup 10 mod 0= if cr else space then then then loop cr . ." additive primes found." cr ;   500 print_additive_primes bye
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
#Standard_ML
Standard ML
  datatype color = R | B datatype 'a tree = E | T of color * 'a tree * 'a * 'a tree   (** val balance = fn : color * 'a tree * 'a * 'a tree -> 'a tree *) fun balance (B, T (R, T (R,a,x,b), y, c), z, d) = T (R, T (B,a,x,b), y, T (B,c,z,d)) | balance (B, T (R, a, x, T (R,b,y,c)), z, d) = T (R, T (B,a,x,b), y, T (B,c,z,d)) | balance (B, a, x, T (R, T (R,b,y,c), z, d)) = T (R, T (B,a,x,b), y, T (B,c,z,d)) | balance (B, a, x, T (R, b, y, T (R,c,z,d))) = T (R, T (B,a,x,b), y, T (B,c,z,d)) | balance (col, a, x, b) = T (col, a, x, b)   (** val insert = fn : int -> int tree -> int tree *) fun insert x s = let fun ins E = T (R,E,x,E) | ins (s as T (col,a,y,b)) = if x < y then balance (col, ins a, y, b) else if x > y then balance (col, a, y, ins b) else s val T (_,a,y,b) = ins s in T (B,a,y,b) end  
http://rosettacode.org/wiki/Algebraic_data_types
Algebraic data types
Some languages offer direct support for algebraic data types and pattern matching on them. While this of course can always be simulated with manual tagging and conditionals, it allows for terse code which is easy to read, and can represent the algorithm directly. Task As an example, implement insertion in a red-black-tree. A red-black-tree is a binary tree where each internal node has a color attribute red or black. Moreover, no red node can have a red child, and every path from the root to an empty node must contain the same number of black nodes. As a consequence, the tree is balanced, and must be re-balanced after an insertion. Reference Red-Black Trees in a Functional Setting
#Swift
Swift
enum Color { case R, B } enum Tree<A> { case E indirect case T(Color, Tree<A>, A, Tree<A>) }   func balance<A>(input: (Color, Tree<A>, A, Tree<A>)) -> Tree<A> { switch input { case let (.B, .T(.R, .T(.R,a,x,b), y, c), z, d): return .T(.R, .T(.B,a,x,b), y, .T(.B,c,z,d)) case let (.B, .T(.R, a, x, .T(.R,b,y,c)), z, d): return .T(.R, .T(.B,a,x,b), y, .T(.B,c,z,d)) case let (.B, a, x, .T(.R, .T(.R,b,y,c), z, d)): return .T(.R, .T(.B,a,x,b), y, .T(.B,c,z,d)) case let (.B, a, x, .T(.R, b, y, .T(.R,c,z,d))): return .T(.R, .T(.B,a,x,b), y, .T(.B,c,z,d)) case let (col, a, x, b)  : return .T(col, a, x, b) } }   func insert<A : Comparable>(x: A, s: Tree<A>) -> Tree<A> { func ins(s: Tree<A>) -> Tree<A> { switch s { case .E  : return .T(.R,.E,x,.E) case let .T(col,a,y,b): if x < y { return balance((col, ins(a), y, b)) } else if x > y { return balance((col, a, y, ins(b))) } else { return s } } } switch ins(s) { case let .T(_,a,y,b): return .T(.B,a,y,b) case .E: assert(false) return .E } }
http://rosettacode.org/wiki/Almost_prime
Almost prime
A   k-Almost-prime   is a natural number   n {\displaystyle n}   that is the product of   k {\displaystyle k}   (possibly identical) primes. Example 1-almost-primes,   where   k = 1 {\displaystyle k=1} ,   are the prime numbers themselves. 2-almost-primes,   where   k = 2 {\displaystyle k=2} ,   are the   semiprimes. Task Write a function/method/subroutine/... that generates k-almost primes and use it to create a table here of the first ten members of k-Almost primes for   1 <= K <= 5 {\displaystyle 1<=K<=5} . Related tasks   Semiprime   Category:Prime Numbers
#Haskell
Haskell
isPrime :: Integral a => a -> Bool isPrime n = not $ any ((0 ==) . (mod n)) [2..(truncate $ sqrt $ fromIntegral n)]   primes :: [Integer] primes = filter isPrime [2..]   isKPrime :: (Num a, Eq a) => a -> Integer -> Bool isKPrime 1 n = isPrime n isKPrime k n = any (isKPrime (k - 1)) sprimes where sprimes = map fst $ filter ((0 ==) . snd) $ map (divMod n) $ takeWhile (< n) primes   kPrimes :: (Num a, Eq a) => a -> [Integer] kPrimes k = filter (isKPrime k) [2..]   main :: IO () main = flip mapM_ [1..5] $ \k -> putStrLn $ "k = " ++ show k ++ ": " ++ (unwords $ map show (take 10 $ kPrimes k))
http://rosettacode.org/wiki/Anagrams
Anagrams
When two or more words are composed of the same characters, but in a different order, they are called anagrams. Task[edit] Using the word list at   http://wiki.puzzlers.org/pub/wordlists/unixdict.txt, find the sets of words that share the same characters that contain the most words in them. Related tasks Word plays Ordered words Palindrome detection Semordnilap Anagrams Anagrams/Deranged anagrams Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#Component_Pascal
Component Pascal
  MODULE BbtAnagrams; IMPORT StdLog,Files,Strings,Args; CONST MAXPOOLSZ = 1024;   TYPE Node = POINTER TO LIMITED RECORD; count: INTEGER; word: Args.String; desc: Node; next: Node; END;   Pool = POINTER TO LIMITED RECORD capacity,max: INTEGER; words: POINTER TO ARRAY OF Node; END;   PROCEDURE NewNode(word: ARRAY OF CHAR): Node; VAR n: Node; BEGIN NEW(n);n.count := 0;n.word := word$; n.desc := NIL;n.next := NIL; RETURN n END NewNode;   PROCEDURE Index(s: ARRAY OF CHAR;cap: INTEGER): INTEGER; VAR i,sum: INTEGER; BEGIN sum := 0; FOR i := 0 TO LEN(s$) DO INC(sum,ORD(s[i])) END; RETURN sum MOD cap END Index;   PROCEDURE ISort(VAR s: ARRAY OF CHAR); VAR i, j: INTEGER; t: CHAR; BEGIN FOR i := 0 TO LEN(s$) - 1 DO j := i; t := s[j]; WHILE (j > 0) & (s[j -1] > t) DO s[j] := s[j - 1]; DEC(j) END; s[j] := t END END ISort;   PROCEDURE SameLetters(x,y: ARRAY OF CHAR): BOOLEAN; BEGIN ISort(x);ISort(y); RETURN x = y END SameLetters;   PROCEDURE NewPoolWith(cap: INTEGER): Pool; VAR i: INTEGER; p: Pool; BEGIN NEW(p); p.capacity := cap; p.max := 0; NEW(p.words,cap); i := 0; WHILE i < p.capacity DO p.words[i] := NIL; INC(i); END; RETURN p END NewPoolWith;   PROCEDURE NewPool(): Pool; BEGIN RETURN NewPoolWith(MAXPOOLSZ); END NewPool;   PROCEDURE (p: Pool) Add(w: ARRAY OF CHAR), NEW; VAR idx: INTEGER; iter,n: Node; BEGIN idx := Index(w,p.capacity); iter := p.words[idx]; n := NewNode(w); WHILE(iter # NIL) DO IF SameLetters(w,iter.word) THEN INC(iter.count); IF iter.count > p.max THEN p.max := iter.count END; n.desc := iter.desc; iter.desc := n; RETURN END; iter := iter.next END; ASSERT(iter = NIL); n.next := p.words[idx];p.words[idx] := n END Add;   PROCEDURE ShowAnagrams(l: Node); VAR iter: Node; BEGIN iter := l; WHILE iter # NIL DO StdLog.String(iter.word);StdLog.String(" "); iter := iter.desc END; StdLog.Ln END ShowAnagrams;   PROCEDURE (p: Pool) ShowMax(),NEW; VAR i: INTEGER; iter: Node; BEGIN FOR i := 0 TO LEN(p.words) - 1 DO IF p.words[i] # NIL THEN iter := p.words^[i]; WHILE iter # NIL DO IF iter.count = p.max THEN ShowAnagrams(iter); END; iter := iter.next END END END END ShowMax;   PROCEDURE GetLine(rd: Files.Reader; OUT str: ARRAY OF CHAR); VAR i: INTEGER; b: BYTE; BEGIN rd.ReadByte(b);i := 0; WHILE (~rd.eof) & (i < LEN(str)) DO IF (b = ORD(0DX)) OR (b = ORD(0AX)) THEN str[i] := 0X; RETURN END; str[i] := CHR(b); rd.ReadByte(b);INC(i) END; str[LEN(str) - 1] := 0X END GetLine;   PROCEDURE DoProcess*; VAR params : Args.Params; loc: Files.Locator; fd: Files.File; rd: Files.Reader; line: ARRAY 81 OF CHAR; p: Pool; BEGIN Args.Get(params); IF params.argc = 1 THEN loc := Files.dir.This("Bbt"); fd := Files.dir.Old(loc,params.args[0]$,FALSE); StdLog.String("Processing: " + params.args[0]);StdLog.Ln;StdLog.Ln; rd := fd.NewReader(NIL); p := NewPool(); REPEAT GetLine(rd,line); p.Add(line); UNTIL rd.eof; p.ShowMax() ELSE StdLog.String("Error: Missing file to process");StdLog.Ln END; END DoProcess;   END BbtAnagrams.  
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
#Phixmonti
Phixmonti
include ..\Utilitys.pmt   ( "16" 1 "16" 1 "16" ) var al   def difAngle /# b1 b2 -- diff #/ swap - 360 mod dup 180 > if 360 - endif enddef   def test /# b1 b2 -- #/ over over difAngle >ps swap " " rot " " ps> 5 tolist al lalign ? enddef   ( "b1" " " "b2" " " "diff" ) al lalign ? "---------------- ---------------- ----------------" ? 20 45 test -45 45 test -85 90 test -95 90 test -45 125 test -45 145 test 29.4803 -88.6381 test -78.3251 -159.036 test -70099.74233810938 29840.67437876723 test -165313.6666297357 33693.9894517456 test 1174.8380510598456 -154146.66490124757 test 60175.77306795546 42213.07192354373 test
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
#R
R
puzzlers.dict <- readLines("http://www.puzzlers.org/pub/wordlists/unixdict.txt")   longest.deranged.anagram <- function(dict=puzzlers.dict) { anagram.groups <- function(word.group) { sorted <- sapply(lapply(strsplit(word.group,""),sort),paste, collapse="") grouped <- tapply(word.group, sorted, force, simplify=FALSE) grouped <- grouped[sapply(grouped, length) > 1] grouped[order(-nchar(names(grouped)))] }   derangements <- function(anagram.group) { pairs <- expand.grid(a = anagram.group, b = anagram.group, stringsAsFactors=FALSE) pairs <- subset(pairs, a < b) deranged <- with(pairs, mapply(function(a,b) all(a!=b), strsplit(a,""), strsplit(b,""))) pairs[which(deranged),] }   for (anagram.group in anagram.groups(dict)) { if (nrow(d <- derangements(anagram.group)) > 0) { return(d[1,]) } } }
http://rosettacode.org/wiki/Anonymous_recursion
Anonymous recursion
While implementing a recursive function, it often happens that we must resort to a separate   helper function   to handle the actual recursion. This is usually the case when directly calling the current function would waste too many resources (stack space, execution time), causing unwanted side-effects,   and/or the function doesn't have the right arguments and/or return values. So we end up inventing some silly name like   foo2   or   foo_helper.   I have always found it painful to come up with a proper name, and see some disadvantages:   You have to think up a name, which then pollutes the namespace   Function is created which is called from nowhere else   The program flow in the source code is interrupted Some languages allow you to embed recursion directly in-place.   This might work via a label, a local gosub instruction, or some special keyword. Anonymous recursion can also be accomplished using the   Y combinator. Task If possible, demonstrate this by writing the recursive version of the fibonacci function   (see Fibonacci sequence)   which checks for a negative argument before doing the actual recursion.
#OCaml
OCaml
let fib n = let rec real = function 0 -> 1 | 1 -> 1 | n -> real (n-1) + real (n-2) in if n < 0 then None else Some (real n)
http://rosettacode.org/wiki/Amicable_pairs
Amicable pairs
Two integers N {\displaystyle N} and M {\displaystyle M} are said to be amicable pairs if N ≠ M {\displaystyle N\neq M} and the sum of the proper divisors of N {\displaystyle N} ( s u m ( p r o p D i v s ( N ) ) {\displaystyle \mathrm {sum} (\mathrm {propDivs} (N))} ) = M {\displaystyle =M} as well as s u m ( p r o p D i v s ( M ) ) = N {\displaystyle \mathrm {sum} (\mathrm {propDivs} (M))=N} . Example 1184 and 1210 are an amicable pair, with proper divisors:   1, 2, 4, 8, 16, 32, 37, 74, 148, 296, 592   and   1, 2, 5, 10, 11, 22, 55, 110, 121, 242, 605   respectively. Task Calculate and show here the Amicable pairs below 20,000; (there are eight). Related tasks Proper divisors Abundant, deficient and perfect number classifications Aliquot sequence classifications and its amicable classification.
#MATLAB
MATLAB
function amicable tic N=2:1:20000; aN=[]; N(isprime(N))=[]; %erase prime numbers I=1; a=N(1); b=sum(pd(a)); while length(N)>1 if a==b %erase perfect numbers; N(N==a)=[]; a=N(1); b=sum(pd(a)); elseif b<a %the first member of an amicable pair is abundant not defective N(N==a)=[]; a=N(1); b=sum(pd(a)); elseif ~ismember(b,N) %the other member was previously erased N(N==a)=[]; a=N(1); b=sum(pd(a)); else c=sum(pd(b)); if a==c aN(I,:)=[I a b]; I=I+1; N(N==b)=[]; else if ~ismember(c,N) %the other member was previously erased N(N==b)=[]; end end N(N==a)=[]; a=N(1); b=sum(pd(a)); clear c end end disp(array2table(aN,'Variablenames',{'N','Amicable1','Amicable2'})) toc end   function D=pd(x) K=1:ceil(x/2); D=K(~(rem(x, K))); 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.
#XPL0
XPL0
include c:\cxpl\codes; int CpuReg, Dir, I, J; char Str; string 0; \use zero-terminated strings, instead of MSb set [CpuReg:= GetReg; \provides access to 8086 CPU registers \ 0123456789012 Str:= "Hello World! "; Clear; Dir:= -1; \make string initially scroll to the right I:= 0; \index to start of displayed portion of string repeat Cursor(0, 0); \set cursor position to upper-left corner for J:= 0 to 12 do [ChOut(0, Str(I)); I:= I+1; if I>12 then I:= 0]; Sound(0, 2, 1); \delay about 1/9 second I:= I+Dir; \step starting position of displayed string if I<0 then I:=12; \wraparound if I>12 then I:= 0; CpuReg:= GetReg; \get mouse button press information CpuReg(0):= 5; CpuReg(1):= 0; SoftInt($33); \reverse direction if left button was pressed if CpuReg(1) then Dir:= -Dir; until KeyHit; \any keystroke terminates 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.
#Yabasic
Yabasic
clear screen open window 400, 150 backcolor 0, 0, 0 clear window   color 250, 120, 0 texto$ = "Hello world! " l = len(texto$) dir = 1 do release$ = inkey$(.25) if mouseb(release$) = -1 then dir = -dir end if clear window text 100, 90, texto$, "modern30" if dir = 1 then texto$ = right$(texto$, l-1) + left$(texto$, 1) else texto$ = right$(texto$, 1) + left$(texto$, l-1) end if loop
http://rosettacode.org/wiki/Animate_a_pendulum
Animate a pendulum
One good way of making an animation is by simulating a physical system and illustrating the variables in that system using a dynamically changing graphical display. The classic such physical system is a simple gravity pendulum. Task Create a simple physical model of a pendulum and animate it.
#Prolog
Prolog
:- use_module(library(pce)).   pendulum :- new(D, window('Pendulum')), send(D, size, size(560, 300)), new(Line, line(80, 50, 480, 50)), send(D, display, Line), new(Circle, circle(20)), send(Circle, fill_pattern, colour(@default, 0, 0, 0)), new(Boule, circle(60)), send(Boule, fill_pattern, colour(@default, 0, 0, 0)), send(D, display, Circle, point(270,40)), send(Circle, handle, handle(h/2, w/2, in)), send(Boule, handle, handle(h/2, w/2, out)), send(Circle, connect, Boule, link(in, out, line(0,0,0,0,none))), new(Anim, animation(D, 0.0, Boule, 200.0)), send(D, done_message, and(message(Anim, free), message(Boule, free), message(Circle, free), message(@receiver,destroy))), send(Anim?mytimer, start), send(D, open).         :- pce_begin_class(animation(window, angle, boule, len_pendulum), object). variable(window, object, both, "Display window"). variable(boule, object, both, "bowl of the pendulum"). variable(len_pendulum, object, both, "len of the pendulum"). variable(angle, object, both, "angle with the horizontal"). variable(delta, object, both, "increment of the angle"). variable(mytimer, timer, both, "timer of the animation").   initialise(P, W:object, A:object, B : object, L:object) :-> "Creation of the object":: send(P, window, W), send(P, angle, A), send(P, boule, B), send(P, len_pendulum, L), send(P, delta, 0.01), send(P, mytimer, new(_, timer(0.01,message(P, anim_message)))).   % method called when the object is destroyed % first the timer is stopped % then all the resources are freed unlink(P) :-> send(P?mytimer, stop), send(P, send_super, unlink).     % message processed by the timer anim_message(P) :-> get(P, angle, A), get(P, len_pendulum, L), calc(A, L, X, Y), get(P, window, W), get(P, boule, B), send(W, display, B, point(X,Y)), % computation of the next position get(P, delta, D), next_Angle(A, D, NA, ND), send(P, angle, NA), send(P, delta, ND).   :- pce_end_class.   % computation of the position of the bowl. calc(Ang, Len, X, Y) :- X is Len * cos(Ang)+ 250, Y is Len * sin(Ang) + 20.     % computation of the next angle % if we reach 0 or pi, delta change. next_Angle(A, D, NA, ND) :- NA is D + A, (((D > 0, abs(pi-NA) < 0.01); (D < 0, abs(NA) < 0.01))-> ND = - D; ND = D).  
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.
#Haskell
Haskell
import Control.Monad   amb = id   joins left right = last left == head right   example = do w1 <- amb ["the", "that", "a"] w2 <- amb ["frog", "elephant", "thing"] w3 <- amb ["walked", "treaded", "grows"] w4 <- amb ["slowly", "quickly"] guard (w1 `joins` w2) guard (w2 `joins` w3) guard (w3 `joins` w4) pure $ unwords [w1, w2, w3, w4]  
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.
#AppleScript
AppleScript
on accumulator(n) -- Returns a new script object -- containing a handler. script on call(i) set n to n + i -- Returns n. end call end script end accumulator   set x to accumulator(10) log x's call(1) set y to accumulator(5) log y's call(2) log x's call(3.5) -- Event Log: (*11*) (*7*) (*14.5*)
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.
#Argile
Argile
use std, array   let A = accumulator 42 print(A 0) print(A 1) print(A 10) print(A 100)   let B = accumulator 4.2 print(B 0) print(B 1) print(B 10.0) print(B 100.4)   ~A ; ~B (: use dbg; check mem leak :)   (: accumulator call :) =: <accumulator a> <num x> := -> (a.t) call ((a.func) as function(any)(a.t)->(a.t)) with (a.data) ((Cgen x) as a.t)   (: accumulator constructors :) .: accumulator <int x> :. -> int accumulator (val (int accumulator) A).init(x) (A as Accumulator).func = ( .:<int& accu, int x>:. ->int {accu += x; accu} ) A   .: accumulator <real x> :. -> real accumulator (val (real accumulator) A).init(x) (A as Accumulator).func = ( .:<real&accu,real x>:. ->real{accu += x; accu} ) A   =: <accumulator& a>.init <num x> := a = new (Accumulator) a.data = (new array of 1 a.t) *(a.data as (a.t*)) = Cgen x   (: accumulator destructor :) .: del Accumulator <Accumulator a>:. free a.data free a =: ~ <accumulator a> := {del Accumulator a}   (: accumulator type :) class Accumulator function func any data   =: [<type t=(int)>] accumulator := -> type Accumulator.prefix Accumulator.suffix   autocast accumulator<->Accumulator
http://rosettacode.org/wiki/Abundant,_deficient_and_perfect_number_classifications
Abundant, deficient and perfect number classifications
These define three classifications of positive integers based on their   proper divisors. Let   P(n)   be the sum of the proper divisors of   n   where the proper divisors are all positive divisors of   n   other than   n   itself. if P(n) < n then n is classed as deficient (OEIS A005100). if P(n) == n then n is classed as perfect (OEIS A000396). if P(n) > n then n is classed as abundant (OEIS A005101). Example 6   has proper divisors of   1,   2,   and   3. 1 + 2 + 3 = 6,   so   6   is classed as a perfect number. Task Calculate how many of the integers   1   to   20,000   (inclusive) are in each of the three classes. Show the results here. Related tasks   Aliquot sequence classifications.   (The whole series from which this task is a subset.)   Proper divisors   Amicable pairs
#360_Assembly
360 Assembly
* Abundant, deficient and perfect number 08/05/2016 ABUNDEFI CSECT USING ABUNDEFI,R13 set base register SAVEAR B STM-SAVEAR(R15) skip savearea DC 17F'0' savearea STM STM R14,R12,12(R13) save registers ST R13,4(R15) link backward SA ST R15,8(R13) link forward SA LR R13,R15 establish addressability SR R10,R10 deficient=0 SR R11,R11 perfect =0 SR R12,R12 abundant =0 LA R6,1 i=1 LOOPI C R6,NN do i=1 to nn BH ELOOPI SR R8,R8 sum=0 LR R9,R6 i SRA R9,1 i/2 LA R7,1 j=1 LOOPJ CR R7,R9 do j=1 to i/2 BH ELOOPJ LR R2,R6 i SRDA R2,32 DR R2,R7 i//j=0 LTR R2,R2 if i//j=0 BNZ NOTMOD AR R8,R7 sum=sum+j NOTMOD LA R7,1(R7) j=j+1 B LOOPJ ELOOPJ CR R8,R6 if sum?i BL SLI < BE SEI = BH SHI > SLI LA R10,1(R10) deficient+=1 B EIF SEI LA R11,1(R11) perfect +=1 B EIF SHI LA R12,1(R12) abundant +=1 EIF LA R6,1(R6) i=i+1 B LOOPI ELOOPI XDECO R10,XDEC edit deficient MVC PG+10(5),XDEC+7 XDECO R11,XDEC edit perfect MVC PG+24(5),XDEC+7 XDECO R12,XDEC edit abundant MVC PG+39(5),XDEC+7 XPRNT PG,80 print buffer L R13,4(0,R13) restore savearea pointer LM R14,R12,12(R13) restore registers XR R15,R15 return code = 0 BR R14 return to caller NN DC F'20000' PG DC CL80'deficient=xxxxx perfect=xxxxx abundant=xxxxx' XDEC DS CL12 REGEQU END ABUNDEFI
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
#Aime
Aime
data b; file f; text n, t; list c, r, s; integer a, i, k, m, w;   b = "Given$a$text$file$of$many$lines,$where$fields$within$a$line$\n" "are$delineated$by$a$single$'dollar'$character,$write$a$program\n" "that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$\n" "column$are$separated$by$at$least$one$space.\n" "Further,$allow$for$each$word$in$a$column$to$be$either$left$\n" "justified,$right$justified,$or$center$justified$within$its$column.";   f.b_affix(b);   m = 0;   while (f.news(r, 0, 0, "$") ^ -1) { c.append(r); m = max(m, ~r); }   i = 0; while (i < m) { w = 0; for (, r in c) { if (i < ~r) { w = max(w, length(r[i])); } } s.append(w + 1); i += 1; }   for (k, t in list("left", "center", "right")) { o_(t, " justified\n"); for (, r in c) { for (i, n in r) { m = s[i] - ~n; o_form("/w~3/~/w~1/", a = (2 - k) * m >> 1, "", m - a, "", n); } o_newline(); } o_newline(); }
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.
#D
D
import core.thread; import std.datetime; import std.math; import std.stdio;   void main() { auto func = (double t) => sin(cast(double) PI * t); Integrator integrator = new Integrator(func); Thread.sleep(2000.msecs);   integrator.setFunc(t => 0.0); Thread.sleep(500.msecs);   integrator.stop(); writeln(integrator.getOutput()); }   /** * Integrates input function K over time * S + (t1 - t0) * (K(t1) + K(t0)) / 2 */ public class Integrator { public alias Function = double function (double);   private SysTime start; private shared bool running;   private Function func; private shared double t0; private shared double v0; private shared double sum = 0.0;   public this(Function func) { this.start = Clock.currTime(); setFunc(func); new Thread({ integrate(); }).start(); }   public void setFunc(Function func) { this.func = func; v0 = func(0.0); t0 = 0.0; }   public double getOutput() { return sum; }   public void stop() { running = false; }   private void integrate() { running = true; while (running) { Thread.sleep(1.msecs); update(); } }   private void update() { import core.atomic;   Duration t1 = (Clock.currTime() - start); double v1 = func(t1.total!"msecs"); double rect = (t1.total!"msecs" - t0) * (v0 + v1) / 2; atomicOp!"+="(this.sum, rect); t0 = t1.total!"msecs"; v0 = v1; } }
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
#Perl
Perl
use strict; use warnings; use feature <say current_sub>; use experimental 'signatures'; use List::AllUtils <max head uniqint>; use ntheory <is_square_free is_power euler_phi>; use Math::AnyNum <:overload idiv iroot ipow is_coprime>;   sub table { my $t = shift() * (my $c = 1 + length max @_); ( sprintf( ('%'.$c.'d')x@_, @_) ) =~ s/.{1,$t}\K/\n/gr }   sub powerful_numbers ($n, $k = 2) { my @powerful; sub ($m, $r) { $r < $k and push @powerful, $m and return; for my $v (1 .. iroot(idiv($n, $m), $r)) { if ($r > $k) { next unless is_square_free($v) and is_coprime($m, $v) } __SUB__->($m * ipow($v, $r), $r - 1); } }->(1, 2*$k - 1); sort { $a <=> $b } @powerful; }   my(@P, @achilles, %Ahash, @strong); @P = uniqint @P, powerful_numbers(10**9, $_) for 2..9; shift @P; !is_power($_) and push @achilles, $_ and $Ahash{$_}++ for @P; $Ahash{euler_phi $_} and push @strong, $_ for @achilles;   say "First 50 Achilles numbers:\n" . table 10, head 50, @achilles; say "First 30 strong Achilles numbers:\n" . table 10, head 30, @strong; say "Number of Achilles numbers with:\n"; for my $l (2..9) { my $c; $l == length and $c++ for @achilles; say "$l digits: $c"; }
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
#Go
Go
package main   import ( "fmt" "math" "strings" )   const threshold = uint64(1) << 47   func indexOf(s []uint64, search uint64) int { for i, e := range s { if e == search { return i } } return -1 }   func contains(s []uint64, search uint64) bool { return indexOf(s, search) > -1 }   func maxOf(i1, i2 int) int { if i1 > i2 { return i1 } return i2 }   func sumProperDivisors(n uint64) uint64 { if n < 2 { return 0 } sqrt := uint64(math.Sqrt(float64(n))) sum := uint64(1) for i := uint64(2); i <= sqrt; i++ { if n % i != 0 { continue } sum += i + n / i } if sqrt * sqrt == n { sum -= sqrt } return sum }   func classifySequence(k uint64) ([]uint64, string) { if k == 0 { panic("Argument must be positive.") } last := k var seq []uint64 seq = append(seq, k) for { last = sumProperDivisors(last) seq = append(seq, last) n := len(seq) aliquot := "" switch { case last == 0: aliquot = "Terminating" case n == 2 && last == k: aliquot = "Perfect" case n == 3 && last == k: aliquot = "Amicable" case n >= 4 && last == k: aliquot = fmt.Sprintf("Sociable[%d]", n - 1) case last == seq[n - 2]: aliquot = "Aspiring" case contains(seq[1 : maxOf(1, n - 2)], last): aliquot = fmt.Sprintf("Cyclic[%d]", n - 1 - indexOf(seq[:], last)) case n == 16 || last > threshold: aliquot = "Non-Terminating" } if aliquot != "" { return seq, aliquot } } }   func joinWithCommas(seq []uint64) string { res := fmt.Sprint(seq) res = strings.Replace(res, " ", ", ", -1) return res }   func main() { fmt.Println("Aliquot classifications - periods for Sociable/Cyclic in square brackets:\n") for k := uint64(1); k <= 10; k++ { seq, aliquot := classifySequence(k) fmt.Printf("%2d: %-15s %s\n", k, aliquot, joinWithCommas(seq)) } fmt.Println()   s := []uint64{ 11, 12, 28, 496, 220, 1184, 12496, 1264460, 790, 909, 562, 1064, 1488, } for _, k := range s { seq, aliquot := classifySequence(k) fmt.Printf("%7d: %-15s %s\n", k, aliquot, joinWithCommas(seq)) } fmt.Println()   k := uint64(15355717786080) seq, aliquot := classifySequence(k) fmt.Printf("%d: %-15s %s\n", k, aliquot, joinWithCommas(seq)) }
http://rosettacode.org/wiki/Add_a_variable_to_a_class_instance_at_runtime
Add a variable to a class instance at runtime
Demonstrate how to dynamically add variables to an object (a class instance) at runtime. This is useful when the methods/variables of an instance are based on a data file that isn't available until runtime. Hal Fulton gives an example of creating an OO CSV parser at An Exercise in Metaprogramming with Ruby. This is referred to as "monkeypatching" by Pythonistas and some others.
#Octave
Octave
  % Given struct "test" test.b=1; test = setfield (test, "c", 3);  
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.
#ooRexx
ooRexx
  d = .dynamicvar~new d~foo = 123 say d~foo   d2 = .dynamicvar2~new d~bar = "Fred" say d~bar   -- a class that allows dynamic variables. Since this is a mixin, this -- capability can be added to any class using multiple inheritance ::class dynamicvar MIXINCLASS object ::method init expose variables variables = .directory~new   -- the UNKNOWN method is invoked for all unknown messages. We turn this -- into either an assignment or a retrieval for the desired item ::method unknown expose variables use strict arg messageName, arguments   -- assignment messages end with '=', which tells us what to do if messageName~right(1) == '=' then do variables[messageName~left(messageName~length - 1)] = arguments[1] end else do return variables[messageName] end     -- this class is not a direct subclass of dynamicvar, but mixes in the -- functionality using multiple inheritance ::class dynamicvar2 inherit dynamicvar ::method init -- mixin init methods are not automatically invoked, so we must -- explicitly invoke this self~init:.dynamicvar    
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.
#OxygenBasic
OxygenBasic
  '================= class fleximembers '=================   indexbase 0 bstring buf, *varl sys dp,en   method addVar(string name,dat) sys le=len buf if dp+16>le then buf+=nuls 0x100 : le+=0x100 : end if @varl=?buf varl[en]=name varl[en+1]=dat dp+=2*sizeof sys en+=2 'next slot end method   method find(string name) as sys sys i for i=0 to <en step 2 if name=varl[i] then return i+1 next end method   method vars(string name) as string sys f=find(name) if f then return varl[f] end method   method VarF(string name) as double return vars(name) end method   method VarI(string name) as sys return vars(name) end method   method vars(string name,dat) bstring varl at buf sys f=find(name) if f then varl[f]=dat end method   method delete() sys i sys v at buf for i=0 to <en freememory v[i] next freememory ?buf  ? buf=0 : en=0 : dp=0 end method   end class   'TEST   fleximembers a   a.addVar "p",5 a.addVar "q",4.5 a.addVar "r","123456"   print a.Vars("q")+a.vars("q") 'result 4.54.5 print a.Varf("q")+a.varf("q") 'result 9   a.delete    
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.
#Panoramic
Panoramic
  == Get ==   adr(variable)   Example:   dim a print adr(a)   == Set ==   Whether Panoramic is able to set the value of a variable may depend on what is meant by that. Panoramic implements the poke command to set a byte from a value of 0 to 255 (inclusive). Panoramic also implements the peek command to get the value of a byte, so it is possible to the following:   (A) dim a rem a variable with no post-fix is a real. poke adr(a),57 rem the value of a variable being set by setting an address, the address of a in this instance.   (B) dim a%,b% rem % means integer. b%=57 poke adr(a%),b% rem b% being assigned to the address of a%, in this instance. rem it is even possible to free b% free b% print a%   (C) dim a,b b=57 poke adr(a),b b=peek(adr(a)) print b rem the address of b being, in effect, set to the address of a, the address of a, in this instance.   rem Observations and further insight welcome.   ''Note:'' An attempt to poke a real or an integer (Panoramic's only numeric types) value of less than 0 or of more than 255 will cause an error.