task_url
stringlengths
30
116
task_name
stringlengths
2
86
task_description
stringlengths
0
14.4k
language_url
stringlengths
2
53
language_name
stringlengths
1
52
code
stringlengths
0
61.9k
http://rosettacode.org/wiki/Animation
Animation
Animation is integral to many parts of GUIs, including both the fancy effects when things change used in window managers, and of course games.   The core of any animation system is a scheme for periodically changing the display while still remaining responsive to the user.   This task demonstrates this. Task Creat...
#Scratch
Scratch
'Animation, by rbytes and Dutchman word$="Hello World! " 'use button window with text SET BUTTONS CUSTOM SET BUTTONS FONT SIZE 40 DRAW COLOR 0,0,0 DO 'the button is redrawn each loop BUTTON "anim" TEXT word$ AT 130,100 PAUSE .1 'touching the button reverses the scrolling IF BUTTON_PRESSED("anim") THEN flag=1-flag IF fl...
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 Creat...
#smart_BASIC
smart BASIC
'Animation, by rbytes and Dutchman word$="Hello World! " 'use button window with text SET BUTTONS CUSTOM SET BUTTONS FONT SIZE 40 DRAW COLOR 0,0,0 DO 'the button is redrawn each loop BUTTON "anim" TEXT word$ AT 130,100 PAUSE .1 'touching the button reverses the scrolling IF BUTTON_PRESSED("anim") THEN flag=1-flag IF fl...
http://rosettacode.org/wiki/Animate_a_pendulum
Animate a pendulum
One good way of making an animation is by simulating a physical system and illustrating the variables in that system using a dynamically changing graphical display. The classic such physical system is a simple gravity pendulum. Task Create a simple physical model of a pendulum and animate it.
#ooRexx
ooRexx
  pendulum = .pendulum~new(10, 30)   before = .datetime~new do 100 -- somewhat arbitrary loop count call syssleep .2 now = .datetime~new pendulum~update(now - before) before = now say " X:" pendulum~x " Y:" pendulum~y end   ::class pendulum ::method init expose length theta x y velocity use arg le...
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 v...
#Elena
Elena
import system'routines; import extensions; import extensions'routines;   joinable(former,later) = (former[former.Length - 1] == later[0]);   dispatcher = new { eval(object a, Func2 f) { ^ f(a[0],a[1]) }   eval(object a, Func3 f) { ^ f(a[0], a[1],a[2]) }   eval(object a, Func4...
http://rosettacode.org/wiki/Active_Directory/Connect
Active Directory/Connect
The task is to establish a connection to an Active Directory or Lightweight Directory Access Protocol server.
#NetRexx
NetRexx
/* NetRexx */ options replace format comments java crossref symbols binary   import org.apache.directory.ldap.client.api.LdapConnection import org.apache.directory.ldap.client.api.LdapNetworkConnection import org.apache.directory.shared.ldap.model.exception.LdapException import org.slf4j.Logger import org.slf4j.LoggerF...
http://rosettacode.org/wiki/Active_Directory/Connect
Active Directory/Connect
The task is to establish a connection to an Active Directory or Lightweight Directory Access Protocol server.
#Perl
Perl
  use Net::LDAP;   my $ldap = Net::LDAP->new('ldap://ldap.example.com') or die $@; my $mesg = $ldap->bind( $bind_dn, password => $bind_pass );  
http://rosettacode.org/wiki/Align_columns
Align columns
Given a text file of many lines, where fields within a line are delineated by a single 'dollar' character, write a program that aligns each column of fields by ensuring that words in each column are separated by at least one space. Further, allow for each word in a column to be either left justified, right justified, o...
#360_Assembly
360 Assembly
* Align columns 12/04/2019 ALICOL CSECT USING ALICOL,R13 base register B 72(R15) skip savearea DC 17F'0' savearea SAVE (14,12) save previous context ST R13,4(R15) link backward ST...
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 sync...
#BBC_BASIC
BBC BASIC
INSTALL @lib$+"CLASSLIB" INSTALL @lib$+"TIMERLIB" INSTALL @lib$+"NOWAIT"   REM Integrator class: DIM integ{f$, t#, v#, tid%, @init, @@exit, input, output, tick} PROC_class(integ{})   REM Methods: DEF integ.@init integ.f$ = "0" : integ.tid% = FN_ontimer(10, PROC(integ.tick...
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 sync...
#C
C
#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <math.h> #include <sys/time.h> #include <pthread.h>   /* no need to lock the object: at worst the readout would be 1 tick off, which is no worse than integrator's inate inaccuracy */ typedef struct { double (*func)(double); struct timeval start; ...
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. Na...
#ALGOL_68
ALGOL 68
BEGIN # find Achilles Numbers: numbers whose prime factors p appear at least # # twice (i.e. if p is a prime factor, so is p^2) and cannot be # # expressed as m^k for any integer m, k > 1 # # also find strong Achilles Numbers: Achilles Numbers where the Euler's # ...
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 s...
#D
D
import std.stdio, std.range, std.algorithm, std.typecons, std.conv;   auto properDivisors(in ulong n) pure nothrow @safe /*@nogc*/ { return iota(1UL, (n + 1) / 2 + 1).filter!(x => n % x == 0 && n != x); }   enum pDivsSum = (in ulong n) pure nothrow @safe /*@nogc*/ => n.properDivisors.sum;   auto aliquot(in ulon...
http://rosettacode.org/wiki/Active_Directory/Search_for_a_user
Active Directory/Search for a user
Make sure you Connect to Active Directory
#REXX
REXX
/* Rexx */ do LDAP_URL = 'ldap://localhost:11389' LDAP_DN_STR = 'uid=admin,ou=system' LDAP_CREDS = '********' LDAP_BASE_DN = 'ou=users,o=mojo' LDAP_SCOPE = 'sub' LDAP_FILTER = '"(&(objectClass=person)(&(uid=*mil*)))"' LDAP_ATTRIBUTES = '"dn" "cn" "sn" "uid"'   ldapCommand = ...
http://rosettacode.org/wiki/Active_Directory/Search_for_a_user
Active Directory/Search for a user
Make sure you Connect to Active Directory
#Ruby
Ruby
require 'rubygems' require 'net/ldap'   ldap = Net::LDAP.new(:host => 'hostname', :base => 'base') ldap.authenticate('bind_dn', 'bind_pass')   filter = Net::LDAP::Filter.pres('objectclass') filter &= Net::LDAP::Filter.eq('sn','Jackman') # or filter = Net::LDAP::Filter.construct('(&(objectclass=*)(sn=Jackman))')   resul...
http://rosettacode.org/wiki/Active_Directory/Search_for_a_user
Active Directory/Search for a user
Make sure you Connect to Active Directory
#Run_BASIC
Run BASIC
This allows the client on the web to see their directory. The user can click on any file or directory and this will give them the following options: [upload] data from their computer to the server [delete] data from their directory [rename] files [view] image files
http://rosettacode.org/wiki/Active_Directory/Search_for_a_user
Active Directory/Search for a user
Make sure you Connect to Active Directory
#Scala
Scala
import org.apache.directory.api.ldap.model.message.SearchScope import org.apache.directory.ldap.client.api.{LdapConnection, LdapNetworkConnection}   object LdapSearchDemo extends App {   class LdapSearch {   def demonstrateSearch(): Unit = {   val conn = new LdapNetworkConnection("localhost", 11389) t...
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 re...
#Groovy
Groovy
class A { final x = { it + 25 } private map = new HashMap() Object get(String key) { map[key] } void set(String key, Object value) { map[key] = value } }
http://rosettacode.org/wiki/Add_a_variable_to_a_class_instance_at_runtime
Add a variable to a class instance at runtime
Demonstrate how to dynamically add variables to an object (a class instance) at runtime. This is useful when the methods/variables of an instance are based on a data file that isn't available until runtime. Hal Fulton gives an example of creating an OO CSV parser at An Exercise in Metaprogramming with Ruby. This is re...
#Icon_and_Unicon
Icon and Unicon
  link ximage   procedure main() c1 := foo(1,2) # instance of foo write("c1:\n",ximage(c1)) c1 := extend(c1,["c","d"],[8,9]) # 2 new fields write("new c1:\n",ximage(c1)) c1 := extend(c1,["e"],[7]) # 1 more write("newest c1:\n",ximage(c1)) end   cla...
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 |...
#IWBASIC
IWBASIC
  == Get ==   There are at least three ways to get the address of a variable in IWBASIC. The first is to use the address of operator:   DEF X:INT PRINT &X 'This will print in the console window (after OPENCONSOLE is issued.) 'To Print in an open window the appropriate Window variable is specified, e.g., PRINT Win,&X. ...
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 |...
#J
J
var =: 52 NB. Any variable (including data, functions, operators etc) var_addr =: 15!:6<'var' NB. Get address new_var =: 15!:7 var_addr NB. Set address
http://rosettacode.org/wiki/Address_of_a_variable
Address of a variable
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation |...
#Java
Java
julia> x = [1, 2, 3] julia> ptr = pointer_from_objref(x) Ptr{Void} @0x000000010282e4a0 julia> unsafe_pointer_to_objref(ptr) 3-element Array{Int64,1}: 1 2 3
http://rosettacode.org/wiki/Address_of_a_variable
Address of a variable
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation |...
#Julia
Julia
julia> x = [1, 2, 3] julia> ptr = pointer_from_objref(x) Ptr{Void} @0x000000010282e4a0 julia> unsafe_pointer_to_objref(ptr) 3-element Array{Int64,1}: 1 2 3
http://rosettacode.org/wiki/AKS_test_for_primes
AKS test for primes
The AKS algorithm for testing whether a number is prime is a polynomial-time algorithm based on an elementary theorem about Pascal triangles. The theorem on which the test is based can be stated as follows:   a number   p {\displaystyle p}   is prime   if and only if   all the coefficients of the polynomial ...
#C.2B.2B
C++
  #include <iomanip> #include <iostream> using namespace std;   const int pasTriMax = 61;   uint64_t pasTri[pasTriMax + 1];   void pascalTriangle(unsigned long n) // Calculate the n'th line 0.. middle { unsigned long j, k;   pasTri[0] = 1; j = 1; while (j <= n) { j++; k = j / 2; ...
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.   ...
#CLU
CLU
% Sieve of Erastothenes % Returns an array [1..max] marking the primes sieve = proc (max: int) returns (array[bool]) prime: array[bool] := array[bool]$fill(1, max, true) prime[1] := false   for p: int in int$from_to(2, max/2) do if prime[p] then for comp: int in int$from_to_by(p*2, max,...
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.   ...
#COBOL
COBOL
IDENTIFICATION DIVISION. PROGRAM-ID. ADDITIVE-PRIMES.   DATA DIVISION. WORKING-STORAGE SECTION. 01 VARIABLES. 03 MAXIMUM PIC 999. 03 AMOUNT PIC 999. 03 CANDIDATE PIC 999. 03 DIGIT PIC 9 OCCURS 3 TIMES...
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-bla...
#Picat
Picat
main => T = e, foreach (X in 1..10) insert(X,T,T1), T := T1 end, output(T,0).   insert(X,S,R) => ins(X,S,R1), R1 = $t(_,A,Y,B), R = $t(b,A,Y,B).   ins(X,e,R) => R = $t(r,e,X,e). ins(X,t(C,A,Y,B),R), X < Y => ins(X,A,Ao), balance(C,Ao,Y,B,R). ins(X,t(C,A,Y,B),R), X > Y => ins(...
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-bla...
#PicoLisp
PicoLisp
(be color (R)) (be color (B))   (be tree (@ E)) (be tree (@P (T @C @L @X @R)) (color @C) (tree @P @L) (call @P @X) (tree @P @R) )   (be bal (B (T R (T R @A @X @B) @Y @C) @Z @D (T R (T B @A @X @B) @Y (T B @C @Z @D)))) (be bal (B (T R @A @X (T R @B @Y @C)) @Z @D (T R (T B @A @X @B) @Y (T B @C @Z @D)))) (be ba...
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 {\displaystyl...
#FreeBASIC
FreeBASIC
' FB 1.05.0 Win64   Function kPrime(n As Integer, k As Integer) As Boolean Dim f As Integer = 0 For i As Integer = 2 To n While n Mod i = 0 If f = k Then Return false f += 1 n \= i Wend Next Return f = k End Function   Dim As Integer i, c, k For k = 1 To 5 Print "k = "; k; ...
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 ...
#Clojure
Clojure
(require '[clojure.java.io :as io])   (def groups (with-open [r (io/reader wordfile)] (group-by sort (line-seq r))))   (let [wordlists (sort-by (comp - count) (vals groups)) maxlength (count (first wordlists))] (doseq [wordlist (take-while #(= (count %) maxlength) wordlists)] (println wordlist))
http://rosettacode.org/wiki/Angle_difference_between_two_bearings
Angle difference between two bearings
Finding the angle between two bearings is often confusing.[1] Task Find the angle which is the result of the subtraction b2 - b1, where b1 and b2 are the bearings. Input bearings are expressed in the range   -180   to   +180   degrees. The  result  is also expressed in the range   -180   to   +180   degrees. ...
#OCaml
OCaml
let get_diff b1 b2 = let r = mod_float (b2 -. b1) 360.0 in if r < -180.0 then r +. 360.0 else if r >= 180.0 then r -. 360.0 else r   let () = print_endline "Input in -180 to +180 range"; Printf.printf " %g\n" (get_diff 20.0 45.0); Printf.printf " %g\n" (get_diff (-45.0) 45.0); Printf.printf " %g\n" ...
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 uni...
#PowerShell
PowerShell
function Test-Deranged ([string[]]$Strings) { $array1 = $Strings[0].ToCharArray()   for ($i = 1; $i -lt $Strings.Count; $i++) { $array2 = $Strings[$i].ToCharArray()   for ($i = 0; $i -lt $array1.Count; $i++) { if ($array1[$i] -match $array2[$i]) { ...
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 f...
#Mathematica_.2F_Wolfram_Language
Mathematica / Wolfram Language
check := #<0& fib := If[check[#],Throw["Negative Argument"],If[#<=1,1,#0[#-2]+#0[#-1]]&[#]]& fib /@ Range[0,10]   {1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89}
http://rosettacode.org/wiki/Amicable_pairs
Amicable pairs
Two integers N {\displaystyle N} and M {\displaystyle M} are said to be amicable pairs if N ≠ M {\displaystyle N\neq M} and the sum of the proper divisors of N {\displaystyle N} ( s u m ( p r o p D i v s ( N ) ) {\displaystyle \mathrm {sum} (\mathrm {propDivs} (N))} ) = M ...
#Kotlin
Kotlin
// version 1.1   fun sumProperDivisors(n: Int): Int { if (n < 2) return 0 return (1..n / 2).filter{ (n % it) == 0 }.sum() }   fun main(args: Array<String>) { val sum = IntArray(20000, { sumProperDivisors(it) } ) println("The pairs of amicable numbers below 20,000 are:\n") for(n in 2..19998) { ...
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 Creat...
#Standard_ML
Standard ML
open XWindows ; open Motif ;   structure TTd = Thread.Thread ; structure TTm = Thread.Mutex ;   val bannerWindow = fn () =>   let datatype thron = nothr | thr of TTd.thread ; val toThr = fn thr x=> x; val on = ref nothr ; val mx = TTm.mutex (); val dim = {tw=77,th=14} ; val shell = XtAp...
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 Creat...
#Suneido
Suneido
Window(Controller { Xmin: 50 Ymin: 50 New() { super(.layout()) .txt = .FindControl('text') .moveTimer = SetTimer(NULL, 0, 600, .moveTimerFunc) } direction: -1 moveTimer: false layout() { return #(Vert (Static 'Hello World! ', size: 12, ...
http://rosettacode.org/wiki/Animate_a_pendulum
Animate a pendulum
One good way of making an animation is by simulating a physical system and illustrating the variables in that system using a dynamically changing graphical display. The classic such physical system is a simple gravity pendulum. Task Create a simple physical model of a pendulum and animate it.
#Oz
Oz
declare [QTk] = {Link ['x-oz://system/wp/QTk.ozf']}   Pi = 3.14159265   class PendulumModel feat K attr angle velocity   meth init(length:L <= 1.0 %% meters gravity:G <= 9.81 %% m/s² initialAngle:A <= Pi/2.) %% radians self.K = ~G / L angle := A velocity := 0.0...
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 v...
#ERRE
ERRE
  PROGRAM AMB   ! ! for rosettacode.org !   !$KEY   DIM SET1$[2],SET2$[2],SET3$[2],SET4$[2]   FUNCTION WORDS_OK(STRING1$,STRING2$) WORDS_OK=(RIGHT$(STRING1$,1)=LEFT$(STRING2$,1)) END FUNCTION   PROCEDURE AMB(SET1$[],SET2$[],SET3$[],SET4$[]->RESULT$) RESULT$="" ! Empty string, e.g. fail FOR A=0 TO 2 DO FOR B=0...
http://rosettacode.org/wiki/Active_Directory/Connect
Active Directory/Connect
The task is to establish a connection to an Active Directory or Lightweight Directory Access Protocol server.
#Phix
Phix
include builtins/ldap.e constant servers = { "ldap.somewhere.com", } --... string name="name", password="passwd" --... for i=1 to length(servers) do atom ld = ldap_init(servers[i]) integer res = ldap_simple_bind_s(ld, name, password) printf(1,"%s: %d [%s]\n",{servers[i],res,ldap_err_desc(res)}) --... ...
http://rosettacode.org/wiki/Active_Directory/Connect
Active Directory/Connect
The task is to establish a connection to an Active Directory or Lightweight Directory Access Protocol server.
#PHP
PHP
<?php $ldap = ldap_connect($hostname, $port); $success = ldap_bind($ldap, $username, $password);
http://rosettacode.org/wiki/Active_Directory/Connect
Active Directory/Connect
The task is to establish a connection to an Active Directory or Lightweight Directory Access Protocol server.
#PicoLisp
PicoLisp
(unless (=0 (setq Ldap (native "libldap.so" "ldap_open" 'N "example.com" 389))) (quit "Can't open LDAP") )   (native "libldap.so" "ldap_simple_bind_s" 'I Ldap "user" "password")
http://rosettacode.org/wiki/Active_Directory/Connect
Active Directory/Connect
The task is to establish a connection to an Active Directory or Lightweight Directory Access Protocol server.
#Python
Python
import ldap   l = ldap.initialize("ldap://ldap.example.com") try: l.protocol_version = ldap.VERSION3 l.set_option(ldap.OPT_REFERRALS, 0)   bind = l.simple_bind_s("me@example.com", "password") finally: l.unbind()  
http://rosettacode.org/wiki/Accumulator_factory
Accumulator factory
A problem posed by Paul Graham is that of creating a function that takes a single (numeric) argument and which returns another function that is an accumulator. The returned accumulator function in turn also takes a single numeric argument, and returns the sum of all the numeric values passed in so far to that accumulat...
#11l
11l
F accumulator(n) T Accumulator Float s F (Float n) .s = n F ()(Float n) .s += n R .s R Accumulator(n)   V x = accumulator(1) print(x(5)) print(x(2.3))   V x2 = accumulator(3) print(x2(5)) print(x2(3.3)) print(x2(0))
http://rosettacode.org/wiki/Align_columns
Align columns
Given a text file of many lines, where fields within a line are delineated by a single 'dollar' character, write a program that aligns each column of fields by ensuring that words in each column are separated by at least one space. Further, allow for each word in a column to be either left justified, right justified, o...
#8th
8th
  quote | Given$a$text$file$of$many$lines,$where$fields$within$a$line$ are$delineated$by$a$single$'dollar'$character,$write$a$program that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$ column$are$separated$by$at$least$one$space. Further,$allow$for$each$word$in$a$column$to$be$either$left$ justified,$right...
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 sync...
#C.23
C#
using System; using System.Threading.Tasks;   using static System.Diagnostics.Stopwatch; using static System.Math; using static System.Threading.Thread;   class ActiveObject { static double timeScale = 1.0 / Frequency;   Func<double, double> func; Task updateTask; double integral; double value; ...
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. Na...
#ARM_Assembly
ARM Assembly
  /* ARM assembly Raspberry PI */ /* program achilleNumber.s */   /* REMARK 1 : this program use routines in a include file see task Include a file language arm assembly for the routine affichageMess conversion10 see at end of this program the instruction include */ /* for constantes see task include a...
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 s...
#EchoLisp
EchoLisp
  ;; implementation of Floyd algorithm to find cycles in a graph ;; see Wikipedia https://en.wikipedia.org/wiki/Cycle_detection ;; returns (cycle-length cycle-starter steps) ;; steps = 0 if no cycle found ;; it's all about a tortoise 🐢 running at speed f(x) after a hare 🐰 at speed f(f (x)) ;; when they meet, a cycle...
http://rosettacode.org/wiki/Active_Directory/Search_for_a_user
Active Directory/Search for a user
Make sure you Connect to Active Directory
#Tcl
Tcl
set Username "TestUser" set Filter "((&objectClass=*)(sAMAccountName=$Username))" set Base "dc=skycityauckland,dc=sceg,dc=com" set Attrs distinguishedName
http://rosettacode.org/wiki/Active_Directory/Search_for_a_user
Active Directory/Search for a user
Make sure you Connect to Active Directory
#UNIX_Shell
UNIX Shell
#!/bin/sh   LDAP_HOST="localhost" LDAP_PORT=11389 LDAP_DN_STR="uid=admin,ou=system" LDAP_CREDS="********" LDAP_BASE_DN="ou=users,o=mojo" LDAP_SCOPE="sub" LDAP_FILTER="(&(objectClass=person)(&(uid=*mil*)))" LDAP_ATTRIBUTES="dn cn sn uid"   ldapsearch \ -s base \ -h $LDAP_HOST \ -p $LDAP_PORT \ -LLL \ -x \ -v...
http://rosettacode.org/wiki/Active_Directory/Search_for_a_user
Active Directory/Search for a user
Make sure you Connect to Active Directory
#VBScript
VBScript
strUsername = "TestUser" strQuery = "<LDAP://dc=skycityauckland,dc=sceg,dc=com>;"_ & "(&(objectclass=*)(samaccountname=" & strUsername & "));distinguishedname;subtree" objCmd.ActiveConnection = objConn objCmd.Properties("Page Size")=100 objCmd.CommandText = strQuery Set objRS = objCmd.Execute
http://rosettacode.org/wiki/Active_Directory/Search_for_a_user
Active Directory/Search for a user
Make sure you Connect to Active Directory
#Wren
Wren
/* active_directory_search_for_user.wren */   var LDAP_SCOPE_SUBTREE = 0x0002   foreign class LDAPMessage { construct new() {}   foreign msgfree() }   foreign class LDAP { construct init(host, port) {}   foreign simpleBindS(name, password)   foreign searchS(base, scope, filter, attrs, attrsOnly, res...
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 re...
#Io
Io
Empty := Object clone   e := Empty clone e foo := 1
http://rosettacode.org/wiki/Add_a_variable_to_a_class_instance_at_runtime
Add a variable to a class instance at runtime
Demonstrate how to dynamically add variables to an object (a class instance) at runtime. This is useful when the methods/variables of an instance are based on a data file that isn't available until runtime. Hal Fulton gives an example of creating an OO CSV parser at An Exercise in Metaprogramming with Ruby. This is re...
#J
J
C=:<'exampleclass' NB. this will be our class name V__C=: 0 NB. ensure the class exists OBJ1=:conew 'exampleclass' NB. create an instance of our class OBJ2=:conew 'exampleclass' NB. create another instance V__OBJ1,V__OBJ2 NB. both of our instances exist 0 W__OBJ1 ...
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 re...
#JavaScript
JavaScript
e = {} // generic object e.foo = 1 e["bar"] = 2 // name specified at runtime
http://rosettacode.org/wiki/Add_a_variable_to_a_class_instance_at_runtime
Add a variable to a class instance at runtime
Demonstrate how to dynamically add variables to an object (a class instance) at runtime. This is useful when the methods/variables of an instance are based on a data file that isn't available until runtime. Hal Fulton gives an example of creating an OO CSV parser at An Exercise in Metaprogramming with Ruby. This is re...
#jq
jq
{"a":1} as $a | ($a + {"b":2}) as $a | $a  
http://rosettacode.org/wiki/Address_of_a_variable
Address of a variable
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation |...
#Kotlin
Kotlin
// Kotlin Native v0.5   import kotlinx.cinterop.*   fun main(args: Array<String>) { val intVar = nativeHeap.alloc<IntVar>() intVar.value = 42 with(intVar) { println("Value is $value, address is $rawPtr") } nativeHeap.free(intVar) }
http://rosettacode.org/wiki/Address_of_a_variable
Address of a variable
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation |...
#Lambdatalk
Lambdatalk
    1) lambdas   {lambda {:x} {* :x :x}} -> _LAMB_123   2) arrays   '{A.new hello world} // defining an array -> _ARRA_123 // as replaced and used before post-processing -> [hello,world] // if unused after post-processing   3) pairs   {pre '{P.new hello world} // defining a pair -> _PAIR_123 //...
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 ...
#Clojure
Clojure
(defn c "kth coefficient of (x - 1)^n" [n k] (/ (apply *' (range n (- n k) -1)) (apply *' (range k 0 -1)) (if (and (even? k) (< k n)) -1 1)))   (defn cs "coefficient series for (x - 1)^n, k=[0..n]" [n] (map #(c n %) (range (inc n))))   (defn aks? [p] (->> (cs p) rest butlast (every? #(-> % (m...
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.   ...
#Common_Lisp
Common Lisp
  (defun sum-of-digits (n) "Return the sum of the digits of a number" (do* ((sum 0 (+ sum rem)) rem ) ((zerop n) sum) (multiple-value-setq (n rem) (floor n 10)) ))   (defun additive-primep (n) (and (primep n) (primep (sum-of-digits n))) )     ; To test if a number is prime we can use a number of...
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.   ...
#Crystal
Crystal
# Fast/simple way to generate primes for small values. # Uses P3 Prime Generator (PG) and its Prime Generator Sequence (PGS).   def prime?(n) # P3 Prime Generator primality test return false unless (n | 1 == 3 if n < 5) || (n % 6) | 4 == 5 sqrt_n = Math.isqrt(n) # For Crystal < 1.2.0 use Math.sqrt(n).to_i pc = t...
http://rosettacode.org/wiki/Algebraic_data_types
Algebraic data types
Some languages offer direct support for algebraic data types and pattern matching on them. While this of course can always be simulated with manual tagging and conditionals, it allows for terse code which is easy to read, and can represent the algorithm directly. Task As an example, implement insertion in a red-bla...
#Prolog
Prolog
color(r). color(b). tree(_,e). tree(P,t(C,L,X,R)) :- color(C), tree(P,L), call(P,X), tree(P,R). bal(b, t(r,t(r,A,X,B),Y,C), Z, D, t(r,t(b,A,X,B),Y,t(b,C,Z,D))). bal(b, t(r,A,X,t(r,B,Y,C)), Z, D, t(r,t(b,A,X,B),Y,t(b,C,Z,D))). bal(b, A, X, t(r,t(r,B,Y,C),Z,D), t(r,t(b,A,X,B),Y,t(b,C,Z,D))). bal(b, A, X, t(r,B,Y,t(r,C,...
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-bla...
#Python
Python
from __future__ import annotations from enum import Enum from typing import NamedTuple from typing import Optional     class Color(Enum): B = 0 R = 1     class Tree(NamedTuple): color: Color left: Optional[Tree] value: int right: Optional[Tree]   def insert(self, val: int) -> Tree: r...
http://rosettacode.org/wiki/Almost_prime
Almost prime
A   k-Almost-prime   is a natural number   n {\displaystyle n}   that is the product of   k {\displaystyle k}   (possibly identical) primes. Example 1-almost-primes,   where   k = 1 {\displaystyle k=1} ,   are the prime numbers themselves. 2-almost-primes,   where   k = 2 {\displaystyl...
#Frink
Frink
for k = 1 to 5 { n=2 count = 0 print["k=$k:"] do { if length[factorFlat[n]] == k { print[" $n"] count = count + 1 } n = n + 1 } while count < 10   println[] }
http://rosettacode.org/wiki/Almost_prime
Almost prime
A   k-Almost-prime   is a natural number   n {\displaystyle n}   that is the product of   k {\displaystyle k}   (possibly identical) primes. Example 1-almost-primes,   where   k = 1 {\displaystyle k=1} ,   are the prime numbers themselves. 2-almost-primes,   where   k = 2 {\displaystyl...
#Futhark
Futhark
  let kprime(n: i32, k: i32): bool = let (p,f) = (2, 0) let (n,_,f) = loop (n, p, f) while f < k && p*p <= n do let (n,f) = loop (n, f) while 0 == n % p do (n/p, f+1) in (n, p+1, f) in f + (if n > 1 then 1 else 0) == k   let main(m: i32): [][]i32 = let f k = let ps = replicate 10 0 let (_,...
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 ...
#CLU
CLU
% Keep a list of anagrams anagrams = cluster is new, add, largest_size, sets anagram_set = struct[letters: string, words: array[string]] rep = array[anagram_set]   new = proc () returns (cvt) return(rep$[]) end new    % Sort the letters in a string sort = proc (s: string) returns (string)...
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. ...
#PARI.2FGP
PARI/GP
centerliftmod1(x)=frac(x+1/2)-1/2; anglediff(x,y)=centerliftmod1((y-x)/360)*360; vecFunc(f)=v->call(f,v); apply(vecFunc(anglediff), [[20,45], [-45,45], [-85,90], [-95,90], [-45,125], [-45,145], [29.4803,-88.6381], [-78.3251,-159.036], [-70099.74233810938,29840.67437876723], [-165313.6666297357,33693.9894517456], [1174....
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 uni...
#Prolog
Prolog
longest_deranged_anagram :- http_open('http://www.puzzlers.org/pub/wordlists/unixdict.txt',In,[]), read_file(In, [], Out), close(In), msort(Out, MOut), group_pairs_by_key(MOut, GPL), map_list_to_pairs(compute_len, GPL, NGPL), predsort(my_compare, NGPL, GPLSort), search_derangement(GPLSort).     % order tuples t...
http://rosettacode.org/wiki/Anonymous_recursion
Anonymous recursion
While implementing a recursive function, it often happens that we must resort to a separate   helper function   to handle the actual recursion. This is usually the case when directly calling the current function would waste too many resources (stack space, execution time), causing unwanted side-effects,   and/or the f...
#MATLAB
MATLAB
  function v = fibonacci(n) assert(n >= 0) v = fibonacci(n,0,1);   % nested function function a = fibonacci(n,a,b) if n ~= 0 a = fibonacci(n-1,b,a+b); end end end  
http://rosettacode.org/wiki/Amicable_pairs
Amicable pairs
Two integers N {\displaystyle N} and M {\displaystyle M} are said to be amicable pairs if N ≠ M {\displaystyle N\neq M} and the sum of the proper divisors of N {\displaystyle N} ( s u m ( p r o p D i v s ( N ) ) {\displaystyle \mathrm {sum} (\mathrm {propDivs} (N))} ) = M ...
#Lua
Lua
function sumDivs (n) local sum = 1 for d = 2, math.sqrt(n) do if n % d == 0 then sum = sum + d sum = sum + n / d end end return sum end   for n = 2, 20000 do m = sumDivs(n) if m > n then if sumDivs(m) == n then print(n, m) end end end
http://rosettacode.org/wiki/Animation
Animation
Animation is integral to many parts of GUIs, including both the fancy effects when things change used in window managers, and of course games.   The core of any animation system is a scheme for periodically changing the display while still remaining responsive to the user.   This task demonstrates this. Task Creat...
#SVG
SVG
<svg xmlns="http://www.w3.org/2000/svg" width="100" height="30"> <g id="all"> <rect width="100%" height="100%" fill="yellow"/> <g style="font: 18 'Times New Roman', serif; fill: black; stroke: white; stroke-width: 0.001; /* workaround for Batik oddity */ "> ...
http://rosettacode.org/wiki/Animate_a_pendulum
Animate a pendulum
One good way of making an animation is by simulating a physical system and illustrating the variables in that system using a dynamically changing graphical display. The classic such physical system is a simple gravity pendulum. Task Create a simple physical model of a pendulum and animate it.
#Perl
Perl
  use strict; use warnings; use Tk; use Math::Trig qw/:pi/;   my $root = new MainWindow( -title => 'Pendulum Animation' ); my $canvas = $root->Canvas(-width => 320, -height => 200); my $after_id;   for ($canvas) { $_->createLine( 0, 25, 320, 25, -tags => [qw/plate/], -width => 2, -fill => 'grey50' ); $_->create...
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 v...
#F.23
F#
// define the List "workflow" (monad) type ListBuilder() = member o.Bind( lst, f ) = List.concat( List.map (fun x -> f x) lst ) member o.Return( x ) = [x] member o.Zero() = []   let list = ListBuilder()   let amb = id   // last element of a sequence let last s = Seq.nth ((Seq.length s) - 1) s   // is the last ...
http://rosettacode.org/wiki/Active_Directory/Connect
Active Directory/Connect
The task is to establish a connection to an Active Directory or Lightweight Directory Access Protocol server.
#Racket
Racket
#lang racket (require net/ldap) (ldap-authenticate "ldap.somewhere.com" 389 "uid=username,ou=people,dc=somewhere,dc=com" password)
http://rosettacode.org/wiki/Active_Directory/Connect
Active Directory/Connect
The task is to establish a connection to an Active Directory or Lightweight Directory Access Protocol server.
#Raku
Raku
use LMDB;   my %DB := LMDB::DB.open(:path<some-dir>, %connection-parameters);  
http://rosettacode.org/wiki/Active_Directory/Connect
Active Directory/Connect
The task is to establish a connection to an Active Directory or Lightweight Directory Access Protocol server.
#Ruby
Ruby
require 'rubygems' require 'net/ldap' ldap = Net::LDAP.new(:host => 'ldap.example.com', :base => 'o=companyname') ldap.authenticate('bind_dn', 'bind_pass')
http://rosettacode.org/wiki/Active_Directory/Connect
Active Directory/Connect
The task is to establish a connection to an Active Directory or Lightweight Directory Access Protocol server.
#Run_BASIC
Run BASIC
print shell$("dir") ' shell out to the os and print it
http://rosettacode.org/wiki/Active_Directory/Connect
Active Directory/Connect
The task is to establish a connection to an Active Directory or Lightweight Directory Access Protocol server.
#Rust
Rust
  let conn = ldap3::LdapConn::new("ldap://ldap.example.com")?; conn.simple_bind("bind_dn", "bind_pass")?.success()?;  
http://rosettacode.org/wiki/Active_Directory/Connect
Active Directory/Connect
The task is to establish a connection to an Active Directory or Lightweight Directory Access Protocol server.
#Scala
Scala
import java.io.IOException   import org.apache.directory.api.ldap.model.exception.LdapException import org.apache.directory.ldap.client.api.{LdapConnection, LdapNetworkConnection}   object LdapConnectionDemo { @throws[LdapException] @throws[IOException] def main(args: Array[String]): Unit = { try { val ...
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 accumulat...
#8th
8th
  \ RossetaCode 'accumulator factory'   \ The 'accumulate' word stores the accumulated value in an array, because arrays \ are mutable: : accumulate \ n [m] -- n+m \ [m] -> [n+m] a:pop rot n:+ tuck a:push swap ;   \ To comply with the rules, this takes a number and wraps it in an array, and \ then curries it. Sinc...
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 accumulat...
#ABAP
ABAP
report z_accumulator class acc definition. public section. methods: call importing iv_i type any default 0 exporting ev_r type any, constructor importing iv_d type f. private section. data a_sum type f. endclass.   class acc implementation. method call. add iv_i to a_sum. ev_r = a_...
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, o...
#AArch64_Assembly
AArch64 Assembly
  /* ARM assembly AARCH64 Raspberry PI 3B or android 64 bits */ /* program alignColumn64.s */   /*******************************************/ /* Constantes file */ /*******************************************/ /* for this file see task include a file in language AArch64 assembly*/ .include ...
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 sync...
#C.2B.2B
C++
#include <atomic> #include <chrono> #include <cmath> #include <iostream> #include <mutex> #include <thread>   using namespace std::chrono_literals;   class Integrator { public: using clock_type = std::chrono::high_resolution_clock; using dur_t = std::chrono::duration<double>; using func_t = doubl...
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. Na...
#C.2B.2B
C++
#include <algorithm> #include <chrono> #include <cmath> #include <cstdint> #include <iomanip> #include <iostream> #include <vector>   #include <boost/multiprecision/cpp_int.hpp>   using boost::multiprecision::uint128_t;   template <typename T> void unique_sort(std::vector<T>& vector) { std::sort(vector.begin(), vec...
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 s...
#Elixir
Elixir
defmodule Proper do def divisors(1), do: [] def divisors(n), do: [1 | divisors(2,n,:math.sqrt(n))] |> Enum.sort   defp divisors(k,_n,q) when k>q, do: [] defp divisors(k,n,q) when rem(n,k)>0, do: divisors(k+1,n,q) defp divisors(k,n,q) when k * k == n, do: [k | divisors(k+1,n,q)] defp divisors(k,n,q) ...
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 re...
#Julia
Julia
  {"phoneNumbers": [ { "type": "home", "number": "212 555-1234" }, { "type": "office", "number": "646 555-4567" }, { "type": "mobile", "number": "123 456-7890" }]}  
http://rosettacode.org/wiki/Add_a_variable_to_a_class_instance_at_runtime
Add a variable to a class instance at runtime
Demonstrate how to dynamically add variables to an object (a class instance) at runtime. This is useful when the methods/variables of an instance are based on a data file that isn't available until runtime. Hal Fulton gives an example of creating an OO CSV parser at An Exercise in Metaprogramming with Ruby. This is re...
#Kotlin
Kotlin
// version 1.1.2   class SomeClass { val runtimeVariables = mutableMapOf<String, Any>() }   fun main(args: Array<String>) { val sc = SomeClass() println("Create two variables at runtime: ") for (i in 1..2) { println(" Variable #$i:") print(" Enter name  : ") val name = rea...
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 re...
#Latitude
Latitude
myObject := Object clone.   ;; Name known at compile-time. myObject foo := "bar".   ;; Name known at runtime. myObject slot 'foo = "bar".
http://rosettacode.org/wiki/Address_of_a_variable
Address of a variable
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation |...
#Lua
Lua
t = {} print(t) f = function() end print(f) c = coroutine.create(function() end) print(c) u = io.open("/dev/null","w") print(u) print(_G, _ENV) -- global/local environments (are same here) print(string.format("%p %p %p", print, string, string.format)) -- themselves formatted as pointers
http://rosettacode.org/wiki/Address_of_a_variable
Address of a variable
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation |...
#Maple
Maple
> addressof( x ); 18446884674469911422
http://rosettacode.org/wiki/Address_of_a_variable
Address of a variable
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation |...
#Modula-2
Modula-2
MODULE GetAddress;   FROM SYSTEM IMPORT ADR; FROM InOut IMPORT WriteInt, WriteLn;   VAR var : INTEGER; adr : LONGINT; BEGIN adr := ADR(var); (*get the address*) WriteInt(adr, 0); WriteLn; END GetAddress.
http://rosettacode.org/wiki/AKS_test_for_primes
AKS test for primes
The AKS algorithm for testing whether a number is prime is a polynomial-time algorithm based on an elementary theorem about Pascal triangles. The theorem on which the test is based can be stated as follows:   a number   p {\displaystyle p}   is prime   if and only if   all the coefficients of the polynomial ...
#CoffeeScript
CoffeeScript
pascal = () -> a = [] return () -> if a.length is 0 then a = [1] else b = (a[i] + a[i+1] for i in [0 ... a.length - 1]) a = [1].concat(b).concat [1]   show = (a) -> show_x = (e) -> switch e when 0 then "" when 1 then "x" els...
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.   ...
#Delphi
Delphi
proc sieve([*] bool prime) void: word max, p, c; max := dim(prime,1)-1; prime[0] := false; prime[1] := false; for p from 2 upto max do prime[p] := true od; for p from 2 upto max/2 do for c from p*2 by p upto max do prime[c] := false od od corp   proc digit_sum(wor...
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.   ...
#Draco
Draco
proc sieve([*] bool prime) void: word max, p, c; max := dim(prime,1)-1; prime[0] := false; prime[1] := false; for p from 2 upto max do prime[p] := true od; for p from 2 upto max/2 do for c from p*2 by p upto max do prime[c] := false od od corp   proc digit_sum(wor...
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-bla...
#Racket
Racket
  #lang racket   ;; Using short names to make the code line up nicely (struct N (color left value right) #:prefab)   (define (balance t) (match t [(N 'B (N 'R (N 'R a x b) y c) z d) (N 'R (N 'B a x b) y (N 'B c z d))] [(N 'B (N 'R a x (N 'R b y c)) z d) (N 'R (N 'B a x b) y (N 'B c z d))] [(N 'B a x (N 'R...
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-bla...
#Raku
Raku
enum RedBlack <R B>;   multi balance(B,[R,[R,$a,$x,$b],$y,$c],$z,$d) { [R,[B,$a,$x,$b],$y,[B,$c,$z,$d]] } multi balance(B,[R,$a,$x,[R,$b,$y,$c]],$z,$d) { [R,[B,$a,$x,$b],$y,[B,$c,$z,$d]] } multi balance(B,$a,$x,[R,[R,$b,$y,$c],$z,$d]) { [R,[B,$a,$x,$b],$y,[B,$c,$z,$d]] } multi balance(B,$a,$x,[R,$b,$y,[R,$c,$z,$d]]) { ...
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 {\displaystyl...
#Go
Go
package main   import "fmt"   func kPrime(n, k int) bool { nf := 0 for i := 2; i <= n; i++ { for n%i == 0 { if nf == k { return false } nf++ n /= i } } return nf == k }   func gen(k, n int) []int { r := make([]int, n) ...
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 ...
#COBOL
COBOL
*> TECTONICS *> wget http://wiki.puzzlers.org/pub/wordlists/unixdict.txt *> or visit https://sourceforge.net/projects/souptonuts/files *> or snag ftp://ftp.openwall.com/pub/wordlists/all.gz *> for a 5 million all language word file (a few phrases) *> cobc -xj anagrams.co...
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. ...
#Pascal
Pascal
  Program Bearings; { Reads pairs of angles from a file and subtracts them }   Const fileName = 'angles.txt';   Type degrees = real;   Var subtrahend, minuend: degrees; angleFile: text;   function Simplify(angle: degrees): degrees; { Returns an number in the range [-180.0, 180.0] } begin while angle > 180...
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 uni...
#PureBasic
PureBasic
Structure anagram word.s letters.s EndStructure   Structure wordList List words.anagram() EndStructure   #True = 1 #False = 0   Procedure.s sortLetters(*word.Character, wordLength) ;returns a string with the letters of a word sorted Protected Dim letters.c(wordLength) Protected *letAdr = @letters() CopyM...
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 f...
#Nemerle
Nemerle
using System; using System.Console;   module Fib { Fib(n : long) : long { def fib(m : long) { |0 => 1 |1 => 1 |_ => fib(m - 1) + fib(m - 2) }   match(n) { |n when (n < 0) => throw ArgumentException("Fib() not defined on nega...
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 ...
#MAD
MAD
NORMAL MODE IS INTEGER DIMENSION DIVS(20000) PRINT COMMENT $ AMICABLE PAIRS$   R CALCULATE SUM OF DIVISORS OF N INTERNAL FUNCTION(N) ENTRY TO DIVSUM. DS = 0 THROUGH SUMMAT, FOR DIVC=1, 1, DIVC.GE.N SUMMAT WHENEVER N/DIVC*...
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 Creat...
#Tcl
Tcl
package require Tk set s "Hello World! " set dir 0 # Periodic animation callback proc animate {} { global dir s if {$dir} { set s [string range $s 1 end][string index $s 0] } else { set s [string index $s end][string range $s 0 end-1] } # We will run this code ~8 times a second (== 1...