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/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.
#PARI.2FGP
PARI/GP
issquare(n, &m)
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.
#Pascal
Pascal
use Scalar::Util qw(refaddr); print refaddr(\my $v), "\n"; # 140502490125712
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.
#Perl
Perl
use Scalar::Util qw(refaddr); print refaddr(\my $v), "\n"; # 140502490125712
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.
#Delphi
Delphi
  (lib 'math.lib) ;; 1 - x^p  : P = (1 0 0 0 ... 0 -1) (define (mono p) (append (list 1) (make-list (1- p) 0) (list -1)))   ;; compute (x-1)^p , p >= 1 (define (aks-poly p) (poly-pow (list -1 1) p))   ;; (define (show-them n) (for ((p (in-range 1 n))) (writeln 'p p (poly->string 'x (aks-poly p)))))   ;; aks-test ;; P = (x-1)^p + 1 - x^p (define (aks-test p) (let ((P (poly-add (mono p) (aks-poly p))) (test (lambda(a) (zero? (modulo a p))))) ;; p divides a[i] ? (apply and (map test P)))) ;; returns #t if true for all a[i]  
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.
#FreeBASIC
FreeBASIC
#include "isprime.bas"   function digsum( n as uinteger ) as uinteger dim as uinteger s while n s+=n mod 10 n\=10 wend return s end function   dim as uinteger s   print "Prime","Digit Sum" for i as uinteger = 2 to 499 if isprime(i) then s = digsum(i) if isprime(s) then print i, s end if end if next i
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.
#Free_Pascal
Free Pascal
  Program AdditivePrimes; Const max_number = 500;   Var is_prime : array Of Boolean;   Procedure sieve(Var arr: Array Of boolean ); {use Sieve of Eratosthenes to find all primes to max number} Var i,j : NativeUInt;   Begin For i := 2 To high(arr) Do arr[i] := True; // set all bits to be True For i := 2 To high(arr) Do Begin If (arr[i]) Then For j := 2 To (high(arr) Div i) Do arr[i * j] := False; End; End;   Function GetSumOfDigits(num: NativeUInt): longint; {calcualte the sum of digits of a number} Var sum : longint = 0; dummy: NativeUInt; Begin Repeat dummy := num; num := num Div 10; Inc(sum, dummy - (num SHL 3 + num SHL 1)); Until num < 1; GetSumOfDigits := sum; End;   Var x : NativeUInt = 2; {first prime} counter : longint = 0; Begin setlength(is_prime,max_number); //set length of array to max_number Sieve(is_prime); //apply Sieve   {since 2 is the only even prime, let's do it separate} If is_prime[x] And is_prime[GetSumOfDigits(x)] Then Begin write(x:4); inc(counter); End; inc(x); While x < max_number Do Begin If is_prime[x] And is_prime[GetSumOfDigits(x)] Then Begin if counter mod 10 = 0 then writeln(); write(x:4); inc(counter); End; inc(x,2); End; writeln(); writeln(); writeln(counter,' additive primes found.'); 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
#Tailspin
Tailspin
  processor RedBlackTree data node <{VOID}|{colour: <='black'|='red'>, left: <node>, right: <node>, value: <> VOID}> local @: {}; sink insert templates balance when <{colour: <='black'>, left: <{ colour: <='red'> left: <{colour: <='red'>}>}>}> do { colour: 'red', left: { $.left.left..., colour: 'black'}, value: $.left.value, right: { $..., left: $.left.right }} ! when <{colour: <='black'>, left: <{ colour: <='red'> right: <{colour: <='red'>}>}>}> do { colour: 'red', left: { $.left..., colour: 'black', right: $.left.right.left}, value: $.left.right.value, right: { $..., left: $.left.right.right }} ! when <{colour: <='black'>, right: <{ colour: <='red'> left: <{colour: <='red'>}>}>}> do { colour: 'red', left: { $..., right: $.right.left.left}, value: $.right.left.value, right: { $.right..., colour: 'black', left: $.right.left.right }} ! when <{colour: <='black'>, right: <{ colour: <='red'> right: <{colour: <='red'>}>}>}> do { colour: 'red', left: { $..., right: $.right.left}, value: $.right.value, right: { $.right.right..., colour: 'black' }} ! otherwise $ ! end balance templates ins&{into:} when <?($into <={}>)> do { colour: 'red', left: {}, value: $, right: {}} ! when <..$into.value::raw> do { $into..., left: $ -> ins&{into: $into.left}} -> balance ! otherwise { $into..., right: $ -> ins&{into: $into.right}} -> balance ! end ins @RedBlackTree: { $ -> ins&{into: $@RedBlackTree} ..., colour: 'black'}; end insert source toString '$@RedBlackTree;' ! end toString end RedBlackTree   def tree: $RedBlackTree; 1..5 -> \('$tree::toString;$#10;' -> !OUT::write $ -> !tree::insert \) -> !VOID $tree::toString -> !OUT::write  
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
#Tcl
Tcl
# From http://wiki.tcl.tk/9547 package require Tcl 8.5 package provide datatype 0.1   namespace eval ::datatype { namespace export define match matches namespace ensemble create   # Datatype definitions proc define {type = args} { set ns [uplevel 1 { namespace current }] foreach cons [split [join $args] |] { set name [lindex $cons 0] set args [lrange $cons 1 end] proc $ns\::$name $args [format { lreplace [info level 0] 0 0 %s } [list $name]] } return $type }   # Pattern matching # matches pattern value envVar -- # Returns 1 if value matches pattern, else 0 # Binds match variables in envVar proc matches {pattern value envVar} { upvar 1 $envVar env if {[var? $pattern]} { return [bind env $pattern $value] } if {[llength $pattern] != [llength $value]} { return 0 } if {[lindex $pattern 0] ne [lindex $value 0]} { return 0 } foreach pat [lrange $pattern 1 end] val [lrange $value 1 end] { if {![matches $pat $val env]} { return 0 } } return 1 } # A variable starts with lower-case letter or _. _ is a wildcard. proc var? term { string match {[a-z_]*} $term } proc bind {envVar var value} { upvar 1 $envVar env if {![info exists env]} { set env [dict create] } if {$var eq "_"} { return 1 } dict set env $var $value return 1 } proc match args { #puts "MATCH: $args" set values [lrange $args 0 end-1] set choices [lindex $args end] append choices \n [list return -code error -level 2 "no match for $values"] set f [list values $choices [namespace current]] lassign [apply $f $values] env body #puts "RESULT: $env -> $body" dict for {k v} $env { upvar 1 $k var; set var $v } catch { uplevel 1 $body } msg opts dict incr opts -level return -options $opts $msg } proc case args { upvar 1 values values set patterns [lrange $args 0 end-2] set body [lindex $args end] set env [dict create] if {[llength $patterns] != [llength $values]} { return } foreach pattern $patterns value $values { if {![matches $pattern $value env]} { return } } return -code return [list $env $body] } proc default body { return -code return [list {} $body] } }  
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
#Icon_and_Unicon
Icon and Unicon
link "factors"   procedure main() every writes(k := 1 to 5,": ") do every writes(right(genKap(k),5)\10|"\n") end   procedure genKap(k) suspend (k = *factors(n := seq(q)), n) end
http://rosettacode.org/wiki/Anagrams
Anagrams
When two or more words are composed of the same characters, but in a different order, they are called anagrams. Task[edit] Using the word list at   http://wiki.puzzlers.org/pub/wordlists/unixdict.txt, find the sets of words that share the same characters that contain the most words in them. Related tasks Word plays Ordered words Palindrome detection Semordnilap Anagrams Anagrams/Deranged anagrams Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#Crystal
Crystal
require "http/client"   response = HTTP::Client.get("http://wiki.puzzlers.org/pub/wordlists/unixdict.txt")   if response.body? words : Array(String) = response.body.split   anagram = {} of String => Array(String)   words.each do |word| key = word.split("").sort.join   if !anagram[key]? anagram[key] = [word] else anagram[key] << word end end   count = anagram.values.map { |ana| ana.size }.max anagram.each_value { |ana| puts ana if ana.size >= count } end  
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
#PowerShell
PowerShell
  <# .Synopsis Gets the difference between two angles between the values of -180 and 180. To see examples use "Get-Examples" .DESCRIPTION This code uses the modulo operator, this is represented with the "%". The modulo operator returns the remainder after division, as displayed below 3 % 2 = 1 20 % 15 = 5 200 % 146 = 54   .EXAMPLE PS C:\WINDOWS\system32> Get-AngleDiff cmdlet Get-AngleDiff at command pipeline position 1 Supply values for the following parameters: angle1: 45 angle2: -85   The difference between 45 and -85 is -130   PS C:\WINDOWS\system32>   .EXAMPLE PS C:\WINDOWS\system32> Get-AngleDiff -angle1 50 -angle2 -65   The difference between 50 and -65 is -115   PS C:\WINDOWS\system32>   .EXAMPLE PS C:\WINDOWS\system32> Get-AngleDiff -89 50   The difference between -89 and 50 is 139   PS C:\WINDOWS\system32>     #> function Get-AngleDiff { [CmdletBinding()]   Param ( # Angle one input, must be a number [Parameter(Mandatory=$true, ValueFromPipelineByPropertyName=$true)][double]$angle1,   # Angle two input, must be a number [Parameter(Mandatory=$true, ValueFromPipelineByPropertyName=$true)][double]$angle2 )   Begin { #This is the equation to calculate the difference [double]$Difference = ($angle2 - $angle1) % 360.0 }   Process { #If/IfElse/Else block to return results within the requested range if ($Difference -lt -180.0) {$Difference += 360.0 }   elseif ($Difference -gt 360.0) {$Difference -= 360.0 }   #Writes the values given by the user and the result Write-Host "The difference between $angle1 and $angle2 is $Difference" }   End { }   }   <# .Synopsis This is simply the outputs of the Get-AngleDiff Function in a function .EXAMPLE PS C:\WINDOWS\system32> Get-Examples   Inputs from the -180 to 180 range The difference between 20 and 45 is 25 The difference between -45 and 45 is 90 The difference between -85 and 90 is 175 The difference between -95 and 90 is 185 The difference between -45 and 125 is 170 The difference between -45 and 145 is 190 The difference between -45 and 125 is 170 The difference between -45 and 145 is 190 The difference between 29.4803 and -88.6381 is -118.1184 The difference between -78.3251 and -159.036 is -80.7109   Inputs from a wider range The difference between -70099.7423381094 and 29840.6743787672 is 220.416716876614 The difference between -165313.666629736 and 33693.9894517456 is 287.656081481313 The difference between 1174.83805105985 and -154146.664901248 is -161.502952307404 The difference between 60175.7730679555 and 42213.0719235437 is 37.2988555882694   PS C:\WINDOWS\system32> #>   function Get-Examples { #blank write-host is used for a blank line to make the output look a lil cleaner Write-Host Write-Host "Inputs from the -180 to 180 range"   Get-AngleDiff 20.0 45.0 Get-AngleDiff -45.0 45.0 Get-AngleDiff -85.0 90.0 Get-AngleDiff -95.0 90.0 Get-AngleDiff -45.0 125.0 Get-AngleDiff -45.0 145.0 Get-AngleDiff -45.0 125.0 Get-AngleDiff -45.0 145.0 Get-AngleDiff 29.4803 -88.6381 Get-AngleDiff -78.3251 -159.036   Write-Host Write-Host "Inputs from a wider range"   Get-AngleDiff -70099.74233810938 29840.67437876723 Get-AngleDiff -165313.6666297357 33693.9894517456 Get-AngleDiff 1174.8380510598456 -154146.66490124757 Get-AngleDiff 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
#Racket
Racket
#lang racket (define word-list-file "data/unixdict.txt")   (define (read-words-into-anagram-keyed-hash) (define (anagram-key word) (sort (string->list word) char<?)) (for/fold ((hsh (hash))) ((word (in-lines))) (hash-update hsh (anagram-key word) (curry cons word) null)))   (define anagrams-list (sort (for/list ((v (in-hash-values (with-input-from-file word-list-file read-words-into-anagram-keyed-hash))) #:when (> (length v) 1)) v) > #:key (compose string-length first)))     (define (deranged-anagram-pairs l (acc null)) (define (deranged-anagram-pair? hd tl) (define (first-underanged-char? hd tl) (for/first (((c h) (in-parallel hd tl)) #:when (char=? c h)) c)) (not (first-underanged-char? hd tl)))   (if (null? l) acc (let ((hd (car l)) (tl (cdr l))) (deranged-anagram-pairs tl (append acc (map (lambda (x) (list hd x)) (filter (curry deranged-anagram-pair? hd) tl)))))))   ;; for*/first give the first set of deranged anagrams (as per the RC problem) ;; for*/list gives a full list of the sets of deranged anagrams (which might be interesting) (for*/first ((anagrams (in-list anagrams-list)) (daps (in-value (deranged-anagram-pairs anagrams))) #:unless (null? daps)) daps)
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.
#Ol
Ol
  (define (fibonacci n) (if (> 0 n) "error: negative argument." (let loop ((a 1) (b 0) (count n)) (if (= count 0) b (loop (+ a b) a (- count 1))))))   (print (map fibonacci '(1 2 3 4 5 6 7 8 9 10)))  
http://rosettacode.org/wiki/Amicable_pairs
Amicable pairs
Two integers N {\displaystyle N} and M {\displaystyle M} are said to be amicable pairs if N ≠ M {\displaystyle N\neq M} and the sum of the proper divisors of N {\displaystyle N} ( s u m ( p r o p D i v s ( N ) ) {\displaystyle \mathrm {sum} (\mathrm {propDivs} (N))} ) = M {\displaystyle =M} as well as s u m ( p r o p D i v s ( M ) ) = N {\displaystyle \mathrm {sum} (\mathrm {propDivs} (M))=N} . Example 1184 and 1210 are an amicable pair, with proper divisors:   1, 2, 4, 8, 16, 32, 37, 74, 148, 296, 592   and   1, 2, 5, 10, 11, 22, 55, 110, 121, 242, 605   respectively. Task Calculate and show here the Amicable pairs below 20,000; (there are eight). Related tasks Proper divisors Abundant, deficient and perfect number classifications Aliquot sequence classifications and its amicable classification.
#Nim
Nim
  from math import sqrt   const N = 524_000_000.int32   proc sumProperDivisors(someNum: int32, chk4less: bool): int32 = result = 1 let maxPD = sqrt(someNum.float).int32 let offset = someNum mod 2 for divNum in countup(2 + offset, maxPD, 1 + offset): if someNum mod divNum == 0: result += divNum + someNum div divNum if chk4less and result >= someNum: return 0   for n in countdown(N, 2): let m = sumProperDivisors(n, true) if m != 0 and n == sumProperDivisors(m, false): echo $n, " ", $m  
http://rosettacode.org/wiki/Animation
Animation
Animation is integral to many parts of GUIs, including both the fancy effects when things change used in window managers, and of course games.   The core of any animation system is a scheme for periodically changing the display while still remaining responsive to the user.   This task demonstrates this. Task Create a window containing the string "Hello World! " (the trailing space is significant). Make the text appear to be rotating right by periodically removing one letter from the end of the string and attaching it to the front. When the user clicks on the (windowed) text, it should reverse its direction.
#ZX_Spectrum_Basic
ZX Spectrum Basic
10 LET t$="Hello world! ": LET lt=LEN t$ 20 LET direction=1 30 PRINT AT 0,0;t$ 40 IF direction THEN LET t$=t$(2 TO )+t$(1): GO TO 60 50 LET t$=t$(lt)+t$( TO lt-1) 60 IF INKEY$<>"" THEN LET direction=NOT direction 70 PAUSE 5: GO TO 30
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.
#PureBasic
PureBasic
Procedure handleError(x, msg.s) If Not x MessageRequester("Error", msg) End EndIf EndProcedure   #ScreenW = 320 #ScreenH = 210 handleError(OpenWindow(0, 0, 0, #ScreenW, #ScreenH, "Animated Pendulum", #PB_Window_SystemMenu), "Can't open window.") handleError(InitSprite(), "Can't setup sprite display.") handleError(OpenWindowedScreen(WindowID(0), 0, 0, #ScreenW, #ScreenH, 0, 0, 0), "Can't open screen.")   Enumeration ;sprites #bob_spr #ceiling_spr #pivot_spr EndEnumeration   TransparentSpriteColor(#PB_Default, RGB(255, 0, 255)) CreateSprite(#bob_spr, 32, 32) StartDrawing(SpriteOutput(#bob_spr)) Box(0, 0, 32, 32, RGB(255, 0, 255)) Circle(16, 16, 15, RGB(253, 252, 3)) DrawingMode(#PB_2DDrawing_Outlined) Circle(16, 16, 15, RGB(0, 0, 0)) StopDrawing()   CreateSprite(#pivot_spr, 10, 10) StartDrawing(SpriteOutput(#pivot_spr)) Box(0, 0, 10, 10, RGB(255, 0, 255)) Circle(5, 5, 4, RGB(125, 125, 125)) DrawingMode(#PB_2DDrawing_Outlined) Circle(5, 5, 4, RGB(0,0 , 0)) StopDrawing()   CreateSprite(#ceiling_spr,#ScreenW,2) StartDrawing(SpriteOutput(#ceiling_spr)) Box(0,0,SpriteWidth(#ceiling_spr), SpriteHeight(#ceiling_spr), RGB(126, 126, 126)) StopDrawing()   Structure pendulum length.d ; meters constant.d ; -g/l gravity.d ; m/s² angle.d ; radians velocity.d ; m/s EndStructure   Procedure initPendulum(*pendulum.pendulum, length.d = 1.0, gravity.d = 9.81, initialAngle.d = #PI / 2) With *pendulum \length = length \gravity = gravity \angle = initialAngle \constant = -gravity / length \velocity = 0.0 EndWith EndProcedure     Procedure updatePendulum(*pendulum.pendulum, deltaTime.d) deltaTime = deltaTime / 1000.0 ;ms Protected acceleration.d = *pendulum\constant * Sin(*pendulum\angle) *pendulum\velocity + acceleration * deltaTime *pendulum\angle + *pendulum\velocity * deltaTime EndProcedure   Procedure drawBackground() ClearScreen(RGB(190,190,190)) ;draw ceiling DisplaySprite(#ceiling_spr, 0, 47) ;draw pivot DisplayTransparentSprite(#pivot_spr, 154,43) ;origin in upper-left EndProcedure   Procedure drawPendulum(*pendulum.pendulum) ;draw rod Protected x = *pendulum\length * 140 * Sin(*pendulum\angle) ;scale = 1 m/140 pixels Protected y = *pendulum\length * 140 * Cos(*pendulum\angle) StartDrawing(ScreenOutput()) LineXY(154 + 5,43 + 5, 154 + 5 + x, 43 + 5 + y) ;draw from pivot-center to bob-center, adjusting for origins StopDrawing()   ;draw bob DisplayTransparentSprite(#bob_spr, 154 + 5 - 16 + x, 43 + 5 - 16 + y) ;adj for origin in upper-left EndProcedure   Define pendulum.pendulum, event initPendulum(pendulum) drawPendulum(pendulum)   AddWindowTimer(0, 1, 50) Repeat event = WindowEvent() Select event Case #pb_event_timer drawBackground() Select EventTimer() Case 1 updatePendulum(pendulum, 50) drawPendulum(pendulum) EndSelect FlipBuffers() Case #PB_Event_CloseWindow Break EndSelect ForEver
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.
#Haxe
Haxe
class RosettaDemo { static var setA = ['the', 'that', 'a']; static var setB = ['frog', 'elephant', 'thing']; static var setC = ['walked', 'treaded', 'grows']; static var setD = ['slowly', 'quickly'];   static public function main() { Sys.print(ambParse([ setA, setB, setC, setD ]).toString()); }   static function ambParse(sets : Array<Array<String>>) { var ambData : Dynamic = amb(sets);   for (data in 0...ambData.length) { var tmpData = parseIt(ambData[data]); var tmpArray = tmpData.split(' '); tmpArray.pop(); if (tmpArray.length == sets.length) { return tmpData; } }   return ''; }   static function amb(startingWith : String = '', sets : Array<Array<String>>) : Dynamic { if (sets.length == 0 || sets[0].length == 0) return;   var match : Dynamic = []; for (reference in sets[0]) { if (startingWith == '' || startingWith == reference.charAt(0)) { var lastChar = reference.charAt(reference.length-1); if (Std.is(amb(lastChar, sets.slice(1)), Array)) { match.push([ reference, amb(lastChar, sets.slice(1))]); } else { match.push([ reference ]); } } } return match; }   static function parseIt(data : Dynamic) { var retData = ''; if (Std.is(data, Array)) { for (elements in 0...data.length) { if (Std.is(data[elements], Array)) { retData = retData + parseIt(data[elements]); } else { retData = retData + data[elements] + ' '; } } } return retData; } }
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.
#Astro
Astro
fun accumulator(var sum): :: Real -> _ n => sum += n   let f = accumulator!(5) print f(5) # 10 print f(10) # 20 print f(2.4) # 22.4
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.
#BBC_BASIC
BBC BASIC
x = FNaccumulator(1) dummy = FN(x)(5) dummy = FNaccumulator(3) PRINT FN(x)(2.3) END   DEF FNaccumulator(sum) LOCAL I%, P%, Q% DIM P% 53 : Q% = !^FNdummy() FOR I% = 0 TO 49 : P%?I% = Q%?I% : NEXT P%!I% = P% : sum = FN(P%+I%)(sum) = P%+I%   DEF FNdummy(n) PRIVATE sum sum += n = sum
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
#8086_Assembly
8086 Assembly
LIMIT: equ 20000 cpu 8086 org 100h mov ax,data ; Set DS and ES to point right after the mov cl,4 ; program, so we can store the array there shr ax,cl mov dx,cs add ax,dx inc ax mov ds,ax mov es,ax mov ax,1 ; Set each element to 1 at the beginning xor di,di mov cx,LIMIT+1 rep stosw mov [2],cx ; Except the value for 1, which is 0 mov bp,LIMIT/2 ; BP = limit / 2 - keep values ready in regs mov di,LIMIT ; DI = limit oloop: inc ax ; Let AX be the outer loop counter (divisor) cmp ax,bp ; Are we there yet? ja clsfy ; If so, stop mov dx,ax ; Let DX be the inner loop counter (number) iloop: add dx,ax cmp dx,di ; Are we there yet? ja oloop ; Loop mov bx,dx ; Each entry is 2 bytes wide shl bx,1 add [bx],ax ; Add divisor to number jmp iloop clsfy: xor bp,bp ; BP = deficient number counter xor dx,dx ; DX = perfect number counter xor cx,cx ; CX = abundant number counter xor bx,bx ; BX = current number under consideration mov si,2 ; SI = pointer to divsum of current number cloop: inc bx ; Next number cmp bx,di ; Are we done yet? ja done ; If so, stop lodsw ; Otherwise, get divsum of current number cmp ax,bx ; Compare to current number jb defic ; If smaller, the number is deficient je prfct ; If equal, the number is perfect inc cx ; Otherwise, the number is abundant jmp cloop defic: inc bp jmp cloop prfct: inc dx jmp cloop done: mov ax,cs ; Set DS and ES back to the code segment mov ds,ax mov es,ax mov di,dx ; Move the perfect numbers to DI mov dx,sdef ; Print "Deficient" call prstr mov ax,bp ; Print amount of deficient numbers call prnum mov dx,sper ; Print "Perfect" call prstr mov ax,di ; Print amount of perfect numbers call prnum mov dx,sabn ; Print "Abundant" call prstr mov ax,cx ; Print amount of abundant numbers prnum: mov bx,snum ; Print number in AX pdgt: xor dx,dx div word [ten] ; Extract digit dec bx ; Move pointer add dl,'0' mov [bx],dl ; Store digit test ax,ax ; Any more digits? jnz pdgt mov dx,bx ; Print string prstr: mov ah,9 int 21h ret ten: dw 10 ; Divisor for number output routine sdef: db 'Deficient: $' sper: db 'Perfect: $' sabn: db 'Abundant: $' db '.....' snum: db 13,10,'$' data: equ $
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
#ALGOL_68
ALGOL 68
STRING nl = REPR 10; STRING text in list := "Given$a$text$file$of$many$lines,$where$fields$within$a$line$"+nl+ "are$delineated$by$a$single$'dollar'$character,$write$a$program"+nl+ "that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$"+nl+ "column$are$separated$by$at$least$one$space."+nl+ "Further,$allow$for$each$word$in$a$column$to$be$either$left$"+nl+ "justified,$right$justified,$or$center$justified$within$its$column.";   MODE PAGE = FLEX[0,0]STRING; PAGE page;   PROC flex page = (PAGE in page, INT row, col)PAGE:( HEAP FLEX[row, col]STRING out page; out page[:1 UPB in page, :2 UPB in page] := in page; FOR r TO row DO FOR c FROM 2 UPB in page + 1 TO col DO out page[r,c]:="" OD OD; FOR r FROM 1 UPB in page + 1 TO row DO FOR c FROM 1 TO col DO out page[r,c]:="" OD OD; out page );   FILE text in file; associate(text in file, text in list); make term(text in file, "$");   on physical file end(text in file, (REF FILE skip)BOOL: stop iteration); on logical file end(text in file, (REF FILE skip)BOOL: stop iteration); FOR row DO on line end(text in file, (REF FILE skip)BOOL: stop iteration); FOR col DO STRING tok; getf(text in file, ($gx$,tok)); IF row > 1 UPB page THEN page := flex page(page, row, 2 UPB page) FI; IF col > 2 UPB page THEN page := flex page(page, 1 UPB page, col) FI; page[row,col]:=tok OD; stop iteration: SKIP OD; stop iteration: SKIP;   BEGIN PROC aligner = (PAGE in page, PROC (STRING,INT)STRING aligner)VOID:( PAGE page := in page; [2 UPB page]INT max width; FOR col TO 2 UPB page DO INT max len:=0; FOR row TO UPB page DO IF UPB page[row,col]>max len THEN max len:=UPB page[row,col] FI OD; FOR row TO UPB page DO page[row,col] := aligner(page[row,col], maxlen) OD OD; printf(($n(UPB page)(n(2 UPB page -1)(gx)gl)$,page)) );   PROC left = (STRING in, INT len)STRING: in + " "*(len - UPB in), right = (STRING in, INT len)STRING: " "*(len - UPB in) + in, centre = (STRING in, INT len)STRING: ( INT pad=len-UPB in; pad%2*" "+ in + (pad-pad%2)*" " );   []STRUCT(STRING name, PROC(STRING,INT)STRING align) aligners = (("Left",left), ("Left",right), ("Centre",centre));   FOR index TO UPB aligners DO print((new line, "# ",name OF aligners[index]," Column-aligned output:",new line)); aligner(page, align OF aligners[index]) OD END
http://rosettacode.org/wiki/Active_object
Active object
In object-oriented programming an object is active when its state depends on clock. Usually an active object encapsulates a task that updates the object's state. To the outer world the object looks like a normal object with methods that can be called from outside. Implementation of such methods must have a certain synchronization mechanism with the encapsulated task in order to prevent object's state corruption. A typical instance of an active object is an animation widget. The widget state changes with the time, while as an object it has all properties of a normal widget. The task Implement an active integrator object. The object has an input and output. The input can be set using the method Input. The input is a function of time. The output can be queried using the method Output. The object integrates its input over the time and the result becomes the object's output. So if the input is K(t) and the output is S, the object state S is changed to S + (K(t1) + K(t0)) * (t1 - t0) / 2, i.e. it integrates K using the trapeze method. Initially K is constant 0 and S is 0. In order to test the object: set its input to sin (2π f t), where the frequency f=0.5Hz. The phase is irrelevant. wait 2s set the input to constant 0 wait 0.5s Verify that now the object's output is approximately 0 (the sine has the period of 2s). The accuracy of the result will depend on the OS scheduler time slicing and the accuracy of the clock.
#Delphi
Delphi
  program Active_object;   {$APPTYPE CONSOLE}   uses System.SysUtils, System.Classes;   type TIntegrator = class(TThread) private { Private declarations } interval, s: double; IsRunning: Boolean; protected procedure Execute; override; public k: Tfunc<Double, Double>; constructor Create(k: Tfunc<Double, Double>; inteval: double = 1e-4); overload; procedure Join; end;   { TIntegrator }   constructor TIntegrator.Create(k: Tfunc<Double, Double>; inteval: double = 1e-4); begin self.interval := Interval; self.K := k; self.S := 0.0; IsRunning := True; FreeOnTerminate := True; inherited Create(false); end;   procedure TIntegrator.Execute; var interval, t0, k0, t1, k1: double; start: Cardinal; begin inherited;   interval := self.interval; start := GetTickCount; t0 := 0; k0 := self.K(0);   while IsRunning do begin t1 := (GetTickCount - start) / 1000; k1 := self.K(t1); self.S := self.S + ((k1 + k0) * (t1 - t0) / 2.0); t0 := t1; k0 := k1; end; end;   procedure TIntegrator.Join; begin IsRunning := false; end;   var Integrator: TIntegrator;   begin Integrator := TIntegrator.create( function(t: double): double begin Result := sin(pi * t); end);   sleep(2000);   Writeln(Integrator.s);   Integrator.k := function(t: double): double begin Result := 0; end;   sleep(500); Writeln(Integrator.s); Integrator.Join; Readln; end.
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
#Phix
Phix
with javascript_semantics requires("1.0.2") -- [join_by(fmt)] atom t0 = time() constant maxDigits = iff(platform()=JS?10:12) integer pps = new_dict() procedure getPerfectPowers(integer maxExp) atom hi = power(10, maxExp) integer imax = floor(sqrt(hi)) for i=2 to imax do atom p = i while true do p *= i if p>=hi then exit end if setd(p,true,pps) end while end for end procedure function get_achilles(integer minExp, maxExp) atom lo10 = power(10,minExp), hi10 = power(10,maxExp) integer bmax = floor(power(hi10,1/3)), amax = floor(sqrt(hi10)) sequence achilles = {} for b=2 to bmax do atom b3 = b * b * b for a=2 to amax do atom p = b3 * a * a if p>=hi10 then exit end if if p>=lo10 then integer node = getd_index(p,pps) if node=NULL then achilles &= p end if end if end for end for achilles = unique(achilles) return achilles end function getPerfectPowers(maxDigits) sequence achilles = get_achilles(1,5) function strong_achilles(integer n) integer totient = sum(sq_eq(apply(true,gcd,{tagset(n),n}),1)) return find(totient,achilles) end function sequence a = join_by(achilles[1..50],1,10," ",fmt:="%4d"), sa = filter(achilles,strong_achilles)[1..30], ssa = join_by(sa,1,10," ",fmt:="%5d") printf(1,"First 50 Achilles numbers:\n%s\n",{a}) printf(1,"First 30 strong Achilles numbers:\n%s\n",{ssa}) for d=2 to maxDigits do printf(1,"Achilles numbers with %d digits:%d\n",{d,length(get_achilles(d-1,d))}) end for ?elapsed(time()-t0)
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
#Haskell
Haskell
divisors :: (Integral a) => a -> [a] divisors n = filter ((0 ==) . (n `mod`)) [1 .. (n `div` 2)]   data Class = Terminating | Perfect | Amicable | Sociable | Aspiring | Cyclic | Nonterminating deriving (Show)   aliquot :: (Integral a) => a -> [a] aliquot 0 = [0] aliquot n = n : (aliquot $ sum $ divisors n)   classify :: (Num a, Eq a) => [a] -> Class classify [] = Nonterminating classify [0] = Terminating classify [_] = Nonterminating classify [a,b] | a == b = Perfect | b == 0 = Terminating | otherwise = Nonterminating classify x@(a:b:c:_) | a == b = Perfect | a == c = Amicable | a `elem` (drop 1 x) = Sociable | otherwise = case classify (drop 1 x) of Perfect -> Aspiring Amicable -> Cyclic Sociable -> Cyclic d -> d   main :: IO () main = do let cls n = let ali = take 16 $ aliquot n in (classify ali, ali) mapM_ (print . cls) $ [1..10] ++ [11, 12, 28, 496, 220, 1184, 12496, 1264460, 790, 909, 562, 1064, 1488]
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.
#Oz
Oz
declare %% Creates a new class derived from BaseClass %% with an added feature (==public immutable attribute) fun {AddFeature BaseClass FeatureName FeatureValue} class DerivedClass from BaseClass feat %% "FeatureName" is escaped, otherwise a new variable %% refering to a private feature would be created !FeatureName:FeatureValue end in DerivedClass end   class Base feat bar:1   meth init skip end end   Derived = {AddFeature Base foo 2}   Instance = {New Derived init} in {Show Instance.bar} %% inherited feature {Show Instance.foo} %% feature of "synthesized" class
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.
#Perl
Perl
package Empty;   # Constructor. Object is hash. sub new { return bless {}, shift; }   package main;   # Object. my $o = Empty->new;   # Set runtime variable (key => value). $o->{'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.
#Phix
Phix
class wobbly dynamic -- (pre-define a few fields/methods if you like) end class wobbly wobble = new() ?wobble.jelly -- 0 --?wobble["jelly"] -- for dynamic names use [] wobble.jelly = "green" ?wobble.jelly -- "green"
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.
#Phix
Phix
procedure address() object V integer addr4 -- stored /4 (assuming dword aligned, which it will be) #ilASM{ [32] lea eax,[V] shr eax,2 mov [addr4],eax [64] lea rax,[V] shr rax,2 mov [addr4],rax [] } if machine_bits()=32 then poke4(addr4*4,123) elsif machine_bits()=64 then poke8(addr4*4,123) end if ?V if getc(0) then end if end procedure address()
http://rosettacode.org/wiki/Address_of_a_variable
Address of a variable
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation | Comparison | Matching Memory Operations Pointers & references | Addresses Task Demonstrate how to get the address of a variable and how to set the address of a variable.
#PicoLisp
PicoLisp
: (setq X 7) -> 7   : (adr 'X) -> -2985527269106   : (val (adr -2985527269106)) -> 7   : (set (adr -2985527269106) '(a b c)) -> (a b c)   : X -> (a b c)
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.
#PL.2FI
PL/I
  declare addr builtin; /* retrieve address of a variable */ declare ptradd builtin; /* pointer addition */ declare cstg builtin; /* retrieve length of the storage of a variable */ declare hbound builtin; /* retrieve the number of elements in an array */   declare p pointer; declare i bin fixed(31) init(42); p = addr(i); /* Obtain address of variable, stored in integer variable k */   /* how to read a string bit by bit - example for pointerAdd */ /* we built a pointer (movingPointer), which will move through the */ /* storage of a variable (exampleTxt). attached to the pointer is */ /* an array of bits (movingBit) - this means wherever the pointer */ /* is pointing to, this will also be the position of the array. */ /* only whole bytes can be addressed. to get down to the single bits, */ /* an array of 8 bits is used. */   declare exampleTxt char(16) init('Hello MainFrame!); declare movingPointer pointer; declare movingBit(8) bit(01) based(movingPointer);   declare walkOffset bin fixed(31); declare walkBit bin fixed(31);   do walkOffset = 0 to cstg(exampleTxt)-1; movingPointer = ptradd(addr(exampleTxt, walkOffset);   do walkBit = 1 to hbound(movingBit); put skip list( 'bit at Byte '  !!walkOffset  !!' and position '!!walkBit  !!' is '  !!movingBit(walkBit)); end; end;  
http://rosettacode.org/wiki/AKS_test_for_primes
AKS test for primes
The AKS algorithm for testing whether a number is prime is a polynomial-time algorithm based on an elementary theorem about Pascal triangles. The theorem on which the test is based can be stated as follows:   a number   p {\displaystyle p}   is prime   if and only if   all the coefficients of the polynomial expansion of ( x − 1 ) p − ( x p − 1 ) {\displaystyle (x-1)^{p}-(x^{p}-1)} are divisible by   p {\displaystyle p} . Example Using   p = 3 {\displaystyle p=3} : (x-1)^3 - (x^3 - 1) = (x^3 - 3x^2 + 3x - 1) - (x^3 - 1) = -3x^2 + 3x And all the coefficients are divisible by 3,   so 3 is prime. Note: This task is not the AKS primality test.   It is an inefficient exponential time algorithm discovered in the late 1600s and used as an introductory lemma in the AKS derivation. Task Create a function/subroutine/method that given   p {\displaystyle p}   generates the coefficients of the expanded polynomial representation of   ( x − 1 ) p {\displaystyle (x-1)^{p}} . Use the function to show here the polynomial expansions of   ( x − 1 ) p {\displaystyle (x-1)^{p}}   for   p {\displaystyle p}   in the range   0   to at least   7,   inclusive. Use the previous function in creating another function that when given   p {\displaystyle p}   returns whether   p {\displaystyle p}   is prime using the theorem. Use your test to generate a list of all primes under   35. As a stretch goal,   generate all primes under   50   (needs integers larger than 31-bit). References Agrawal-Kayal-Saxena (AKS) primality test (Wikipedia) Fool-Proof Test for Primes - Numberphile (Video). The accuracy of this video is disputed -- at best it is an oversimplification.
#EchoLisp
EchoLisp
  (lib 'math.lib) ;; 1 - x^p  : P = (1 0 0 0 ... 0 -1) (define (mono p) (append (list 1) (make-list (1- p) 0) (list -1)))   ;; compute (x-1)^p , p >= 1 (define (aks-poly p) (poly-pow (list -1 1) p))   ;; (define (show-them n) (for ((p (in-range 1 n))) (writeln 'p p (poly->string 'x (aks-poly p)))))   ;; aks-test ;; P = (x-1)^p + 1 - x^p (define (aks-test p) (let ((P (poly-add (mono p) (aks-poly p))) (test (lambda(a) (zero? (modulo a p))))) ;; p divides a[i] ? (apply and (map test P)))) ;; returns #t if true for all a[i]  
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.
#Frink
Frink
vals = toArray[select[primes[2, 500], {|x| isPrime[sum[integerDigits[x]]]}]] println[formatTable[columnize[vals, 10]]] println["\n" + length[vals] + " values found."]
http://rosettacode.org/wiki/Additive_primes
Additive primes
Definitions In mathematics, additive primes are prime numbers for which the sum of their decimal digits are also primes. Task Write a program to determine (and show here) all additive primes less than 500. Optionally, show the number of additive primes. Also see   the OEIS entry:   A046704 additive primes.   the prime-numbers entry:   additive primes.   the geeks for geeks entry: additive prime number.   the prime-numbers fandom: additive primes.
#Go
Go
package main   import "fmt"   func isPrime(n int) bool { switch { case n < 2: return false case n%2 == 0: return n == 2 case n%3 == 0: return n == 3 default: d := 5 for d*d <= n { if n%d == 0 { return false } d += 2 if n%d == 0 { return false } d += 4 } return true } }   func sumDigits(n int) int { sum := 0 for n > 0 { sum += n % 10 n /= 10 } return sum }   func main() { fmt.Println("Additive primes less than 500:") i := 2 count := 0 for { if isPrime(i) && isPrime(sumDigits(i)) { count++ fmt.Printf("%3d ", i) if count%10 == 0 { fmt.Println() } } if i > 2 { i += 2 } else { i++ } if i > 499 { break } } fmt.Printf("\n\n%d additive primes found.\n", count) }
http://rosettacode.org/wiki/Algebraic_data_types
Algebraic data types
Some languages offer direct support for algebraic data types and pattern matching on them. While this of course can always be simulated with manual tagging and conditionals, it allows for terse code which is easy to read, and can represent the algorithm directly. Task As an example, implement insertion in a red-black-tree. A red-black-tree is a binary tree where each internal node has a color attribute red or black. Moreover, no red node can have a red child, and every path from the root to an empty node must contain the same number of black nodes. As a consequence, the tree is balanced, and must be re-balanced after an insertion. Reference Red-Black Trees in a Functional Setting
#Wren
Wren
var R = "R" var B = "B"   class Tree { ins(x) {} // overridden by child classes   insert(x) { // inherited by child classes var t = ins(x) if (t.type == T) return T.new(B, t.le, t.aa, t.ri) if (t.type == E) return E.new() return null } }   class T is Tree { construct new(cl, le, aa, ri) { _cl = cl // color _le = le // Tree _aa = aa // integer _ri = ri // Tree }   cl { _cl } le { _le } aa { _aa } ri { _ri }   balance() { if (_cl != B) return this   var le2 = _le.type == T ? _le : null var lele var leri if (le2) { lele = _le.le.type == T ? _le.le : null leri = _le.ri.type == T ? _le.ri : null } var ri2 = _ri.type == T ? _ri : null var rile var riri if (ri2) { rile = _ri.le.type == T ? _ri.le : null riri = _ri.ri.type == T ? _ri.ri : null }   if (le2 && lele && le2.cl == R && lele.cl == R) { var t = le2.le return T.new(R, T.new(B, t.le, t.aa, t.ri), le2.aa, T.new(B, le2.ri, _aa, _ri)) } if (le2 && leri && le2.cl == R && leri.cl == R) { var t = le2.ri return T.new(R, T.new(B, le2.le, le2.aa, t.le), t.aa, T.new(B, t.ri, _aa, _ri)) } if (ri2 && rile && ri2.cl == R && rile.cl == R) { var t = ri2.ri return T.new(R, T.new(B, _le, _aa, t.le), t.aa, T.new(B, t.ri, ri2.aa, ri2.ri)) } if (ri2 && riri && ri2.cl == R && riri.cl == R) { var t = ri2.ri return T.new(R, T.new(B, _le, _aa, ri2.le), ri2.aa, T.new(B, t.le, t.aa, t.ri)) } return this }   ins(x) { if (x < _aa) return T.new(_cl, _le.ins(x), _aa, _ri).balance() if (x > _aa) return T.new(_cl, _le, _aa, _ri.ins(x)).balance() return this }   toString { "T(%(_cl), %(_le), %(_aa), %(_ri))" } }   class E is Tree { construct new() {}   ins(x) { T.new(R, E.new(), x, E.new()) }   toString { "E" } }   var tr = E.new() for (i in 1..16) tr = tr.insert(i) System.print(tr)
http://rosettacode.org/wiki/Almost_prime
Almost prime
A   k-Almost-prime   is a natural number   n {\displaystyle n}   that is the product of   k {\displaystyle k}   (possibly identical) primes. Example 1-almost-primes,   where   k = 1 {\displaystyle k=1} ,   are the prime numbers themselves. 2-almost-primes,   where   k = 2 {\displaystyle k=2} ,   are the   semiprimes. Task Write a function/method/subroutine/... that generates k-almost primes and use it to create a table here of the first ten members of k-Almost primes for   1 <= K <= 5 {\displaystyle 1<=K<=5} . Related tasks   Semiprime   Category:Prime Numbers
#J
J
(10 {. [:~.[:/:~[:,*/~)^:(i.5)~p:i.10 2 3 5 7 11 13 17 19 23 29 4 6 9 10 14 15 21 22 25 26 8 12 18 20 27 28 30 42 44 45 16 24 36 40 54 56 60 81 84 88 32 48 72 80 108 112 120 162 168 176
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
#D
D
import std.stdio, std.algorithm, std.string, std.exception, std.file;   void main() { string[][ubyte[]] an; foreach (w; "unixdict.txt".readText.splitLines) an[w.dup.representation.sort().release.assumeUnique] ~= w; immutable m = an.byValue.map!q{ a.length }.reduce!max; writefln("%(%s\n%)", an.byValue.filter!(ws => ws.length == m)); }
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
#PureBasic
PureBasic
Procedure.f getDifference (b1.f, b2.f) r.f = Mod((b2 - b1), 360) If r >= 180: r - 360 EndIf PrintN(StrF(b1) + #TAB$ + StrF(b2) + #TAB$ + StrF(r)); EndProcedure   If OpenConsole() PrintN("Input in -180 to +180 range:") getDifference(20.0, 45.0) getDifference(-45.0, 45.0) getDifference(-85.0, 90.0) getDifference(-95.0, 90.0) getDifference(-45.0, 125.0) getDifference(-45.0, 145.0) getDifference(-45.0, 125.0) getDifference(-45.0, 145.0) getDifference(29.4803, -88.6381) getDifference(-78.3251, -159.036) PrintN(#CRLF$ + "Input in wider range:") getDifference(-70099.74233810938, 29840.67437876723) getDifference(-165313.6666297357, 33693.9894517456) getDifference(1174.8380510598456, -154146.66490124757) getDifference(60175.77306795546, 42213.07192354373) Repeat: Until Inkey() <> "" EndIf
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
#Raku
Raku
my @anagrams = 'unixdict.txt'.IO.words .map(*.comb.cache) # explode words into lists of characters .classify(*.sort.join).values # group words with the same characters .grep(* > 1) # only take groups with more than one word .sort(-*[0]) # sort by length of the first word ;   for @anagrams -> @group { for @group.combinations(2) -> [@a, @b] { if none @a Zeq @b { say "{@a.join} {@b.join}"; exit; } } }
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.
#OxygenBasic
OxygenBasic
  function fiboRatio() as double function fibo( double i, j ) as double if j > 2e12 then return j / i return fibo j, i + j end function return fibo 1, 1 end function   print fiboRatio    
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.
#Oberon-2
Oberon-2
  MODULE AmicablePairs; IMPORT Out; CONST max = 20000;   VAR i,j: INTEGER; pd: ARRAY max + 1 OF LONGINT;   PROCEDURE ProperDivisorsSum(n: LONGINT): LONGINT; VAR i,sum: LONGINT; BEGIN sum := 0; IF n > 1 THEN INC(sum,1);i := 2; WHILE (i < n) DO IF (n MOD i) = 0 THEN INC(sum,i) END; INC(i) END END; RETURN sum END ProperDivisorsSum;   BEGIN FOR i := 0 TO max DO pd[i] := ProperDivisorsSum(i) END;   FOR i := 2 TO max DO FOR j := i + 1 TO max DO IF (pd[i] = j) & (pd[j] = i) THEN Out.Char('[');Out.Int(i,0);Out.Char(',');Out.Int(j,0);Out.Char("]");Out.Ln END END END END AmicablePairs.  
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.
#Python
Python
import pygame, sys from pygame.locals import * from math import sin, cos, radians   pygame.init()   WINDOWSIZE = 250 TIMETICK = 100 BOBSIZE = 15   window = pygame.display.set_mode((WINDOWSIZE, WINDOWSIZE)) pygame.display.set_caption("Pendulum")   screen = pygame.display.get_surface() screen.fill((255,255,255))   PIVOT = (WINDOWSIZE/2, WINDOWSIZE/10) SWINGLENGTH = PIVOT[1]*4   class BobMass(pygame.sprite.Sprite): def __init__(self): pygame.sprite.Sprite.__init__(self) self.theta = 45 self.dtheta = 0 self.rect = pygame.Rect(PIVOT[0]-SWINGLENGTH*cos(radians(self.theta)), PIVOT[1]+SWINGLENGTH*sin(radians(self.theta)), 1,1) self.draw()   def recomputeAngle(self): scaling = 3000.0/(SWINGLENGTH**2)   firstDDtheta = -sin(radians(self.theta))*scaling midDtheta = self.dtheta + firstDDtheta midtheta = self.theta + (self.dtheta + midDtheta)/2.0   midDDtheta = -sin(radians(midtheta))*scaling midDtheta = self.dtheta + (firstDDtheta + midDDtheta)/2 midtheta = self.theta + (self.dtheta + midDtheta)/2   midDDtheta = -sin(radians(midtheta)) * scaling lastDtheta = midDtheta + midDDtheta lasttheta = midtheta + (midDtheta + lastDtheta)/2.0   lastDDtheta = -sin(radians(lasttheta)) * scaling lastDtheta = midDtheta + (midDDtheta + lastDDtheta)/2.0 lasttheta = midtheta + (midDtheta + lastDtheta)/2.0   self.dtheta = lastDtheta self.theta = lasttheta self.rect = pygame.Rect(PIVOT[0]- SWINGLENGTH*sin(radians(self.theta)), PIVOT[1]+ SWINGLENGTH*cos(radians(self.theta)),1,1)     def draw(self): pygame.draw.circle(screen, (0,0,0), PIVOT, 5, 0) pygame.draw.circle(screen, (0,0,0), self.rect.center, BOBSIZE, 0) pygame.draw.aaline(screen, (0,0,0), PIVOT, self.rect.center) pygame.draw.line(screen, (0,0,0), (0, PIVOT[1]), (WINDOWSIZE, PIVOT[1]))   def update(self): self.recomputeAngle() screen.fill((255,255,255)) self.draw()   bob = BobMass()   TICK = USEREVENT + 2 pygame.time.set_timer(TICK, TIMETICK)   def input(events): for event in events: if event.type == QUIT: sys.exit(0) elif event.type == TICK: bob.update()   while True: input(pygame.event.get()) pygame.display.flip()
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.
#Icon_and_Unicon
Icon and Unicon
procedure main() s1 := ["the","that","a"] s2 := ["frog","elephant","thing"] s3 := ["walked","treaded","grows"] s4 := ["slowly","quickly"]   write(amb(!s1,!s2,!s3,!s4)) end   procedure amb(exprs[]) s := "" every e := !exprs do { if \c ~== e[1] then fail c := e[-1] s ||:= e || " " } return s end
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.
#Bracmat
Bracmat
( ( accumulator = . ' ( add sum object . (object=add=$arg+!arg) & !(object.add):?sum & '($($sum)+!arg):(=?(object.add)) & !sum ) ) & accumulator$1:(=?x) & x$5 & accumulator$3 & out$(x$23/10) )
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.
#Brat
Brat
accumulator = { sum | { n | sum = sum + n } }   x = accumulator 1 x 5 accumulator 3 #Does not affect x p x 2.3 #Prints 8.3 (1 + 5 + 2.3)
http://rosettacode.org/wiki/Ackermann_function
Ackermann function
The Ackermann function is a classic example of a recursive function, notable especially because it is not a primitive recursive function. It grows very quickly in value, as does the size of its call tree. The Ackermann function is usually defined as follows: A ( m , n ) = { n + 1 if  m = 0 A ( m − 1 , 1 ) if  m > 0  and  n = 0 A ( m − 1 , A ( m , n − 1 ) ) if  m > 0  and  n > 0. {\displaystyle A(m,n)={\begin{cases}n+1&{\mbox{if }}m=0\\A(m-1,1)&{\mbox{if }}m>0{\mbox{ and }}n=0\\A(m-1,A(m,n-1))&{\mbox{if }}m>0{\mbox{ and }}n>0.\end{cases}}} Its arguments are never negative and it always terminates. Task Write a function which returns the value of A ( m , n ) {\displaystyle A(m,n)} . Arbitrary precision is preferred (since the function grows so quickly), but not required. See also Conway chained arrow notation for the Ackermann function.
#11l
11l
F ack2(m, n) -> Int R I m == 0 {(n + 1) } E I m == 1 {(n + 2) } E I m == 2 {(2 * n + 3) } E I m == 3 {(8 * (2 ^ n - 1) + 5) } E I n == 0 {ack2(m - 1, 1) } E ack2(m - 1, ack2(m, n - 1))   print(ack2(0, 0)) print(ack2(3, 4)) print(ack2(4, 1))
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
#AArch64_Assembly
AArch64 Assembly
  /* ARM assembly AARCH64 Raspberry PI 3B or android 64 bits */ /* program numberClassif64.s */   /*******************************************/ /* Constantes file */ /*******************************************/ /* for this file see task include a file in language AArch64 assembly*/ .include "../includeConstantesARM64.inc"   .equ NBDIVISORS, 1000   /*******************************************/ /* Initialized data */ /*******************************************/ .data szMessStartPgm: .asciz "Program 64 bits start \n" szMessEndPgm: .asciz "Program normal end.\n" szMessErrorArea: .asciz "\033[31mError : area divisors too small.\n" szMessError: .asciz "\033[31mError  !!!\n" szMessErrGen: .asciz "Error end program.\n" szMessNbPrem: .asciz "This number is prime !!!.\n" szMessOverflow: .asciz "Overflow function isPrime.\n"   szCarriageReturn: .asciz "\n"   /* datas message display */ szMessResult: .asciz "Number déficients : @ perfects : @ abundants : @ \n"   /*******************************************/ /* UnInitialized data */ /*******************************************/ .bss .align 4 sZoneConv: .skip 24 tbZoneDecom: .skip 8 * NBDIVISORS // facteur 8 octets /*******************************************/ /* code section */ /*******************************************/ .text .global main main: // program start ldr x0,qAdrszMessStartPgm // display start message bl affichageMess   mov x4,#1 mov x3,#0 mov x6,#0 mov x7,#0 mov x8,#0 ldr x9,iNBMAX 1: mov x0,x4 // number //================================= ldr x1,qAdrtbZoneDecom bl decompFact // create area of divisors cmp x0,#0 // error ? blt 2f lsl x5,x4,#1 // number * 2 cmp x5,x1 // compare number and sum cinc x7,x7,eq // perfect cinc x6,x6,gt // deficient cinc x8,x8,lt // abundant   2: add x4,x4,#1 cmp x4,x9 ble 1b   //================================   mov x0,x6 // deficient ldr x1,qAdrsZoneConv bl conversion10 // convert ascii string ldr x0,qAdrszMessResult ldr x1,qAdrsZoneConv bl strInsertAtCharInc // and put in message mov x5,x0 mov x0,x7 // perfect ldr x1,qAdrsZoneConv bl conversion10 // convert ascii string mov x0,x5 ldr x1,qAdrsZoneConv bl strInsertAtCharInc // and put in message mov x5,x0 mov x0,x8 // abundant ldr x1,qAdrsZoneConv bl conversion10 // convert ascii string mov x0,x5 ldr x1,qAdrsZoneConv bl strInsertAtCharInc // and put in message bl affichageMess     ldr x0,qAdrszMessEndPgm // display end message bl affichageMess b 100f 99: // display error message ldr x0,qAdrszMessError bl affichageMess 100: // standard end of the program mov x0, #0 // return code mov x8, #EXIT // request to exit program svc 0 // perform system call qAdrszMessStartPgm: .quad szMessStartPgm qAdrszMessEndPgm: .quad szMessEndPgm qAdrszMessError: .quad szMessError qAdrszCarriageReturn: .quad szCarriageReturn qAdrtbZoneDecom: .quad tbZoneDecom   qAdrszMessResult: .quad szMessResult qAdrsZoneConv: .quad sZoneConv   iNBMAX: .quad 20000 /******************************************************************/ /* decomposition en facteur */ /******************************************************************/ /* x0 contient le nombre à decomposer */ /* x1 contains factor area address */ decompFact: stp x3,lr,[sp,-16]! // save registres stp x4,x5,[sp,-16]! // save registres stp x6,x7,[sp,-16]! // save registres stp x8,x9,[sp,-16]! // save registres stp x10,x11,[sp,-16]! // save registres mov x5,x1 mov x1,x0 cmp x0,1 beq 100f mov x8,x0 // save number bl isPrime // prime ? cmp x0,#1 beq 98f // yes is prime mov x1,#1 str x1,[x5] // first factor mov x12,#1 // divisors sum mov x4,#1 // indice divisors table mov x1,#2 // first divisor mov x6,#0 // previous divisor mov x7,#0 // number of same divisors 2: mov x0,x8 // dividende udiv x2,x0,x1 // x1 divisor x2 quotient x3 remainder msub x3,x2,x1,x0 cmp x3,#0 bne 5f // if remainder <> zero -> no divisor mov x8,x2 // else quotient -> new dividende cmp x1,x6 // same divisor ? beq 4f // yes mov x7,x4 // number factors in table mov x9,#0 // indice 21: ldr x10,[x5,x9,lsl #3 ] // load one factor mul x10,x1,x10 // multiply str x10,[x5,x7,lsl #3] // and store in the table add x12,x12,x10 add x7,x7,#1 // and increment counter add x9,x9,#1 cmp x9,x4 blt 21b mov x4,x7 mov x6,x1 // new divisor b 7f 4: // same divisor sub x9,x4,#1 mov x7,x4 41: ldr x10,[x5,x9,lsl #3 ] cmp x10,x1 sub x13,x9,1 csel x9,x13,x9,ne bne 41b sub x9,x4,x9 42: ldr x10,[x5,x9,lsl #3 ] mul x10,x1,x10 str x10,[x5,x7,lsl #3] // and store in the table add x12,x12,x10 add x7,x7,#1 // and increment counter add x9,x9,#1 cmp x9,x4 blt 42b mov x4,x7 b 7f // and loop   /* not divisor -> increment next divisor */ 5: cmp x1,#2 // if divisor = 2 -> add 1 add x13,x1,#1 // add 1 add x14,x1,#2 // else add 2 csel x1,x13,x14,eq b 2b   /* divisor -> test if new dividende is prime */ 7: mov x3,x1 // save divisor cmp x8,#1 // dividende = 1 ? -> end beq 10f mov x0,x8 // new dividende is prime ? mov x1,#0 bl isPrime // the new dividende is prime ? cmp x0,#1 bne 10f // the new dividende is not prime   cmp x8,x6 // else dividende is same divisor ? beq 9f // yes mov x7,x4 // number factors in table mov x9,#0 // indice 71: ldr x10,[x5,x9,lsl #3 ] // load one factor mul x10,x8,x10 // multiply str x10,[x5,x7,lsl #3] // and store in the table add x12,x12,x10 add x7,x7,#1 // and increment counter add x9,x9,#1 cmp x9,x4 blt 71b mov x4,x7 mov x7,#0 b 11f 9: sub x9,x4,#1 mov x7,x4 91: ldr x10,[x5,x9,lsl #3 ] cmp x10,x8 sub x13,x9,#1 csel x9,x13,x9,ne bne 91b sub x9,x4,x9 92: ldr x10,[x5,x9,lsl #3 ] mul x10,x8,x10 str x10,[x5,x7,lsl #3] // and store in the table add x12,x12,x10 add x7,x7,#1 // and increment counter add x9,x9,#1 cmp x9,x4 blt 92b mov x4,x7 b 11f   10: mov x1,x3 // current divisor = new divisor cmp x1,x8 // current divisor > new dividende ? ble 2b // no -> loop   /* end decomposition */ 11: mov x0,x4 // return number of table items mov x1,x12 // return sum mov x3,#0 str x3,[x5,x4,lsl #3] // store zéro in last table item b 100f     98: //ldr x0,qAdrszMessNbPrem //bl affichageMess add x1,x8,1 mov x0,#0 // return code b 100f 99: ldr x0,qAdrszMessError bl affichageMess mov x0,#-1 // error code b 100f     100: ldp x10,x11,[sp],16 // restaur des 2 registres ldp x8,x9,[sp],16 // restaur des 2 registres ldp x6,x7,[sp],16 // restaur des 2 registres ldp x4,x5,[sp],16 // restaur des 2 registres ldp x3,lr,[sp],16 // restaur des 2 registres ret // retour adresse lr x30 qAdrszMessErrGen: .quad szMessErrGen qAdrszMessNbPrem: .quad szMessNbPrem /***************************************************/ /* Verification si un nombre est premier */ /***************************************************/ /* x0 contient le nombre à verifier */ /* x0 retourne 1 si premier 0 sinon */ isPrime: stp x1,lr,[sp,-16]! // save registres stp x2,x3,[sp,-16]! // save registres mov x2,x0 sub x1,x0,#1 cmp x2,0 beq 99f // retourne zéro cmp x2,2 // pour 1 et 2 retourne 1 ble 2f mov x0,#2 bl moduloPux64 bcs 100f // erreur overflow cmp x0,#1 bne 99f // Pas premier cmp x2,3 beq 2f mov x0,#3 bl moduloPux64 blt 100f // erreur overflow cmp x0,#1 bne 99f   cmp x2,5 beq 2f mov x0,#5 bl moduloPux64 bcs 100f // erreur overflow cmp x0,#1 bne 99f // Pas premier   cmp x2,7 beq 2f mov x0,#7 bl moduloPux64 bcs 100f // erreur overflow cmp x0,#1 bne 99f // Pas premier   cmp x2,11 beq 2f mov x0,#11 bl moduloPux64 bcs 100f // erreur overflow cmp x0,#1 bne 99f // Pas premier   cmp x2,13 beq 2f mov x0,#13 bl moduloPux64 bcs 100f // erreur overflow cmp x0,#1 bne 99f // Pas premier 2: cmn x0,0 // carry à zero pas d'erreur mov x0,1 // premier b 100f 99: cmn x0,0 // carry à zero pas d'erreur mov x0,#0 // Pas premier 100: ldp x2,x3,[sp],16 // restaur des 2 registres ldp x1,lr,[sp],16 // restaur des 2 registres ret // retour adresse lr x30   /**************************************************************/ /********************************************************/ /* Calcul modulo de b puissance e modulo m */ /* Exemple 4 puissance 13 modulo 497 = 445 */ /********************************************************/ /* x0 nombre */ /* x1 exposant */ /* x2 modulo */ moduloPux64: stp x1,lr,[sp,-16]! // save registres stp x3,x4,[sp,-16]! // save registres stp x5,x6,[sp,-16]! // save registres stp x7,x8,[sp,-16]! // save registres stp x9,x10,[sp,-16]! // save registres cbz x0,100f cbz x1,100f mov x8,x0 mov x7,x1 mov x6,1 // resultat udiv x4,x8,x2 msub x9,x4,x2,x8 // contient le reste 1: tst x7,1 beq 2f mul x4,x9,x6 umulh x5,x9,x6 //cbnz x5,99f mov x6,x4 mov x0,x6 mov x1,x5 bl divisionReg128U cbnz x1,99f // overflow mov x6,x3 2: mul x8,x9,x9 umulh x5,x9,x9 mov x0,x8 mov x1,x5 bl divisionReg128U cbnz x1,99f // overflow mov x9,x3 lsr x7,x7,1 cbnz x7,1b mov x0,x6 // result cmn x0,0 // carry à zero pas d'erreur b 100f 99: ldr x0,qAdrszMessOverflow bl affichageMess cmp x0,0 // carry à un car erreur mov x0,-1 // code erreur   100: ldp x9,x10,[sp],16 // restaur des 2 registres ldp x7,x8,[sp],16 // restaur des 2 registres ldp x5,x6,[sp],16 // restaur des 2 registres ldp x3,x4,[sp],16 // restaur des 2 registres ldp x1,lr,[sp],16 // restaur des 2 registres ret // retour adresse lr x30 qAdrszMessOverflow: .quad szMessOverflow /***************************************************/ /* division d un nombre de 128 bits par un nombre de 64 bits */ /***************************************************/ /* x0 contient partie basse dividende */ /* x1 contient partie haute dividente */ /* x2 contient le diviseur */ /* x0 retourne partie basse quotient */ /* x1 retourne partie haute quotient */ /* x3 retourne le reste */ divisionReg128U: stp x6,lr,[sp,-16]! // save registres stp x4,x5,[sp,-16]! // save registres mov x5,#0 // raz du reste R mov x3,#128 // compteur de boucle mov x4,#0 // dernier bit 1: lsl x5,x5,#1 // on decale le reste de 1 tst x1,1<<63 // test du bit le plus à gauche lsl x1,x1,#1 // on decale la partie haute du quotient de 1 beq 2f orr x5,x5,#1 // et on le pousse dans le reste R 2: tst x0,1<<63 lsl x0,x0,#1 // puis on decale la partie basse beq 3f orr x1,x1,#1 // et on pousse le bit de gauche dans la partie haute 3: orr x0,x0,x4 // position du dernier bit du quotient mov x4,#0 // raz du bit cmp x5,x2 blt 4f sub x5,x5,x2 // on enleve le diviseur du reste mov x4,#1 // dernier bit à 1 4: // et boucle subs x3,x3,#1 bgt 1b lsl x1,x1,#1 // on decale le quotient de 1 tst x0,1<<63 lsl x0,x0,#1 // puis on decale la partie basse beq 5f orr x1,x1,#1 5: orr x0,x0,x4 // position du dernier bit du quotient mov x3,x5 100: ldp x4,x5,[sp],16 // restaur des 2 registres ldp x6,lr,[sp],16 // restaur des 2 registres ret // retour adresse lr x30   /********************************************************/ /* File Include fonctions */ /********************************************************/ /* for this file see task include a file in language AArch64 assembly */ .include "../includeARM64.inc"  
http://rosettacode.org/wiki/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
#Amazing_Hopper
Amazing Hopper
  #define IGet(__N__,__X__) [__N__]SGet(__X__)   #include <hbasic.h> #define MAX_LINE 1000   Begin Option Stack 15   Declare as Numeric ( fd, i, index, max token ) as Numeric ( num tokens, size Column, tCells ) as Alpha ( line ) as Numeric ( display Left, display Right, display Center )   GetParam(script, file to edit, separator)   // get statistics of file: #lines, #total chars, line more long, and num tokens from first line. Token Sep( separator ) Stat( file to edit, dats )   // declare arrays to work: Dim ( IGet(1,dats), Add(IGet(4,dats),10) ) for Fill Array("",cells) Clear(dats) MStore ( cells, display Left, display Right, display Center )   // read each line as array, get # of elements, and put into array cells: Open(OPEN_READ, file to edit ) (fd) When( File Error ){ Stop }   index=1 While Not Eof(fd) ReadRow(MAX_LINE)(fd) and Copy to (line); get Length, and Move to (num tokens) Set Interval [index, 1:num tokens]; Take( line ) and SPut(cells) When ( var( max token) Is Lt (num tokens) ) { max token = num tokens } ++index Wend Close(fd)   // formatting... For Up( i:=1, max token, 1 ) Set Interval [1:end,i], and Let ( size Column := MaxValue( Len(Get(cells)) ) Plus(1) ) Let ( tCells := Get(cells) ) LPad$( " ", size Column, tCells ), and Put(display Left) RPad$( " ", size Column, tCells ), and Put(display Right) CPad$( " ", size Column, tCells ), and Put(display Center) Next   // display: Token Sep ("") Print("Left Pad:\n", display Left, Newl, "Right Pad:\n", display Right, Newl, "Center Pad:\n", display Center,Newl) End  
http://rosettacode.org/wiki/Active_object
Active object
In object-oriented programming an object is active when its state depends on clock. Usually an active object encapsulates a task that updates the object's state. To the outer world the object looks like a normal object with methods that can be called from outside. Implementation of such methods must have a certain synchronization mechanism with the encapsulated task in order to prevent object's state corruption. A typical instance of an active object is an animation widget. The widget state changes with the time, while as an object it has all properties of a normal widget. The task Implement an active integrator object. The object has an input and output. The input can be set using the method Input. The input is a function of time. The output can be queried using the method Output. The object integrates its input over the time and the result becomes the object's output. So if the input is K(t) and the output is S, the object state S is changed to S + (K(t1) + K(t0)) * (t1 - t0) / 2, i.e. it integrates K using the trapeze method. Initially K is constant 0 and S is 0. In order to test the object: set its input to sin (2π f t), where the frequency f=0.5Hz. The phase is irrelevant. wait 2s set the input to constant 0 wait 0.5s Verify that now the object's output is approximately 0 (the sine has the period of 2s). The accuracy of the result will depend on the OS scheduler time slicing and the accuracy of the clock.
#E
E
def makeIntegrator() { var value := 0.0 var input := fn { 0.0 }   var input1 := input() var t1 := timer.now()   def update() { def t2 := timer.now() def input2 :float64 := input() def dt := (t2 - t1) / 1000   value += (input1 + input2) * dt / 2   t1 := t2 input1 := input2 }   var task() { update <- () task <- () } task()   def integrator { to input(new) :void { input := new } to output() :float64 { return value } to shutdown() { task := fn {} } } return integrator }   def test() { def result   def pi := (-1.0).acos() def freq := pi / 1000   def base := timer.now() def i := makeIntegrator()   i.input(fn { (freq * timer.now()).sin() }) timer.whenPast(base + 2000, fn { i.input(fn {0}) }) timer.whenPast(base + 2500, fn { bind result := i.output() i.shutdown() }) return result }
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
#Raku
Raku
use Prime::Factor; use Math::Root;   sub is-square-free (Int \n) { constant @p = ^100 .map: { next unless .is-prime; .² }; for @p -> \p { return False if n %% p } True }   sub powerful (\n, \k = 2) { my @p; p(1, 2*k - 1); sub p (\m, \r) { @p.push(m) and return if r < k; for 1 .. (n / m).&root(r) -> \v { if r > k { next unless is-square-free(v); next unless m gcd v == 1; } p(m * v ** r, r - 1) } } @p }   my $achilles = powerful(10**9).hyper(:500batch).grep( { my $f = .&prime-factors.Bag; (+$f.keys > 1) && (1 == [gcd] $f.values) && (.sqrt.Int² !== $_) } ).classify: { .chars }   my \𝜑 = 0, |(1..*).hyper.map: -> \t { t × [×] t.&prime-factors.squish.map: { 1 - 1/$_ } }   my %as = Set.new: flat $achilles.values».list;   my $strong = lazy (flat $achilles.sort».value».list».sort).grep: { ?%as{𝜑[$_]} };   put "First 50 Achilles numbers:"; put (flat $achilles.sort».value».list».sort)[^50].batch(10)».fmt("%4d").join("\n");   put "\nFirst 30 strong Achilles numbers:"; put $strong[^30].batch(10)».fmt("%5d").join("\n");   put "\nNumber of Achilles numbers with:"; say "$_ digits: " ~ +$achilles{$_} // 0 for 2..9;   printf "\n%.1f total elapsed seconds\n", now - INIT now;
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
#J
J
proper_divisors=: [: */@>@}:@,@{ [: (^ i.@>:)&.>/ 2 p: x: aliquot=: +/@proper_divisors ::0: rc_aliquot_sequence=: aliquot^:(i.16)&> rc_classify=: 3 :0 if. 16 ~:# y do. ' invalid ' elseif. 6 > {: y do. ' terminate ' elseif. (+./y>2^47) +. 16 = #~.y do. ' non-terminating' elseif. 1=#~. y do. ' perfect ' elseif. 8= st=. {.#/.~ y do. ' amicable ' elseif. 1 < st do. ' sociable ' elseif. =/_2{. y do. ' aspiring ' elseif. 1 do. ' cyclic ' end. ) rc_display_aliquot_sequence=: (rc_classify,' ',":)@:rc_aliquot_sequence
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.
#PHP
PHP
class E {};   $e=new E();   $e->foo=1;   $e->{"foo"} = 1; // using a runtime name $x = "foo"; $e->$x = 1; // using a runtime name in a variable
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.
#PicoLisp
PicoLisp
: (setq MyObject (new '(+MyClass))) # Create some object -> $385605941 : (put MyObject 'newvar '(some value)) # Set variable -> (some value) : (show MyObject) # Show the object $385605941 (+MyClass) newvar (some value) -> $385605941
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.
#Pike
Pike
class CSV { mapping variables = ([]);   mixed `->(string name) { return variables[name]; }   void `->=(string name, mixed value) { variables[name] = value; }   array _indices() { return indices(variables); } }   object csv = CSV(); csv->greeting = "hello world"; csv->count = 1; csv->lang = "Pike";   indices(csv); Result: ({ /* 3 elements */ "lang", "count", "greeting" })  
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.
#PL.2FM
PL/M
100H: /* THERE IS NO STANDARD LIBRARY THIS DEFINES SOME BASIC I/O USING CP/M */ BDOS: PROCEDURE (F,A); DECLARE F BYTE, A ADDRESS; GO TO 5; END BDOS; EXIT: PROCEDURE; CALL BDOS(0,0); END EXIT; PUT$CHAR: PROCEDURE (C); DECLARE C BYTE; CALL BDOS(2,C); END PUT$CHAR; PRINT: PROCEDURE (S); DECLARE S ADDRESS; CALL BDOS(9,S); END PRINT; NEWLINE: PROCEDURE; CALL PRINT(.(13,10,'$')); END NEWLINE;   /* PRINT 16-BIT HEX VALUE (POINTER) */ PRINT$HEX: PROCEDURE (N); DECLARE N ADDRESS, (I, C) BYTE; DO I=0 TO 3; IF I <> 3 THEN C = SHR(N,12-4*I) AND 0FH; ELSE C = N AND 0FH; IF C >= 10 THEN C = C - 10 + 'A'; ELSE C = C + '0'; CALL PUT$CHAR(C); END; END PRINT$HEX;   /* OF COURSE WE WILL NEED SOME VALUES TO POINT AT TOO */ DECLARE FOO ADDRESS INITIAL (0F00H); DECLARE BAR ADDRESS INITIAL (0BA1H);   /* OK, NOW ON TO THE DEMONSTRATION */   /* THE ADDRESS OF A VARIABLE CAN BE RETRIEVED BY PREPENDING IT WITH A DOT, E.G.: */ CALL PRINT(.'FOO IS $'); CALL PRINT$HEX(FOO); CALL PRINT(.' AND ITS ADDRESS IS $'); CALL PRINT$HEX(.FOO); CALL NEWLINE;   CALL PRINT(.'BAR IS $'); CALL PRINT$HEX(BAR); CALL PRINT(.' AND ITS ADDRESS IS $'); CALL PRINT$HEX(.BAR); CALL NEWLINE;   /* PL/M DOES NOT HAVE C-STYLE POINTERS. INSTEAD IT HAS 'BASED' VARIABLES.   WHEN A VARIABLE IS DECLARED 'BASED', ITS ADDRESS IS STORED IN ANOTHER VARIABLE.   NOTE HOWEVER THAT THE 'ADDRESS' DATATYPE IS SIMPLY A 16-BIT INTEGER, AND DOES NOT INTRINSICALLY POINT TO ANYTHING.   THE FOLLOWING DECLARES A VARIABLE 'POINTER', WHICH WILL HOLD AN ADDRESS, AND A VARIABLE 'VALUE' WHICH WILL BE LOCATED AT WHATEVER THE VALUE IN 'POINTER' IS. */   DECLARE POINTER ADDRESS; DECLARE VALUE BASED POINTER ADDRESS;   /* WE CAN NOW ACCESS 'FOO' AND 'BAR' THROUGH 'VALUE' BY ASSIGNING THEIR ADDRESSES TO 'POINTER'. */ POINTER = .FOO; CALL PRINT(.'POINTER IS $'); CALL PRINT$HEX(POINTER); CALL PRINT(.' AND VALUE IS $'); CALL PRINT$HEX(VALUE); CALL NEWLINE;   POINTER = .BAR; CALL PRINT(.'POINTER IS $'); CALL PRINT$HEX(POINTER); CALL PRINT(.' AND VALUE IS $'); CALL PRINT$HEX(VALUE); CALL NEWLINE;   /* MUTATION IS ALSO POSSIBLE OF COURSE */ VALUE = 0BA3H; CALL PRINT(.'VALUE IS NOW $'); CALL PRINT$HEX(VALUE); CALL PRINT(.' AND BAR IS NOW $'); CALL PRINT$HEX(BAR); CALL NEWLINE;   /* LASTLY, PL/M SUPPORTS ANONYMOUS CONSTANTS. YOU CAN TAKE THE ADDRESS OF AN IMMEDIATE CONSTANT, AND PL/M WILL STORE THE CONSTANT IN THE CONSTANT POOL AND GIVE YOU ITS ADDRESS. THE CONSTANT MUST HOWEVER BE A BYTE OR A LIST OF BYTES. */ POINTER = .(0FEH,0CAH); /* NOTE THE DOT, AND THE LOW-ENDIAN 16-BIT VALUE */ CALL PRINT(.'POINTER IS $'); CALL PRINT$HEX(POINTER); CALL PRINT(.' AND VALUE IS $'); CALL PRINT$HEX(VALUE); CALL NEWLINE;   /* NOTE THAT THIS IS ALSO HOW STRINGS WORK - SEE ALL THE DOTS IN FRONT OF THE STRINGS IN THE 'PRINT' CALLS */ CALL EXIT; EOF
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.
#Elena
Elena
import extensions;   singleton AksTest { static long[] c := new long[](100);   coef(int n) { int i := 0; int j := 0;   if ((n < 0) || (n > 63)) { AbortException.raise() }; // gracefully deal with range issue   c[i] := 1l; for (int i := 0, i < n, i += 1) { c[1 + i] := 1l; for (int j := i, j > 0, j -= 1) { c[j] := c[j - 1] - c[j] }; c[0] := c[0].Negative } }   bool is_prime(int n) { int i := n;   self.coef(n); c[0] := c[0] + 1; c[i] := c[i] - 1;   i -= 1; while (i + 1 != 0 && c[i+1].mod(n) == 0) { i -= 1 };   ^ i < 0 }   show(int n) { int i := n; i += 1; while(i != 0) { i -= 1; console.print("+",c[i],"x^",i) } } }   public program() { for (int n := 0, n < 10, n += 1) { AksTest.coef(n);   console.print("(x-1)^",n," = "); AksTest.show(n); console.printLine() };   console.print("Primes:"); for (int n := 1, n <= 63, n += 1) { if (AksTest.is_prime(n)) { console.print(n," ") } };   console.printLine().readChar() }
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.
#J
J
(#~ 1 p: [:+/@|: 10&#.inv) i.&.(p:inv) 500 2 3 5 7 11 23 29 41 43 47 61 67 83 89 101 113 131 137 139 151 157 173 179 191 193 197 199 223 227 229 241 263 269 281 283 311 313 317 331 337 353 359 373 379 397 401 409 421 443 449 461 463 467 487
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.
#Java
Java
public class additivePrimes {   public static void main(String[] args) { int additive_primes = 0; for (int i = 2; i < 500; i++) { if(isPrime(i) && isPrime(digitSum(i))){ additive_primes++; System.out.print(i + " "); } } System.out.print("\nFound " + additive_primes + " additive primes less than 500"); }   static boolean isPrime(int n) { int counter = 1; if (n < 2 || (n != 2 && n % 2 == 0) || (n != 3 && n % 3 == 0)) { return false; } while (counter * 6 - 1 <= Math.sqrt(n)) { if (n % (counter * 6 - 1) == 0 || n % (counter * 6 + 1) == 0) { return false; } else { counter++; } } return true; }   static int digitSum(int n) { int sum = 0; while (n > 0) { sum += n % 10; n /= 10; } return sum; } }  
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
#Java
Java
public class AlmostPrime { public static void main(String[] args) { for (int k = 1; k <= 5; k++) { System.out.print("k = " + k + ":");   for (int i = 2, c = 0; c < 10; i++) { if (kprime(i, k)) { System.out.print(" " + i); c++; } }   System.out.println(""); } }   public static boolean kprime(int n, int k) { int f = 0; for (int p = 2; f < k && p * p <= n; p++) { while (n % p == 0) { n /= p; f++; } } return f + ((n > 1) ? 1 : 0) == 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
#Delphi
Delphi
  program AnagramsTest;   {$APPTYPE CONSOLE}   {$R *.res}   uses System.SysUtils, System.Classes, System.Diagnostics;   function Sort(s: string): string; var c: Char; i, j, aLength: Integer; begin aLength := s.Length;   if aLength = 0 then exit('');   Result := s;   for i := 1 to aLength - 1 do for j := i + 1 to aLength do if result[i] > result[j] then begin c := result[i]; result[i] := result[j]; result[j] := c; end; end;   function IsAnagram(s1, s2: string): Boolean; begin if s1.Length <> s2.Length then exit(False);   Result := Sort(s1) = Sort(s2);   end;   function Split(s: string; var Count: Integer; var words: string): Boolean; var sCount: string; begin sCount := s.Substring(0, 4); words := s.Substring(5); Result := TryStrToInt(sCount, Count); end;   function CompareLength(List: TStringList; Index1, Index2: Integer): Integer; begin result := List[Index1].Length - List[Index2].Length; if Result = 0 then Result := CompareText(Sort(List[Index2]), Sort(List[Index1])); end;   var Dict: TStringList; i, j, Count, MaxCount, WordLength, Index: Integer; words: string; StopWatch: TStopwatch;   begin StopWatch := TStopwatch.Create; StopWatch.Start;   Dict := TStringList.Create(); Dict.LoadFromFile('unixdict.txt');   Dict.CustomSort(CompareLength);   Index := 0; words := Dict[Index]; Count := 1;   while Index + Count < Dict.Count do begin if IsAnagram(Dict[Index], Dict[Index + Count]) then begin words := words + ',' + Dict[Index + Count]; Dict[Index + Count] := ''; inc(Count); end else begin Dict[Index] := format('%.4d', [Count]) + ',' + words; inc(Index, Count); words := Dict[Index]; Count := 1; end; end;   // The last one not match any one if not Dict[Dict.count - 1].IsEmpty then Dict.Delete(Dict.count - 1);   Dict.Sort;   while Dict[0].IsEmpty do Dict.Delete(0);   StopWatch.Stop;   Writeln(Format('Time pass: %d ms [i7-4500U Windows 7]', [StopWatch.ElapsedMilliseconds]));   Split(Dict[Dict.count - 1], MaxCount, words); writeln(#10'The anagrams that contain the most words, has ', MaxCount, ' words:'#10); writeln('Words found:'#10);   Writeln(' ', words);   for i := Dict.Count - 2 downto 0 do begin Split(Dict[i], Count, words); if Count = MaxCount then Writeln(' ', words) else Break; end;   Dict.Free; Readln; end.    
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
#Python
Python
from __future__ import print_function   def getDifference(b1, b2): r = (b2 - b1) % 360.0 # Python modulus has same sign as divisor, which is positive here, # so no need to consider negative case if r >= 180.0: r -= 360.0 return r   if __name__ == "__main__": print ("Input in -180 to +180 range") print (getDifference(20.0, 45.0)) print (getDifference(-45.0, 45.0)) print (getDifference(-85.0, 90.0)) print (getDifference(-95.0, 90.0)) print (getDifference(-45.0, 125.0)) print (getDifference(-45.0, 145.0)) print (getDifference(-45.0, 125.0)) print (getDifference(-45.0, 145.0)) print (getDifference(29.4803, -88.6381)) print (getDifference(-78.3251, -159.036))   print ("Input in wider range") print (getDifference(-70099.74233810938, 29840.67437876723)) print (getDifference(-165313.6666297357, 33693.9894517456)) print (getDifference(1174.8380510598456, -154146.66490124757)) print (getDifference(60175.77306795546, 42213.07192354373))
http://rosettacode.org/wiki/Anagrams/Deranged_anagrams
Anagrams/Deranged anagrams
Two or more words are said to be anagrams if they have the same characters, but in a different order. By analogy with derangements we define a deranged anagram as two words with the same characters, but in which the same character does not appear in the same position in both words. Task[edit] Use the word list at unixdict to find and display the longest deranged anagram. Related tasks Permutations/Derangements Best shuffle Word plays Ordered words Palindrome detection Semordnilap Anagrams Anagrams/Deranged anagrams Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#REXX
REXX
/*REXX program finds the largest deranged word (within an identified dictionary). */ iFID= 'unixdict.txt'; words=0 /*input file ID; number of words so far*/ wL.=0 /*number of words of length L. so far*/ do while lines(iFID)\==0 /*read each word in the file (word=X).*/ x= strip( linein( iFID) ) /*pick off a word from the input line. */ L= length(x); if L<3 then iterate /*onesies & twosies can't possible win.*/ words= words + 1 /*bump the count of (usable) words. */ #.words= L /*the length of the word found. */ @.words= x /*save the word in an array. */ wL.L= wL.L+1; _= wL.L /*bump counter of words of length L. */ @@.L._= x /*array of words of length L. */ do i=1 while x\==''; parse var x !.i +1 x; end /*i*/ call eSort L; z=; do j=1 for L; z= z || !.j; end /*j*/ @@s.L._= z /*store the sorted word (letters). */ @s.words= @@s.L._ /*store the sorted length L version. */ end /*while*/ a.= /*all the anagrams for word X. */ say copies('─', 30) words 'usable words in the dictionary file: ' iFID m= 0; n.= 0 /*# anagrams for word X; m=max L. */ do j=1 for words /*process usable words that were found.*/ Lx= #.j; if Lx<m then iterate /*get length of word; skip if too short*/ x= @.j; xs= @s.j /*get some vital statistics for X */ do k=1 for wL.Lx /*process all the words of length L. */ if xs\== @@s.Lx.k then iterate /*is this not a true anagram of X ? */ if x == @@.Lx.k then iterate /*skip of processing anagram on itself.*/ do c=1 for Lx /*ensure no character position shared. */ if substr(@.j, c, 1) == substr(@@.Lx.k, c, 1) then iterate k end /*c*/ /* [+] now compare the rest of chars. */ n.j= n.j + 1; a.j= a.j @@.Lx.k /*bump counter; then add ──► anagrams.*/ m= max(m, Lx) /*M is the maximum length of a word. */ end /*k*/ end /*j*/   do k=1 for words /*now, search all words for the maximum*/ if #.k==m then if n.k\==0 then if word(a.k, 1) > @.k then say @.k a.k end /*k*/ /* [↑] REXX has no short-circuits. */ exit /*stick a fork in it, we're all done. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ eSort: procedure expose !.; parse arg ho 1 h /*obtain number of elements; also copy.*/ do while h>1; h=h % 2; do i=1 for ho-h; j= i; k= h+i do while !.k<!.j; t=!.j;  !.j=!.k;  !.k=t; if h>=j then leave; j=j-h; k=k-h end /*while !.k···*/; end /*i*/; end /*while h>1*/; return
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.
#PARI.2FGP
PARI/GP
Fib(n)={ my(F=(k,f)->if(k<2,k,f(k-1,f)+f(k-2,f))); if(n<0,(-1)^(n+1),1)*F(abs(n),F) };
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.
#Oforth
Oforth
import: mapping   Integer method: properDivs -- [] #[ self swap mod 0 == ] self 2 / seq filter ;   : amicables | i j | Array new 20000 loop: i [ i properDivs sum dup ->j i <= if continue then j properDivs sum i <> if continue then [ i, j ] over add ] ;
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.
#QB64
QB64
'declare and initialize variables CONST PI = 3.141592   DIM SHARED Bob_X, Bob_Y, Pivot_X, Pivot_Y, Rod_Length, Rod_Angle, Bob_Angular_Acceleration, Bob_Angular_Velocity, Delta_Time, Drawing_Scale, G AS DOUBLE DIM SHARED exit_flag AS INTEGER   'set gravity to Earth's by default (in m/s squared) G = -9.80665   'set the pivot at the screen center near the top. Positions are in meters not pixels, and they translate to 320 and 60 pixels Pivot_X = 1.6 Pivot_Y = 0.3   'set the rod length, 0.994 meters by default (gives 1 second period in Earth gravity) Rod_Length = 0.994 'set the initial rod angle to 6 degrees and convert to radians. 6 degrees seems small but it is near to what clocks use so it 'makes the pendulum look like a clock's. More amplitude works perfectly but looks silly. Rod_Angle = 6 * (PI / 180) 'set delta time, seconds. 5 miliseconds is precise enough. Delta_Time = 0.05   'because the positions are calculated in meters, the pendulum as drawn would be way too small (1 meter = 1 pixel), 'so a scale factor is introduced (1 meter = 200 pixels by default) Drawing_Scale = 200   'initialize the screen to 640 x 480, 16 colors SCREEN 12   'main loop DO 'math to figure out what the pendulum is doing based on the initial conditions.   'first calculate the position of the bob's center based on the rod angle by using the sine and cosine functions for x and y coordinates Bob_X = (Pivot_X + SIN(Rod_Angle) * Rod_Length) Bob_Y = (Pivot_Y + COS(Rod_Angle) * Rod_Length) 'then based on the rod's last angle, length, and gravitational acceleration, calculate the angular acceleration Bob_Angular_Acceleration = G / Rod_Length * SIN(Rod_Angle) 'integrate the angular acceleration over time to obtain angular velocity Bob_Angular_Velocity = Bob_Angular_Velocity + (Bob_Angular_Acceleration * Delta_Time) 'integrate the angular velocity over time to obtain a new angle for the rod Rod_Angle = Rod_Angle + (Bob_Angular_Velocity * Delta_Time)   'draw the user interface and pendulum position   'clear the screen before drawing the next frame of the animation CLS   'print information PRINT " Gravity: " + STR$(ABS(G)) + " m/sý, Rod Length: " + STR$(Rod_Length); " m" LOCATE 25, 1 PRINT "+/- keys control rod length, numbers 1-5 select gravity, (1 Earth, 2 the Moon, 3 Mars, 4 more 5 less), Q to exit"   'draw the pivot CIRCLE (Pivot_X * Drawing_Scale, Pivot_Y * Drawing_Scale), 5, 8 PAINT STEP(0, 0), 8, 8   'draw the bob CIRCLE (Bob_X * Drawing_Scale, Bob_Y * Drawing_Scale), 20, 14 PAINT STEP(0, 0), 14, 14   'draw the rod LINE (Pivot_X * Drawing_Scale, Pivot_Y * Drawing_Scale)-(Bob_X * Drawing_Scale, Bob_Y * Drawing_Scale), 14   'process input SELECT CASE UCASE$(INKEY$) CASE "+" 'lengthen rod Rod_Length = Rod_Length + 0.01 CASE "-" 'shorten rod Rod_Length = Rod_Length - 0.01 CASE "1" 'Earth G G = -9.80665 CASE "2" 'Moon G G = -1.62 CASE "3" 'Mars G G = -3.721 CASE "4" 'More G G = G + 0.1 CASE "5" 'Less G G = G - 0.1 CASE "Q" 'exit on any other key exit_flag = 1 END SELECT   'wait before drawing the next frame _DELAY Delta_Time   'loop the animation until the user presses any key LOOP UNTIL exit_flag = 1
http://rosettacode.org/wiki/Amb
Amb
Define and give an example of the Amb operator. The Amb operator (short for "ambiguous") expresses nondeterminism. This doesn't refer to randomness (as in "nondeterministic universe") but is closely related to the term as it is used in automata theory ("non-deterministic finite automaton"). The Amb operator takes a variable number of expressions (or values if that's simpler in the language) and yields a correct one which will satisfy a constraint in some future computation, thereby avoiding failure. Problems whose solution the Amb operator naturally expresses can be approached with other tools, such as explicit nested iterations over data sets, or with pattern matching. By contrast, the Amb operator appears integrated into the language. Invocations of Amb are not wrapped in any visible loops or other search patterns; they appear to be independent. Essentially Amb(x, y, z) splits the computation into three possible futures: a future in which the value x is yielded, a future in which the value y is yielded and a future in which the value z is yielded. The future which leads to a successful subsequent computation is chosen. The other "parallel universes" somehow go away. Amb called with no arguments fails. For simplicity, one of the domain values usable with Amb may denote failure, if that is convenient. For instance, it is convenient if a Boolean false denotes failure, so that Amb(false) fails, and thus constraints can be expressed using Boolean expressions like Amb(x * y == 8) which unless x and y add to four. A pseudo-code program which satisfies this constraint might look like: let x = Amb(1, 2, 3) let y = Amb(7, 6, 4, 5) Amb(x * y = 8) print x, y The output is 2 4 because Amb(1, 2, 3) correctly chooses the future in which x has value 2, Amb(7, 6, 4, 5) chooses 4 and consequently Amb(x * y = 8) produces a success. Alternatively, failure could be represented using strictly Amb(): unless x * y = 8 do Amb() Or else Amb could take the form of two operators or functions: one for producing values and one for enforcing constraints: let x = Ambsel(1, 2, 3) let y = Ambsel(4, 5, 6) Ambassert(x * y = 8) print x, y where Ambassert behaves like Amb() if the Boolean expression is false, otherwise it allows the future computation to take place, without yielding any value. The task is to somehow implement Amb, and demonstrate it with a program which chooses one word from each of the following four sets of character strings to generate a four-word sentence: "the" "that" "a" "frog" "elephant" "thing" "walked" "treaded" "grows" "slowly" "quickly" The constraint to be satisfied is that the last character of each word (other than the last) is the same as the first character of its successor. The only successful sentence is "that thing grows slowly"; other combinations do not satisfy the constraint and thus fail. The goal of this task isn't to simply process the four lists of words with explicit, deterministic program flow such as nested iteration, to trivially demonstrate the correct output. The goal is to implement the Amb operator, or a facsimile thereof that is possible within the language limitations.
#J
J
amb=. ([ , ' ' , ])&>/&.>@:((({:@:[ = {.@:])&>/&> # ])@:,@:({@(,&<))) >@(amb&.>/) ('the';'that';'a');('frog';'elephant';'thing');('walked';'treaded';'grows');(<'slowly';'quickly') +-----------------------+ |that thing grows slowly| +-----------------------+
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.
#BQN
BQN
Acc ← { 𝕊 sum: {sum+↩𝕩} } x ← Acc 1 X 5 Acc 3 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.
#C
C
#include <stdio.h> //~ Take a number n and return a function that takes a number i #define ACCUMULATOR(name,n) __typeof__(n) name (__typeof__(n) i) { \ static __typeof__(n) _n=n; LOGIC; } //~ have it return n incremented by the accumulation of i #define LOGIC return _n+=i ACCUMULATOR(x,1.0) ACCUMULATOR(y,3) ACCUMULATOR(z,'a') #undef LOGIC int main (void) { printf ("%f\n", x(5)); /* 6.000000 */ printf ("%f\n", x(2.3)); /* 8.300000 */ printf ("%i\n", y(5.0)); /* 8 */ printf ("%i\n", y(3.3)); /* 11 */ printf ("%c\n", z(5)); /* f */ return 0; }
http://rosettacode.org/wiki/Ackermann_function
Ackermann function
The Ackermann function is a classic example of a recursive function, notable especially because it is not a primitive recursive function. It grows very quickly in value, as does the size of its call tree. The Ackermann function is usually defined as follows: A ( m , n ) = { n + 1 if  m = 0 A ( m − 1 , 1 ) if  m > 0  and  n = 0 A ( m − 1 , A ( m , n − 1 ) ) if  m > 0  and  n > 0. {\displaystyle A(m,n)={\begin{cases}n+1&{\mbox{if }}m=0\\A(m-1,1)&{\mbox{if }}m>0{\mbox{ and }}n=0\\A(m-1,A(m,n-1))&{\mbox{if }}m>0{\mbox{ and }}n>0.\end{cases}}} Its arguments are never negative and it always terminates. Task Write a function which returns the value of A ( m , n ) {\displaystyle A(m,n)} . Arbitrary precision is preferred (since the function grows so quickly), but not required. See also Conway chained arrow notation for the Ackermann function.
#360_Assembly
360 Assembly
* Ackermann function 07/09/2015 &LAB XDECO &REG,&TARGET .*-----------------------------------------------------------------* .* THIS MACRO DISPLAYS THE REGISTER CONTENTS AS A TRUE * .* DECIMAL VALUE. XDECO IS NOT PART OF STANDARD S360 MACROS! * *------------------------------------------------------------------* AIF (T'&REG EQ 'O').NOREG AIF (T'&TARGET EQ 'O').NODEST &LAB B I&SYSNDX BRANCH AROUND WORK AREA W&SYSNDX DS XL8 CONVERSION WORK AREA I&SYSNDX CVD &REG,W&SYSNDX CONVERT TO DECIMAL MVC &TARGET,=XL12'402120202020202020202020' ED &TARGET,W&SYSNDX+2 MAKE FIELD PRINTABLE BC 2,*+12 BYPASS NEGATIVE MVI &TARGET+12,C'-' INSERT NEGATIVE SIGN B *+8 BYPASS POSITIVE MVI &TARGET+12,C'+' INSERT POSITIVE SIGN MEXIT .NOREG MNOTE 8,'INPUT REGISTER OMITTED' MEXIT .NODEST MNOTE 8,'TARGET FIELD OMITTED' MEXIT MEND ACKERMAN CSECT USING ACKERMAN,R12 r12 : base register LR R12,R15 establish base register ST R14,SAVER14A save r14 LA R4,0 m=0 LOOPM CH R4,=H'3' do m=0 to 3 BH ELOOPM LA R5,0 n=0 LOOPN CH R5,=H'8' do n=0 to 8 BH ELOOPN LR R1,R4 m LR R2,R5 n BAL R14,ACKER r1=acker(m,n) XDECO R1,PG+19 XDECO R4,XD MVC PG+10(2),XD+10 XDECO R5,XD MVC PG+13(2),XD+10 XPRNT PG,44 print buffer LA R5,1(R5) n=n+1 B LOOPN ELOOPN LA R4,1(R4) m=m+1 B LOOPM ELOOPM L R14,SAVER14A restore r14 BR R14 return to caller SAVER14A DS F static save r14 PG DC CL44'Ackermann(xx,xx) = xxxxxxxxxxxx' XD DS CL12 ACKER CNOP 0,4 function r1=acker(r1,r2) LR R3,R1 save argument r1 in r3 LR R9,R10 save stackptr (r10) in r9 temp LA R1,STACKLEN amount of storage required GETMAIN RU,LV=(R1) allocate storage for stack USING STACK,R10 make storage addressable LR R10,R1 establish stack addressability ST R14,SAVER14B save previous r14 ST R9,SAVER10B save previous r10 LR R1,R3 restore saved argument r1 START ST R1,M stack m ST R2,N stack n IF1 C R1,=F'0' if m<>0 BNE IF2 then goto if2 LR R11,R2 n LA R11,1(R11) return n+1 B EXIT IF2 C R2,=F'0' else if m<>0 BNE IF3 then goto if3 BCTR R1,0 m=m-1 LA R2,1 n=1 BAL R14,ACKER r1=acker(m) LR R11,R1 return acker(m-1,1) B EXIT IF3 BCTR R2,0 n=n-1 BAL R14,ACKER r1=acker(m,n-1) LR R2,R1 acker(m,n-1) L R1,M m BCTR R1,0 m=m-1 BAL R14,ACKER r1=acker(m-1,acker(m,n-1)) LR R11,R1 return acker(m-1,1) EXIT L R14,SAVER14B restore r14 L R9,SAVER10B restore r10 temp LA R0,STACKLEN amount of storage to free FREEMAIN A=(R10),LV=(R0) free allocated storage LR R1,R11 value returned LR R10,R9 restore r10 BR R14 return to caller LTORG DROP R12 base no longer needed STACK DSECT dynamic area SAVER14B DS F saved r14 SAVER10B DS F saved r10 M DS F m N DS F n STACKLEN EQU *-STACK YREGS END ACKERMAN
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
#Action.21
Action!
PROC FillSumOfDivisors(CARD ARRAY pds CARD size,maxNum,offset) CARD i,j   FOR i=0 TO size-1 DO pds(i)=1 OD FOR i=2 TO maxNum DO FOR j=i+i TO maxNum STEP i DO IF j>=offset THEN pds(j-offset)==+i FI OD OD RETURN   PROC Main() DEFINE MAXNUM="20000" DEFINE HALFNUM="10000" CARD ARRAY pds(HALFNUM+1) CARD def,perf,abud,i,sum,offset BYTE CRSINH=$02F0 ;Controls visibility of cursor   CRSINH=1 ;hide cursor Put(125) PutE() ;clear the screen PrintE("Please wait...")   def=1 perf=0 abud=0 FillSumOfDivisors(pds,HALFNUM+1,HALFNUM,0) FOR i=2 TO HALFNUM DO sum=pds(i) IF sum<i THEN def==+1 ELSEIF sum=i THEN perf==+1 ELSE abud==+1 FI OD   offset=HALFNUM FillSumOfDivisors(pds,HALFNUM+1,MAXNUM,offset) FOR i=HALFNUM+1 TO MAXNUM DO sum=pds(i-offset) IF sum<i THEN def==+1 ELSEIF sum=i THEN perf==+1 ELSE abud==+1 FI OD   PrintF(" Numbers: %I%E",MAXNUM) PrintF("Deficient: %I%E",def) PrintF(" Perfect: %I%E",perf) PrintF(" Abudant: %I%E",abud) RETURN
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
#AppleScript
AppleScript
-- COLUMN ALIGNMENTS ---------------------------------------------------------   property pstrLines : ¬ "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."   property eLeft : -1 property eCenter : 0 property eRight : 1   -- columnsAligned :: EnumValue -> [[String]] -> String on columnsAligned(eAlign, lstCols) -- padwords :: Int -> [String] -> [[String]] script padwords on |λ|(n, lstWords)   -- pad :: String -> String script pad on |λ|(str) set lngPad to n - (length of str) if eAlign = my eCenter then set lngHalf to lngPad div 2 {replicate(lngHalf, space), str, ¬ replicate(lngPad - lngHalf, space)} else if eAlign = my eLeft then {"", str, replicate(lngPad, space)} else {replicate(lngPad, space), str, ""} end if end if end |λ| end script   map(pad, lstWords) end |λ| end script   unlines(map(my unwords, ¬ transpose(zipWith(padwords, ¬ map(my widest, lstCols), lstCols)))) end columnsAligned   -- lineColumns :: String -> String -> String on lineColumns(strColDelim, strText) -- _words :: Text -> [Text] script _words on |λ|(str) splitOn(strColDelim, str) end |λ| end script   set lstRows to map(_words, splitOn(linefeed, pstrLines)) set nCols to widest(lstRows)   -- fullRow :: [[a]] -> [[a]] script fullRow on |λ|(lst) lst & replicate(nCols - (length of lst), {""}) end |λ| end script   transpose(map(fullRow, lstRows)) end lineColumns   -- widest [a] -> Int on widest(xs) |length|(maximumBy(comparing(my |length|), xs)) end widest   -- TEST ---------------------------------------------------------------------- on run set lstCols to lineColumns("$", pstrLines)   script testAlignment on |λ|(eAlign) columnsAligned(eAlign, lstCols) end |λ| end script   intercalate(return & return, ¬ map(testAlignment, {eLeft, eRight, eCenter})) end run   -- GENERIC FUNCTIONS ---------------------------------------------------------   -- comparing :: (a -> b) -> (a -> a -> Ordering) on comparing(f) set mf to mReturn(f) script on |λ|(a, b) set x to mf's |λ|(a) set y to mf's |λ|(b) if x < y then -1 else if x > y then 1 else 0 end if end if end |λ| end script end comparing   -- foldl :: (a -> b -> a) -> a -> [b] -> a on foldl(f, startValue, xs) tell mReturn(f) set v to startValue set lng to length of xs repeat with i from 1 to lng set v to |λ|(v, item i of xs, i, xs) end repeat return v end tell end foldl   -- Text -> [Text] -> Text on intercalate(strText, lstText) set {dlm, my text item delimiters} to {my text item delimiters, strText} set strJoined to lstText as text set my text item delimiters to dlm return strJoined end intercalate   -- length :: [a] -> Int on |length|(xs) length of xs end |length|   -- Lift 2nd class handler function into 1st class script wrapper -- mReturn :: Handler -> Script on mReturn(f) if class of f is script then f else script property |λ| : f end script end if end mReturn   -- map :: (a -> b) -> [a] -> [b] on map(f, xs) tell mReturn(f) set lng to length of xs set lst to {} repeat with i from 1 to lng set end of lst to |λ|(item i of xs, i, xs) end repeat return lst end tell end map   -- maximumBy :: (a -> a -> Ordering) -> [a] -> a on maximumBy(f, xs) set cmp to mReturn(f) script max on |λ|(a, b) if a is missing value or cmp's |λ|(a, b) < 0 then b else a end if end |λ| end script   foldl(max, missing value, xs) end maximumBy   -- min :: Ord a => a -> a -> a on min(x, y) if y < x then y else x end if end min   -- Egyptian multiplication - progressively doubling a list, appending -- stages of doubling to an accumulator where needed for binary -- assembly of a target length   -- replicate :: Int -> a -> [a] on replicate(n, a) if class of a is string then set out to "" else set out to {} end if if n < 1 then return out set dbl to a   repeat while (n > 1) if (n mod 2) > 0 then set out to out & dbl set n to (n div 2) set dbl to (dbl & dbl) end repeat return out & dbl end replicate   -- Text -> Text -> [Text] on splitOn(strDelim, strMain) set {dlm, my text item delimiters} to {my text item delimiters, strDelim} set lstParts to text items of strMain set my text item delimiters to dlm return lstParts end splitOn   -- transpose :: [[a]] -> [[a]] on transpose(xss) script column on |λ|(_, iCol) script row on |λ|(xs) item iCol of xs end |λ| end script   map(row, xss) end |λ| end script   map(column, item 1 of xss) end transpose   -- [Text] -> Text on unlines(lstLines) intercalate(linefeed, lstLines) end unlines   -- [Text] -> Text on unwords(lstWords) intercalate(" ", lstWords) end unwords   -- zipWith :: (a -> b -> c) -> [a] -> [b] -> [c] on zipWith(f, xs, ys) set lng to min(length of xs, length of ys) set lst to {} tell mReturn(f) repeat with i from 1 to lng set end of lst to |λ|(item i of xs, item i of ys) end repeat return lst end tell end zipWith
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.
#EchoLisp
EchoLisp
  (require 'timer)   ;; returns an 'object' : (&lamdba; message [values]) ;; messages : input, output, sample, inspect (define (make-active) (let [ (t0 #f) (dt 0) (t 0) (Kt 0) ; K(t) (S 0) (K 0)] (lambda (message . args) (case message ((output) (// S 2)) ((input ) (set! K (car args)) (set! t0 #f)) ((inspect) (printf " Active obj : t0 %v t %v S %v " t0 t Kt (// S 2 ))) ((sample) (when (procedure? K) ;; recved new K : init (unless t0 (set! t0 (first args)) (set! t 0) (set! Kt (K 0)))   ;; integrate K(t) every time 'sample message is received (set! dt (- (first args) t t0)) ;; compute once K(t) (set! S (+ S (* dt Kt))) (set! t (+ t dt)) (set! Kt (K t)) (set! S (+ S (* dt Kt)))))   (else (error "active:bad message" message))))))  
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
#Rust
Rust
fn perfect_powers(n: u128) -> Vec<u128> { let mut powers = Vec::<u128>::new(); let sqrt = (n as f64).sqrt() as u128; for i in 2..=sqrt { let mut p = i * i; while p < n { powers.push(p); p *= i; } } powers.sort(); powers.dedup(); powers }   fn bsearch<T: Ord>(vector: &Vec<T>, value: &T) -> bool { match vector.binary_search(value) { Ok(_) => true, _ => false, } }   fn achilles(from: u128, to: u128, pps: &Vec<u128>) -> Vec<u128> { let mut result = Vec::<u128>::new(); let cbrt = ((to / 4) as f64).cbrt() as u128; let sqrt = ((to / 8) as f64).sqrt() as u128; for b in 2..=cbrt { let b3 = b * b * b; for a in 2..=sqrt { let p = b3 * a * a; if p >= to { break; } if p >= from && !bsearch(&pps, &p) { result.push(p); } } } result.sort(); result.dedup(); result }   fn totient(mut n: u128) -> u128 { let mut tot = n; if (n & 1) == 0 { while (n & 1) == 0 { n >>= 1; } tot -= tot >> 1; } let mut p = 3; while p * p <= n { if n % p == 0 { while n % p == 0 { n /= p; } tot -= tot / p; } p += 2; } if n > 1 { tot -= tot / n; } tot }   fn main() { use std::time::Instant; let t0 = Instant::now(); let limit = 1000000000000000u128;   let pps = perfect_powers(limit); let ach = achilles(1, 1000000, &pps);   println!("First 50 Achilles numbers:"); for i in 0..50 { print!("{:4}{}", ach[i], if (i + 1) % 10 == 0 { "\n" } else { " " }); }   println!("\nFirst 50 strong Achilles numbers:"); for (i, n) in ach .iter() .filter(|&x| bsearch(&ach, &totient(*x))) .take(50) .enumerate() { print!("{:6}{}", n, if (i + 1) % 10 == 0 { "\n" } else { " " }); } println!();   let mut from = 1u128; let mut to = 100u128; let mut digits = 2; while to <= limit { let count = achilles(from, to, &pps).len(); println!("{:2} digits: {}", digits, count); from = to; to *= 10; digits += 1; }   let duration = t0.elapsed(); println!("\nElapsed time: {} milliseconds", duration.as_millis()); }
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
#Wren
Wren
import "./math" for Int import "./seq" for Lst import "./fmt" for Fmt   var maxDigits = 8 var limit = 10.pow(maxDigits) var c = Int.primeSieve(limit-1, false)   var totient = Fn.new { |n| var tot = n var i = 2 while (i*i <= n) { if (n%i == 0) { while(n%i == 0) n = (n/i).floor tot = tot - (tot/i).floor } if (i == 2) i = 1 i = i + 2 } if (n > 1) tot = tot - (tot/n).floor return tot }   var isPerfectPower = Fn.new { |n| if (n == 1) return true var x = 2 while (x * x <= n) { var y = 2 var p = x.pow(y) while (p > 0 && p <= n) { if (p == n) return true y = y + 1 p = x.pow(y) } x = x + 1 } return false }   var isPowerful = Fn.new { |n| while (n % 2 == 0) { var p = 0 while (n % 2 == 0) { n = (n/2).floor p = p + 1 } if (p == 1) return false } var f = 3 while (f * f <= n) { var p = 0 while (n % f == 0) { n = (n/f).floor p = p + 1 } if (p == 1) return false f = f + 2 } return n == 1 }   var isAchilles = Fn.new { |n| c[n] && isPowerful.call(n) && !isPerfectPower.call(n) }   var isStrongAchilles = Fn.new { |n| if (!isAchilles.call(n)) return false var tot = totient.call(n) return isAchilles.call(tot) }   System.print("First 50 Achilles numbers:") var achilles = [] var count = 0 var n = 2 while (count < 50) { if (isAchilles.call(n)) { achilles.add(n) count = count + 1 } n = n + 1 } for (chunk in Lst.chunks(achilles, 10)) Fmt.print("$4d", chunk)   System.print("\nFirst 30 strong Achilles numbers:") var strongAchilles = [] count = 0 n = achilles[0] while (count < 30) { if (isStrongAchilles.call(n)) { strongAchilles.add(n) count = count + 1 } n = n + 1 } for (chunk in Lst.chunks(strongAchilles, 10)) Fmt.print("$5d", chunk)   System.print("\nNumber of Achilles numbers with:") var pow = 10 for (i in 2..maxDigits) { var count = 0 for (j in pow..pow*10-1) { if (isAchilles.call(j)) count = count + 1 } System.print("%(i) digits: %(count)") pow = pow * 10 }
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
#Java
Java
import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.stream.LongStream;   public class AliquotSequenceClassifications {   private static Long properDivsSum(long n) { return LongStream.rangeClosed(1, (n + 1) / 2).filter(i -> n % i == 0 && n != i).sum(); }   static boolean aliquot(long n, int maxLen, long maxTerm) { List<Long> s = new ArrayList<>(maxLen); s.add(n); long newN = n;   while (s.size() <= maxLen && newN < maxTerm) {   newN = properDivsSum(s.get(s.size() - 1));   if (s.contains(newN)) {   if (s.get(0) == newN) {   switch (s.size()) { case 1: return report("Perfect", s); case 2: return report("Amicable", s); default: return report("Sociable of length " + s.size(), s); }   } else if (s.get(s.size() - 1) == newN) { return report("Aspiring", s);   } else return report("Cyclic back to " + newN, s);   } else { s.add(newN); if (newN == 0) return report("Terminating", s); } }   return report("Non-terminating", s); }   static boolean report(String msg, List<Long> result) { System.out.println(msg + ": " + result); return false; }   public static void main(String[] args) { long[] arr = { 11, 12, 28, 496, 220, 1184, 12496, 1264460, 790, 909, 562, 1064, 1488};   LongStream.rangeClosed(1, 10).forEach(n -> aliquot(n, 16, 1L << 47)); System.out.println(); Arrays.stream(arr).forEach(n -> aliquot(n, 16, 1L << 47)); } }
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.
#Pop11
Pop11
lib objectclass;   define :class foo; enddefine;   define define_named_method(method, class); lvars method_str = method >< ''; lvars class_str = class >< ''; lvars method_hash_str = 'hash_' >< length(class_str) >< '_' >< class_str >< '_' >< length(method_str) >< '_' >< method_str; lvars method_hash = consword(method_hash_str); pop11_compile([ lvars ^method_hash = newassoc([]); define :method ^method(self : ^class); ^method_hash(self); enddefine; define :method updaterof ^method(val, self : ^class); val -> ^method_hash(self); enddefine; ]); enddefine;   define_named_method("met1", "foo"); lvars bar = consfoo(); met1(bar) =>  ;;; default value -- false "baz" -> met1(bar); met1(bar) =>  ;;; new value
http://rosettacode.org/wiki/Add_a_variable_to_a_class_instance_at_runtime
Add a variable to a class instance at runtime
Demonstrate how to dynamically add variables to an object (a class instance) at runtime. This is useful when the methods/variables of an instance are based on a data file that isn't available until runtime. Hal Fulton gives an example of creating an OO CSV parser at An Exercise in Metaprogramming with Ruby. This is referred to as "monkeypatching" by Pythonistas and some others.
#PowerShell
PowerShell
$x = 42 ` | Add-Member -PassThru ` NoteProperty ` Title ` "The answer to the question about life, the universe and everything"
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.
#Python
Python
class empty(object): pass e = empty()
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.
#Raku
Raku
class Bar { } # an empty class   my $object = Bar.new; # new instance   role a_role { # role to add a variable: foo, has $.foo is rw = 2; # with an initial value of 2 }   $object does a_role; # compose in the role   say $object.foo; # prints: 2 $object.foo = 5; # change the variable say $object.foo; # prints: 5   my $ohno = Bar.new; # new Bar object #say $ohno.foo; # runtime error, base Bar class doesn't have the variable foo   my $this = $object.new; # instantiate a new Bar derived from $object say $this.foo; # prints: 2 - original role value   my $that = $object.clone; # instantiate a new Bar derived from $object copying any variables say $that.foo; # 5 - value from the cloned object
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.
#PowerBASIC
PowerBASIC
'get a variable's address: DIM x AS INTEGER, y AS LONG y = VARPTR(x)   'can't set the address of a single variable, but can access memory locations DIM z AS INTEGER z = PEEK(INTEGER, y)   'or can do it one byte at a time DIM zz(1) AS BYTE zz(0) = PEEK(BYTE, y) zz(1) = PEEK(BYTE, y + 1) '(MAK creates an INTEGER, LONG, or QUAD out of the next smaller type) z = MAK(INTEGER, zz(0), zz(1))   '*can* set the address of an array DIM zzz(1) AS BYTE AT y 'zzz(0) = low byte of x, zzz(1) = high byte of x
http://rosettacode.org/wiki/Address_of_a_variable
Address of a variable
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation | Comparison | Matching Memory Operations Pointers & references | Addresses Task Demonstrate how to get the address of a variable and how to set the address of a variable.
#PureBasic
PureBasic
a.i = 5 MessageRequester("Address",Str(@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.
#Python
Python
foo = object() # Create (instantiate) an empty object address = id(foo)
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.
#QB64
QB64
  ' Adapted from QB64wiki example a demo of _MEM type data and _MEM functions Type points x As Integer y As Integer z As Integer End Type   Dim Shared m(3) As _MEM Dim Shared Saved As points, first As points   m(1) = _Mem(first.x) m(2) = _Mem(first.y) m(3) = _Mem(first.z)   print "QB64 way to manage address of variable..." first.x = 3: first.y = 5: first.z = 8 Print first.x, first.y, first.z Save first first.x = 30: first.y = 50: first.z = 80 Print first.x, first.y, first.z   RestoreIt Print first.x, first.y, first.z   _MemFree m(1) _MemFree m(2) _MemFree m(3) End   Sub Save (F As points) Saved.x = F.x Saved.y = F.y Saved.z = F.z End Sub   Sub RestoreIt _MemPut m(1), m(1).OFFSET, Saved.x _MemPut m(2), m(2).OFFSET, Saved.y _MemPut m(3), m(3).OFFSET, Saved.z End Sub  
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.
#Elixir
Elixir
defmodule AKS do def iterate(f, x), do: fn -> [x | iterate(f, f.(x))] end   def take(0, _lazy), do: [] def take(n, lazy) do [value | next] = lazy.() [value | take(n-1, next)] end   def pascal, do: iterate(fn row -> [1 | sum_adj(row)] end, [1])   defp sum_adj([_] = l), do: l defp sum_adj([a, b | _] = row), do: [a+b | sum_adj(tl(row))]   def show_binomial(row) do degree = length(row) - 1 ["(x - 1)^", to_char_list(degree), " =", binomial_rhs(row, 1, degree)] end   defp show_x(0), do: "" defp show_x(1), do: "x" defp show_x(n), do: [?x, ?^ | to_char_list(n)]   defp binomial_rhs([], _, _), do: [] defp binomial_rhs([coef | coefs], sgn, exp) do signchar = if sgn > 0, do: ?+, else: ?- [0x20, signchar, 0x20, to_char_list(coef), show_x(exp) | binomial_rhs(coefs, -sgn, exp-1)] end   def primerow(row, n), do: Enum.all?(row, fn coef -> (coef == 1) or (rem(coef, n) == 0) end)   def main do for row <- take(8, pascal), do: IO.puts show_binomial(row) IO.write "\nThe primes upto 50: " IO.inspect for {row, n} <- Enum.zip(tl(tl(take(51, pascal))), 2..50), primerow(row, n), do: n end end   AKS.main
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.
#jq
jq
def is_prime: . as $n | if ($n < 2) then false elif ($n % 2 == 0) then $n == 2 elif ($n % 3 == 0) then $n == 3 elif ($n % 5 == 0) then $n == 5 elif ($n % 7 == 0) then $n == 7 elif ($n % 11 == 0) then $n == 11 elif ($n % 13 == 0) then $n == 13 elif ($n % 17 == 0) then $n == 17 elif ($n % 19 == 0) then $n == 19 else {i:23} | until( (.i * .i) > $n or ($n % .i == 0); .i += 2) | .i * .i > $n end;   # Emit an array of primes less than `.` def primes: if . < 2 then [] else [2] + [range(3; .; 2) | select(is_prime)] end;   def add(s): reduce s as $x (null; . + $x);   def sumdigits: add(tostring | explode[] | [.] | implode | tonumber);   # Pretty-printing def nwise($n): def n: if length <= $n then . else .[0:$n] , (.[$n:] | n) end; n;   def lpad($len): tostring | ($len - length) as $l | (" " * $l)[:$l] + .;  
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.
#Haskell
Haskell
import Data.List (unfoldr)   -- infinite list of primes primes = 2 : sieve [3,5..] where sieve (x:xs) = x : sieve (filter (\y -> y `mod` x /= 0) xs)   -- primarity test, effective for numbers less then billion isPrime n = all (\p -> n `mod` p /= 0) $ takeWhile (< sqrtN) primes where sqrtN = round . sqrt . fromIntegral $ n   -- decimal digits of a number digits = unfoldr f where f 0 = Nothing f n = let (q, r) = divMod n 10 in Just (r,q)   -- test for an additive prime isAdditivePrime n = isPrime n && (isPrime . sum . digits) n  
http://rosettacode.org/wiki/Almost_prime
Almost prime
A   k-Almost-prime   is a natural number   n {\displaystyle n}   that is the product of   k {\displaystyle k}   (possibly identical) primes. Example 1-almost-primes,   where   k = 1 {\displaystyle k=1} ,   are the prime numbers themselves. 2-almost-primes,   where   k = 2 {\displaystyle k=2} ,   are the   semiprimes. Task Write a function/method/subroutine/... that generates k-almost primes and use it to create a table here of the first ten members of k-Almost primes for   1 <= K <= 5 {\displaystyle 1<=K<=5} . Related tasks   Semiprime   Category:Prime Numbers
#JavaScript
JavaScript
function almostPrime (n, k) { var divisor = 2, count = 0 while(count < k + 1 && n != 1) { if (n % divisor == 0) { n = n / divisor count = count + 1 } else { divisor++ } } return count == k }   for (var k = 1; k <= 5; k++) { document.write("<br>k=", k, ": ") var count = 0, n = 0 while (count <= 10) { n++ if (almostPrime(n, k)) { document.write(n, " ") count++ } } }
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
#E
E
println("Downloading...") when (def wordText := <http://wiki.puzzlers.org/pub/wordlists/unixdict.txt> <- getText()) -> { def words := wordText.split("\n")   def storage := [].asMap().diverge() def anagramTable extends storage { to get(key) { return storage.fetch(key, fn { storage[key] := [].diverge() }) } }   println("Grouping...") var largestGroupSeen := 0 for word in words { def anagramGroup := anagramTable[word.sort()] anagramGroup.push(word) largestGroupSeen max= anagramGroup.size() }   println("Selecting...") for _ => anagramGroup ? (anagramGroup.size() == mostSeen) in anagramTable { println(anagramGroup.snapshot()) } }
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
#Quackery
Quackery
[ $ "bigrat.qky" loadfile ] now!   [ v- -v proper rot 360 mod unrot improper 180 1 2over v< iff [ 360 1 v- ] done 2dup -180 1 v< if [ 360 1 v+ ] ] is angledelta ( n/d n/d --> n/d )   ' [ [ $ "20" $ "45" ] [ $ "-45" $ "45" ] [ $ "85" $ "90" ] [ $ "-95" $ "90" ] [ $ "-45" $ "125" ] [ $ "45" $ "145" ] [ $ "29.4803" $ "-88.6361" ] [ $ "-78.3251" $ "-159.0360" ] [ $ "-70099.74233810938" $ "29840.67437876723" ] [ $ "-165313.6666297357" $ "33693.9894517456" ] [ $ "1174.8380510598456" $ "-154146.66490124757" ] [ $ "60175.773067955546" $ "42213.07192354373" ] ]   witheach [ do dip [ $->v drop ] $->v drop angledelta 20 point$ echo$ cr ]
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
#Racket
Racket
#lang racket (define (% a b) (- a (* b (truncate (/ a b)))))   (define (bearing- bearing heading) (- (% (+ (% (- bearing heading) 360) 540) 360) 180))   (module+ main (bearing- 20 45) (bearing- -45 45) (bearing- -85 90) (bearing- -95 90) (bearing- -45 125) (bearing- -45 145) (bearing- 29.4803 -88.6381) (bearing- -78.3251 -159.036)   (bearing- -70099.74233810938 29840.67437876723) (bearing- -165313.6666297357 33693.9894517456) (bearing- 1174.8380510598456 -154146.66490124757) (bearing- 60175.77306795546 42213.07192354373))   (module+ test (require rackunit)   (check-equal? (% 7.5 10) 7.5) (check-equal? (% 17.5 10) 7.5) (check-equal? (% -7.5 10) -7.5) (check-equal? (% -17.5 10) -7.5))
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
#Ring
Ring
# Project : Anagrams/Deranged anagrams   load "stdlib.ring" fn1 = "unixdict.txt"   fp = fopen(fn1,"r") str = fread(fp, getFileSize(fp)) fclose(fp) strlist = str2list(str) anagram = newlist(len(strlist), 5) anag = list(len(strlist)) result = list(len(strlist)) for x = 1 to len(result) result[x] = 0 next for x = 1 to len(anag) anag[x] = 0 next for x = 1 to len(anagram) for y = 1 to 5 anagram[x][y] = 0 next next   strbig = 1 for n = 1 to len(strlist) for m = 1 to len(strlist) sum = 0 if len(strlist[n]) = len(strlist[m]) and n != m for p = 1 to len(strlist[m]) temp1 = count(strlist[n], strlist[m][p]) temp2 = count(strlist[m], strlist[m][p]) if temp1 = temp2 sum = sum + 1 ok next if sum = len(strlist[n]) anag[n] = anag[n] + 1 if anag[n] < 6 and result[n] = 0 and result[m] = 0 anagram[n][anag[n]] = strlist[m] if len(strlist[m]) > len(strlist[strbig]) strbig = n ok result[m] = 1 ok ok ok next if anag[n] > 0 result[n] = 1 ok next   flag = 0 for m = 1 to 5 if anagram[strbig][m] != 0 if m = 1 see strlist[strbig] + " " flag = 1 ok see anagram[strbig][m] + " " ok next   func getFileSize fp c_filestart = 0 c_fileend = 2 fseek(fp,0,c_fileend) nfilesize = ftell(fp) fseek(fp,0,c_filestart) return nfilesize   func count(astring,bstring) cnt = 0 while substr(astring,bstring) > 0 cnt = cnt + 1 astring = substr(astring,substr(astring,bstring)+len(string(sum))) end return cnt
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.
#Pascal
Pascal
  program AnonymousRecursion;   function Fib(X: Integer): integer;   function DoFib(N: Integer): Integer; begin if N < 2 then DoFib:=N else DoFib:=DoFib(N-1) + DoFib(N-2); end;   begin if X < 0 then Fib:=X else Fib:=DoFib(X); end;     var I,V: integer;   begin for I:=-1 to 15 do begin V:=Fib(I); Write(I:3,' - ',V:3); if V<0 then Write(' - Error'); WriteLn; end; WriteLn('Hit Any Key'); ReadLn; end.  
http://rosettacode.org/wiki/Amicable_pairs
Amicable pairs
Two integers N {\displaystyle N} and M {\displaystyle M} are said to be amicable pairs if N ≠ M {\displaystyle N\neq M} and the sum of the proper divisors of N {\displaystyle N} ( s u m ( p r o p D i v s ( N ) ) {\displaystyle \mathrm {sum} (\mathrm {propDivs} (N))} ) = M {\displaystyle =M} as well as s u m ( p r o p D i v s ( M ) ) = N {\displaystyle \mathrm {sum} (\mathrm {propDivs} (M))=N} . Example 1184 and 1210 are an amicable pair, with proper divisors:   1, 2, 4, 8, 16, 32, 37, 74, 148, 296, 592   and   1, 2, 5, 10, 11, 22, 55, 110, 121, 242, 605   respectively. Task Calculate and show here the Amicable pairs below 20,000; (there are eight). Related tasks Proper divisors Abundant, deficient and perfect number classifications Aliquot sequence classifications and its amicable classification.
#OCaml
OCaml
let rec isqrt n = if n = 1 then 1 else let _n = isqrt (n - 1) in (_n + (n / _n)) / 2   let sum_divs n = let sum = ref 1 in for d = 2 to isqrt n do if (n mod d) = 0 then sum := !sum + (n / d + d); done; !sum   let () = for n = 2 to 20000 do let m = sum_divs n in if (m > n) then if (sum_divs m) = n then Printf.printf "%d %d\n" n m; done  
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.
#R
R
library(DescTools)   pendulum<-function(length=5,radius=1,circle.color="white",bg.color="white"){ tseq = c(seq(0,pi,by=.1),seq(pi,0,by=-.1)) slow=.27;fast=.07 sseq = c(seq(slow,fast,length.out = length(tseq)/4),seq(fast,slow,length.out = length(tseq)/4),seq(slow,fast,length.out = length(tseq)/4),seq(fast,slow,length.out = length(tseq)/4)) plot(0,0,xlim=c((-length-radius)*1.2,(length+radius)*1.2),ylim=c((-length-radius)*1.2,0),xaxt="n",yaxt="n",xlab="",ylab="") cat("Press Esc to end animation")   while(T){ for(i in 1:length(tseq)){ rect(par("usr")[1],par("usr")[3],par("usr")[2],par("usr")[4],col = bg.color) abline(h=0,col="grey") points(0,0) DrawCircle((radius+length)*cos(tseq[i]),(radius+length)*-sin(tseq[i]),r.out=radius,col=circle.color) lines(c(0,length*cos(tseq[i])),c(0,length*-sin(tseq[i]))) Sys.sleep(sseq[i]) } }   }   pendulum(5,1,"gold","lightblue")
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.
#JavaScript
JavaScript
function ambRun(func) { var choices = []; var index;   function amb(values) { if (values.length == 0) { fail(); } if (index == choices.length) { choices.push({i: 0, count: values.length}); } var choice = choices[index++]; return values[choice.i]; }   function fail() { throw fail; }   while (true) { try { index = 0; return func(amb, fail); } catch (e) { if (e != fail) { throw e; } var choice; while ((choice = choices.pop()) && ++choice.i == choice.count) {} if (choice == undefined) { return undefined; } choices.push(choice); } } }   ambRun(function(amb, fail) { function linked(s1, s2) { return s1.slice(-1) == s2.slice(0, 1); }   var w1 = amb(["the", "that", "a"]); var w2 = amb(["frog", "elephant", "thing"]); if (!linked(w1, w2)) fail();   var w3 = amb(["walked", "treaded", "grows"]); if (!linked(w2, w3)) fail();   var w4 = amb(["slowly", "quickly"]); if (!linked(w3, w4)) fail();   return [w1, w2, w3, w4].join(' '); }); // "that thing grows slowly"
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.
#C.23
C#
using System;   class Program { static Func<dynamic, dynamic> Foo(dynamic n) { return i => n += i; }   static void Main(string[] args) { var x = Foo(1); x(5); Foo(3); Console.WriteLine(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.
#C.2B.2B
C++
#include <iostream>   class Acc { public: Acc(int init) : _type(intType) , _intVal(init) {}   Acc(float init) : _type(floatType) , _floatVal(init) {}   int operator()(int x) { if( _type == intType ) { _intVal += x; return _intVal; } else { _floatVal += x; return static_cast<int>(_floatVal); } }   float operator()(float x) { if( _type == intType ) { _floatVal = _intVal + x; _type = floatType; return _floatVal; } else { _floatVal += x; return _floatVal; } } private: enum {floatType, intType} _type; float _floatVal; int _intVal; };   int main() { Acc a(1); a(5); Acc(3); std::cout << a(2.3f); return 0; }
http://rosettacode.org/wiki/Ackermann_function
Ackermann function
The Ackermann function is a classic example of a recursive function, notable especially because it is not a primitive recursive function. It grows very quickly in value, as does the size of its call tree. The Ackermann function is usually defined as follows: A ( m , n ) = { n + 1 if  m = 0 A ( m − 1 , 1 ) if  m > 0  and  n = 0 A ( m − 1 , A ( m , n − 1 ) ) if  m > 0  and  n > 0. {\displaystyle A(m,n)={\begin{cases}n+1&{\mbox{if }}m=0\\A(m-1,1)&{\mbox{if }}m>0{\mbox{ and }}n=0\\A(m-1,A(m,n-1))&{\mbox{if }}m>0{\mbox{ and }}n>0.\end{cases}}} Its arguments are never negative and it always terminates. Task Write a function which returns the value of A ( m , n ) {\displaystyle A(m,n)} . Arbitrary precision is preferred (since the function grows so quickly), but not required. See also Conway chained arrow notation for the Ackermann function.
#68000_Assembly
68000 Assembly
; ; Ackermann function for Motorola 68000 under AmigaOs 2+ by Thorham ; ; Set stack space to 60000 for m = 3, n = 5. ; ; The program will print the ackermann values for the range m = 0..3, n = 0..5 ; _LVOOpenLibrary equ -552 _LVOCloseLibrary equ -414 _LVOVPrintf equ -954   m equ 3 ; Nr of iterations for the main loop. n equ 5 ; Do NOT set them higher, or it will take hours to complete on ; 68k, not to mention that the stack usage will become astronomical. ; Perhaps n can be a little higher... If you do increase the ranges ; then don't forget to increase the stack size.   execBase=4   start move.l execBase,a6   lea dosName,a1 moveq #36,d0 jsr _LVOOpenLibrary(a6) move.l d0,dosBase beq exit   move.l dosBase,a6 lea printfArgs,a2   clr.l d3 ; m .loopn clr.l d4 ; n .loopm bsr ackermann   move.l d3,0(a2) move.l d4,4(a2) move.l d5,8(a2) move.l #outString,d1 move.l a2,d2 jsr _LVOVPrintf(a6)   addq.l #1,d4 cmp.l #n,d4 ble .loopm   addq.l #1,d3 cmp.l #m,d3 ble .loopn   exit move.l execBase,a6 move.l dosBase,a1 jsr _LVOCloseLibrary(a6) rts ; ; ackermann function ; ; in: ; ; d3 = m ; d4 = n ; ; out: ; ; d5 = ans ; ackermann move.l d3,-(sp) move.l d4,-(sp)   tst.l d3 bne .l1 move.l d4,d5 addq.l #1,d5 bra .return .l1 tst.l d4 bne .l2 subq.l #1,d3 moveq #1,d4 bsr ackermann bra .return .l2 subq.l #1,d4 bsr ackermann move.l d5,d4 subq.l #1,d3 bsr ackermann   .return move.l (sp)+,d4 move.l (sp)+,d3 rts ; ; variables ; dosBase dc.l 0   printfArgs dcb.l 3 ; ; strings ; dosName dc.b "dos.library",0   outString dc.b "ackermann (%ld,%ld) is: %ld",10,0
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
#Ada
Ada
with Ada.Text_IO, Generic_Divisors;   procedure ADB_Classification is function Same(P: Positive) return Positive is (P); package Divisor_Sum is new Generic_Divisors (Result_Type => Natural, None => 0, One => Same, Add => "+");   type Class_Type is (Deficient, Perfect, Abundant);   function Class(D_Sum, N: Natural) return Class_Type is (if D_Sum < N then Deficient elsif D_Sum = N then Perfect else Abundant);   Cls: Class_Type; Results: array (Class_Type) of Natural := (others => 0);   package NIO is new Ada.Text_IO.Integer_IO(Natural); package CIO is new Ada.Text_IO.Enumeration_IO(Class_Type); begin for N in 1 .. 20_000 loop Cls := Class(Divisor_Sum.Process(N), N); Results(Cls) := Results(Cls)+1; end loop; for Class in Results'Range loop CIO.Put(Class, 12); NIO.Put(Results(Class), 8); Ada.Text_IO.New_Line; end loop; Ada.Text_IO.Put_Line("--------------------"); Ada.Text_IO.Put("Sum "); NIO.Put(Results(Deficient)+Results(Perfect)+Results(Abundant), 8); Ada.Text_IO.New_Line; Ada.Text_IO.Put_Line("===================="); end ADB_Classification;
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
#ARM_Assembly
ARM Assembly
  /* ARM assembly Raspberry PI */ /* program alignColumn.s */   /* REMARK 1 : this program use routines in a include file see task Include a file language arm assembly for the routine affichageMess conversion10 see at end of this program the instruction include */ /* for constantes see task include a file in arm assembly */ /************************************/ /* Constantes */ /************************************/ .include "../constantes.inc" .equ BUFFERSIZE, 20 * 10   /*********************************/ /* Initialized data */ /*********************************/ .data szMessLeft: .asciz "LEFT :\n" szMessRight: .asciz "\nRIGHT :\n" szMessCenter: .asciz "\nCENTER :\n" szCarriageReturn: .asciz "\n"   szLine1: .asciz "Given$a$text$file$of$many$lines,$where$fields$within$a$line$" szLine2: .asciz "are$delineated$by$a$single$'dollar'$character,$write$a$program" szLine3: .asciz "that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$" szLine4: .asciz "column$are$separated$by$at$least$one$space." szLine5: .asciz "Further,$allow$for$each$word$in$a$column$to$be$either$left$" szLine6: .asciz "justified,$right$justified,$or$center$justified$within$its$column."   itbPtLine: .int szLine1,szLine2,szLine3,szLine4,szLine5,szLine6 .equ NBLINES, (. - itbPtLine) / 4   /*********************************/ /* UnInitialized data */ /*********************************/ .bss /*********************************/ /* code section */ /*********************************/ .text .global main main: @ entry of program ldr r0,iAdritbPtLine bl computeMaxiLengthWords mov r10,r0 @ column counter ldr r0,iAdrszMessLeft bl affichageMess ldr r0,iAdritbPtLine mov r1,r10 @ column size bl alignLeft ldr r0,iAdrszMessRight bl affichageMess ldr r0,iAdritbPtLine mov r1,r10 @ column size bl alignRight ldr r0,iAdrszMessCenter bl affichageMess ldr r0,iAdritbPtLine mov r1,r10 @ column size bl alignCenter 100: @ standard end of the program mov r0, #0 @ return code mov r7, #EXIT @ request to exit program svc #0 @ perform the system call iAdrszCarriageReturn: .int szCarriageReturn iAdrszMessLeft: .int szMessLeft iAdrszMessRight: .int szMessRight iAdrszMessCenter: .int szMessCenter iAdritbPtLine: .int itbPtLine /******************************************************************/ /* compute maxi words */ /******************************************************************/ /* r0 contains adresse pointer array */ computeMaxiLengthWords: push {r1-r6,lr} @ save registers mov r2,#0 @ indice pointer array mov r3,#0 @ maxi length words 1: ldr r1,[r0,r2,lsl #2] @ load pointer mov r4,#0 @ length words counter mov r5,#0 @ indice line character 2: ldrb r6,[r1,r5] @ load a line character cmp r6,#0 @ line end ? beq 4f cmp r6,#'$' @ separator ? bne 3f cmp r4,r3 movgt r3,r4 @ ig greather replace maxi mov r4,#-1 @ raz length counter 3: add r4,r4,#1 add r5,r5,#1 @ increment character indice b 2b @ and loop 4: @ end line cmp r4,r3 @ compare word counter and maxi movgt r3,r4 @ if greather replace maxi add r2,r2,#1 @ increment indice line pointer cmp r2,#NBLINES @ maxi ? blt 1b @ no -> loop   mov r0,r3 @ return maxi length counter 100: pop {r1-r6,pc}   /******************************************************************/ /* align left */ /******************************************************************/ /* r0 contains the address of pointer array*/ /* r1 contains column size */ alignLeft: push {r4-r7,fp,lr} @ save registers sub sp,sp,#BUFFERSIZE @ reserve place for output buffer mov fp,sp mov r5,r0 @ array address mov r2,#0 @ indice array 1: ldr r3,[r5,r2,lsl #2] @ load line pointer mov r4,#0 @ line character indice mov r7,#0 @ output buffer character indice mov r6,#0 @ word lenght 2: ldrb r0,[r3,r4] @ load a character line strb r0,[fp,r7] @ store in buffer cmp r0,#0 @ line end ? beq 6f cmp r0,#'$' @ separator ? bne 5f mov r0,#' ' strb r0,[fp,r7] @ replace $ by space 3: cmp r6,r1 @ length word >= length column bge 4f add r7,r7,#1 mov r0,#' ' strb r0,[fp,r7] @ add space to buffer add r6,r6,#1 b 3b @ and loop 4: mov r6,#-1 @ raz word length 5: add r4,r4,#1 @ increment line indice add r7,r7,#1 @ increment buffer indice add r6,r6,#1 @ increment word length b 2b   6: mov r0,#'\n' strb r0,[fp,r7] @ return line add r7,r7,#1 mov r0,#0 strb r0,[fp,r7] @ final zéro mov r0,fp bl affichageMess @ display output buffer add r2,r2,#1 cmp r2,#NBLINES blt 1b   100: add sp,sp,#BUFFERSIZE pop {r4-r7,fp,pc} /******************************************************************/ /* align right */ /******************************************************************/ /* r0 contains the address of pointer array*/ /* r1 contains column size */ alignRight: push {r4-r9,fp,lr} @ save registers sub sp,sp,#BUFFERSIZE @ reserve place for output buffer mov fp,sp mov r5,r0 @ array address mov r2,#0 @ indice array 1: ldr r3,[r5,r2,lsl #2] @ load line pointer mov r4,#0 @ line character indice mov r7,#0 @ output buffer character indice mov r6,#0 @ word lenght mov r8,r3 @ word begin address 2: @ compute word length ldrb r0,[r3,r4] @ load a character line cmp r0,#0 @ line end ? beq 3f cmp r0,#'$' @ separator ? beq 3f add r4,r4,#1 @ increment line indice add r6,r6,#1 @ increment word length b 2b   3: cmp r6,#0 beq 4f sub r6,r1,r6 @ compute left spaces to add 4: @ loop add spaces to buffer cmp r6,#0 blt 5f mov r0,#' ' strb r0,[fp,r7] @ add space to buffer add r7,r7,#1 sub r6,r6,#1 b 4b @ and loop 5: mov r9,#0 6: @ copy loop word to buffer ldrb r0,[r8,r9] cmp r0,#'$' beq 7f cmp r0,#0 @ line end beq 8f strb r0,[fp,r7] add r7,r7,#1 add r9,r9,#1 b 6b 7: add r8,r8,r9 add r8,r8,#1 @ new word begin mov r6,#0 @ raz word length add r4,r4,#1 @ increment line indice b 2b   8: mov r0,#'\n' strb r0,[fp,r7] @ return line add r7,r7,#1 mov r0,#0 strb r0,[fp,r7] @ final zéro mov r0,fp bl affichageMess @ display output buffer add r2,r2,#1 cmp r2,#NBLINES blt 1b   100: add sp,sp,#BUFFERSIZE pop {r4-r9,fp,pc} /******************************************************************/ /* align center */ /******************************************************************/ /* r0 contains the address of pointer array*/ /* r1 contains column size */ alignCenter: push {r4-r12,lr} @ save registers sub sp,sp,#BUFFERSIZE @ reserve place for output buffer mov fp,sp mov r5,r0 @ array address mov r2,#0 @ indice array 1: ldr r3,[r5,r2,lsl #2] @ load line pointer mov r4,#0 @ line character indice mov r7,#0 @ output buffer character indice mov r6,#0 @ word length mov r8,r3 @ word begin address 2: @ compute word length ldrb r0,[r3,r4] @ load a character line cmp r0,#0 @ line end ? beq 3f cmp r0,#'$' @ separator ? beq 3f add r4,r4,#1 @ increment line indice add r6,r6,#1 @ increment word length b 2b 3: cmp r6,#0 beq 5f sub r6,r1,r6 @ total spaces number to add mov r12,r6 lsr r6,r6,#1 @ divise by 2 = left spaces number 4: cmp r6,#0 blt 5f mov r0,#' ' strb r0,[fp,r7] @ add space to buffer add r7,r7,#1 @ increment output indice sub r6,r6,#1 @ decrement number space b 4b @ and loop 5: mov r9,#0 6: @ copy loop word to buffer ldrb r0,[r8,r9] cmp r0,#'$' @ séparator ? beq 7f cmp r0,#0 @ line end ? beq 10f strb r0,[fp,r7] add r7,r7,#1 add r9,r9,#1 b 6b 7: lsr r6,r12,#1 @ divise total spaces by 2 sub r6,r12,r6 @ and compute number spaces to right side 8: @ loop to add right spaces cmp r6,#0 ble 9f mov r0,#' ' strb r0,[fp,r7] @ add space to buffer add r7,r7,#1 sub r6,r6,#1 b 8b @ and loop   9: add r8,r8,r9 add r8,r8,#1 @ new address word begin mov r6,#0 @ raz word length add r4,r4,#1 @ increment line indice b 2b @ and loop new word   10: mov r0,#'\n' strb r0,[fp,r7] @ return line add r7,r7,#1 mov r0,#0 strb r0,[fp,r7] @ final zéro mov r0,fp bl affichageMess @ display output buffer add r2,r2,#1 @ increment line indice cmp r2,#NBLINES @ maxi ? blt 1b @ loop   100: add sp,sp,#BUFFERSIZE pop {r4-r12,pc} /***************************************************/ /* ROUTINES INCLUDE */ /***************************************************/ .include "../affichage.inc"  
http://rosettacode.org/wiki/Active_object
Active object
In object-oriented programming an object is active when its state depends on clock. Usually an active object encapsulates a task that updates the object's state. To the outer world the object looks like a normal object with methods that can be called from outside. Implementation of such methods must have a certain synchronization mechanism with the encapsulated task in order to prevent object's state corruption. A typical instance of an active object is an animation widget. The widget state changes with the time, while as an object it has all properties of a normal widget. The task Implement an active integrator object. The object has an input and output. The input can be set using the method Input. The input is a function of time. The output can be queried using the method Output. The object integrates its input over the time and the result becomes the object's output. So if the input is K(t) and the output is S, the object state S is changed to S + (K(t1) + K(t0)) * (t1 - t0) / 2, i.e. it integrates K using the trapeze method. Initially K is constant 0 and S is 0. In order to test the object: set its input to sin (2π f t), where the frequency f=0.5Hz. The phase is irrelevant. wait 2s set the input to constant 0 wait 0.5s Verify that now the object's output is approximately 0 (the sine has the period of 2s). The accuracy of the result will depend on the OS scheduler time slicing and the accuracy of the clock.
#Erlang
Erlang
  -module( active_object ). -export( [delete/1, input/2, new/0, output/1, task/1] ). -compile({no_auto_import,[time/0]}).   delete( Object ) -> Object ! stop.   input( Object, Fun ) -> Object ! {input, Fun}.   new( ) -> K = fun zero/1, S = 0, T0 = seconds_with_decimals(), erlang:spawn( fun() -> loop(K, S, T0) end ).   output( Object ) -> Object ! {output, erlang:self()}, receive {output, Object, Output} -> Output end.   task( Integrate_millisec ) -> Object = new(), {ok, _Ref} = timer:send_interval( Integrate_millisec, Object, integrate ), io:fwrite( "New ~p~n", [output(Object)] ), input( Object, fun sine/1 ), timer:sleep( 2000 ), io:fwrite( "Sine ~p~n", [output(Object)] ), input( Object, fun zero/1 ), timer:sleep( 500 ), io:fwrite( "Approx ~p~n", [output(Object)] ), delete( Object ).       loop( Fun, Sum, T0 ) -> receive integrate -> T1 = seconds_with_decimals(), New_sum = trapeze( Sum, Fun, T0, T1 ), loop( Fun, New_sum, T1 ); stop -> ok; {input, New_fun} -> loop( New_fun, Sum, T0 ); {output, Pid} -> Pid ! {output, erlang:self(), Sum}, loop( Fun, Sum, T0 ) end.   sine( T ) -> math:sin( 2 * math:pi() * 0.5 * T ).   seconds_with_decimals() -> {Megaseconds, Seconds, Microseconds} = os:timestamp(), (Megaseconds * 1000000) + Seconds + (Microseconds / 1000000).   trapeze( Sum, Fun, T0, T1 ) -> Sum + (Fun(T1) + Fun(T0)) * (T1 - T0) / 2.   zero( _ ) -> 0.