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/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...
#BBC_BASIC
BBC BASIC
INSTALL @lib$+"CLASSLIB"   REM Create a base class with no members: DIM class{method} PROC_class(class{})   REM Instantiate the class: PROC_new(myobject{}, class{})   REM Add a member at run-time: member$ = "mymember#" PROCaddmember(myobject{}, member$, 8)   R...
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...
#Bracmat
Bracmat
( ( struktuur = (aMember=) (aMethod=.!(its.aMember)) ) & new$struktuur:?object & out$"Object as originally created:" & lst$object & A value:?(object..aMember) & !object:(=?originalMembersAndMethods) & new $ ( ' ( (anotherMember=) (anotherMethod=.!(its.anotherMember)) ()$originalMe...
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...
#C.23
C#
// ---------------------------------------------------------------------------------------------- // // Program.cs - DynamicClassVariable // // Mikko Puonti, 2013 // // ----------------------------------------------------------------------------------------------   using System; using System.Dynamic;   namesp...
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 |...
#Creative_Basic
Creative Basic
  == Get ==   To get the address of a variable without using the Windows API:   DEF X:INT DEF pPointer:POINTER pPointer=X   ----   To get the address of a variable using the Windows API Lstrcpy function called in Creative Basic: (This may give users of another language without a native way to get the address of a varia...
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 |...
#D
D
int i; int* ip = &i;
http://rosettacode.org/wiki/Address_of_a_variable
Address of a variable
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation |...
#Delphi
Delphi
var i: integer; p: ^integer; begin p := @i; writeLn(p^); 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 ...
#AutoHotkey
AutoHotkey
; 1. Create a function/subroutine/method that given p generates the coefficients of the expanded polynomial representation of (x-1)^p. ; Function modified from http://rosettacode.org/wiki/Pascal%27s_triangle#AutoHotkey pascalstriangle(n=8) ; n rows of Pascal's triangle { p := Object(), z:=Object() Loop, % n Loop, ...
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.   ...
#Arturo
Arturo
additives: select 2..500 'x -> and? prime? x prime? sum digits x   loop split.every:10 additives 'a -> print map a => [pad to :string & 4]   print ["\nFound" size additives "additive primes up to 500"]
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.   ...
#AWK
AWK
  # syntax: GAWK -f ADDITIVE_PRIMES.AWK BEGIN { start = 1 stop = 500 for (i=start; i<=stop; i++) { if (is_prime(i) && is_prime(sum_digits(i))) { printf("%4d%1s",i,++count%10?"":"\n") } } printf("\nAdditive primes %d-%d: %d\n",start,stop,count) exit(0) } function is_prime(x, ...
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...
#Nim
Nim
import fusion/matching {.experimental: "caseStmtMacros".}   type Colour = enum Empty, Red, Black RBTree[T] = ref object colour: Colour left, right: RBTree[T] value: T   proc `[]`[T](r: RBTree[T], idx: static[FieldIndex]): auto = ## enables tuple syntax for unpacking and matching when idx == 0: r.col...
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...
#OCaml
OCaml
  type color = R | B type 'a tree = E | T of color * 'a tree * 'a * 'a tree   (** val balance : color * 'a tree * 'a * 'a tree -> 'a tree *) let balance = function | B, T (R, T (R,a,x,b), y, c), z, d | B, T (R, a, x, T (R,b,y,c)), z, d | B, a, x, T (R, T (R,b,y,c), z, d) | B, a, x, T (R, b, y, T (R,c,z,d)) -> T...
http://rosettacode.org/wiki/Almost_prime
Almost prime
A   k-Almost-prime   is a natural number   n {\displaystyle n}   that is the product of   k {\displaystyle k}   (possibly identical) primes. Example 1-almost-primes,   where   k = 1 {\displaystyle k=1} ,   are the prime numbers themselves. 2-almost-primes,   where   k = 2 {\displaystyl...
#Elixir
Elixir
defmodule Factors do def factors(n), do: factors(n,2,[])   defp factors(1,_,acc), do: acc defp factors(n,k,acc) when rem(n,k)==0, do: factors(div(n,k),k,[k|acc]) defp factors(n,k,acc) , do: factors(n,k+1,acc)   def kfactors(n,k), do: kfactors(n,k,1,1,[])   defp kfactors(_tn,tk,_n,k,_acc) whe...
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...
#Erlang
Erlang
  -module(factors). -export([factors/1,kfactors/0,kfactors/2]).   factors(N) -> factors(N,2,[]).   factors(1,_,Acc) -> Acc; factors(N,K,Acc) wh...
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 ...
#Bracmat
Bracmat
( get$("unixdict.txt",STR):?list & 1:?product & whl ' ( @(!list:(%?word:?w) \n ?list) & :?sum & whl ' ( @(!w:%?let ?w) & (!let:~#|str$(N !let))+!sum:?sum ) & !sum^!word*!product:?product ) & lst$(product,"product.txt",NEW) & 0:?max & :?group & (  !product  :  ? * ?...
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. ...
#Modula-2
Modula-2
FROM Terminal IMPORT *;   PROCEDURE WriteRealLn(value : REAL); VAR str : ARRAY[0..16] OF CHAR; BEGIN RealToStr(value, str); WriteString(str); WriteLn; END WriteRealLn;   PROCEDURE AngleDifference(b1, b2 : REAL) : REAL; VAR r : REAL; BEGIN r := (b2 - b1); WHILE r < -180.0 DO r := r + 360.0; ...
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...
#Phixmonti
Phixmonti
/# Rosetta Code problem: http://rosettacode.org/wiki/Anagrams/Deranged_anagrams by Galileo, 06/2022 #/   include ..\Utilitys.pmt   "unixdict.txt" "r" fopen var f   ( )   true while f fgets dup -1 == if drop f fclose false else -1 del dup sort swap 2 tolist 0 ...
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...
#LOLCODE
LOLCODE
HAI 1.3   HOW IZ I fib YR x DIFFRINT x AN BIGGR OF x AN 0, O RLY? YA RLY, FOUND YR "ERROR" OIC   HOW IZ I fib_i YR n DIFFRINT n AN BIGGR OF n AN 2, O RLY? YA RLY, FOUND YR n OIC   FOUND YR SUM OF... I IZ fib_i YR DIFF OF n AN 2 MKAY AN... I IZ fib_...
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 ...
#JavaScript
JavaScript
(function (max) {   // Proper divisors function properDivisors(n) { if (n < 2) return []; else { var rRoot = Math.sqrt(n), intRoot = Math.floor(rRoot),   lows = range(1, intRoot).filter(function (x) { return (n % x) === 0; ...
http://rosettacode.org/wiki/Animation
Animation
Animation is integral to many parts of GUIs, including both the fancy effects when things change used in window managers, and of course games.   The core of any animation system is a scheme for periodically changing the display while still remaining responsive to the user.   This task demonstrates this. Task Creat...
#Red
Red
Red ["Animation"]   rev: false roule: does [e: back tail s: t/text either rev [move e s] [move s e]] view [t: text "Hello world! " rate 5 [rev: not rev] on-time [roule]]
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...
#REXX
REXX
/*REXX prg displays a text string (in one direction), and reverses when a key is pressed*/ parse upper version !ver !vernum .;  !pcRexx= 'REXX/PERSONAL'==!ver | 'REXX/PC'==!ver if \!pcRexx then do say say '***error*** This REXX program requires REXX/PERSONAL or REXX/PC.' ...
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.
#Mathematica_.2F_Wolfram_Language
Mathematica / Wolfram Language
freq = 8; length = freq^(-1/2); Animate[Graphics[ List[{Line[{{0, 0}, length {Sin[T], -Cos[T]}} /. {T -> (Pi/6) Cos[2 Pi freq t]}], PointSize[Large], Point[{length {Sin[T], -Cos[T]}} /. {T -> (Pi/6) Cos[2 Pi freq t]}]}], PlotRange -> {{-0.3, 0.3}, {-0.5, 0}}], {t, 0, 1}, AnimationRate -> 0.07]
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...
#E
E
pragma.enable("accumulator")   def [amb, unamb] := { # block hides internals   def Choice := Tuple[any, Map]   def [ambS, ambU] := <elib:sealing.makeBrand>("amb") var counter := 0 # Used just for printing ambs   /** Check whether two sets of decisions are consistent */ def consistent(decA, decB) { def ove...
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.
#D
D
  import openldap; import std.stdio;   void main() { auto ldap = LDAP("ldap://localhost"); auto r = ldap.search_s("dc=example,dc=com", LDAP_SCOPE_SUBTREE, "(uid=%s)".format("test")); int b = ldap.bind_s(r[0].dn, "password"); scope(exit) ldap.unbind; if (b) { writeln("error on binding"); return; } ...
http://rosettacode.org/wiki/Active_Directory/Connect
Active Directory/Connect
The task is to establish a connection to an Active Directory or Lightweight Directory Access Protocol server.
#Erlang
Erlang
  -module(ldap_example). -export( [main/1] ).   main( [Host, DN, Password] ) -> {ok, Handle} = eldap:open( [Host] ), ok = eldap:simple_bind( Handle, DN, Password ), eldap:close( Handle ).  
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.
#F.23
F#
let adObject = new System.DirectoryServices.DirectoryEntry("LDAP://DC=onecity,DC=corp,DC=fabrikam,DC=com")
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...
#C.2B.2B
C++
#include <cstdint> #include <iostream> #include <string>   using integer = uint64_t;   // See https://en.wikipedia.org/wiki/Divisor_function integer divisor_sum(integer n) { integer total = 1, power = 2; // Deal with powers of 2 first for (; n % 2 == 0; power *= 2, n /= 2) total += power; // Odd...
http://rosettacode.org/wiki/Active_Directory/Search_for_a_user
Active Directory/Search for a user
Make sure you Connect to Active Directory
#ooRexx
ooRexx
/* 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
#Perl
Perl
# 20210306 Perl programming solution   use strict; use warnings;   use Net::LDAP;   my $ldap = Net::LDAP->new( 'ldap://ldap.forumsys.com' ) or die "$@";   my $mesg = $ldap->bind( "cn=read-only-admin,dc=example,dc=com", password => "password" );   $mesg->code and die $mesg->err...
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...
#CoffeeScript
CoffeeScript
# CoffeeScript is dynamic, just like the Javascript it compiles to. # You can dynamically add attributes to objects.   # First create an object very simply. e = {} e.foo = "bar" e.yo = -> "baz" console.log e.foo, e.yo()   # CS also has class syntax to instantiate objects, the details of which # aren't shown here. The ...
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...
#Common_Lisp
Common Lisp
(defun augment-instance-with-slots (instance slots) (change-class instance (make-instance 'standard-class :direct-superclasses (list (class-of instance)) :direct-slots slots)))
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...
#D
D
struct Dynamic(T) { private T[string] vars;   @property T opDispatch(string key)() pure nothrow { return vars[key]; }   @property void opDispatch(string key, U)(U value) pure nothrow { vars[key] = value; } }   void main() { import std.variant, std.stdio;   // If the type of t...
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 |...
#Draco
Draco
/* This code uses a CP/M-specific address to demonstrate fixed locations, * so it will very likely only work under CP/M */ proc nonrec main() void: /* When declaring a variable, you can let the compiler choose an address */ word var;   /* Or you can set the address manually using @, to a fixed 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 |...
#ERRE
ERRE
  ........ A%=100 ADDR=VARPTR(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 |...
#FBSL
FBSL
ReferenceOf a = b
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 ...
#Bracmat
Bracmat
( (forceExpansion=.1+!arg+-1) & (expandx-1P=.forceExpansion$((x+-1)^!arg)) & ( isPrime = . forceExpansion $ (!arg^-1*(expandx-1P$!arg+-1*(x^!arg+-1)))  : ?+/*?+? & ~` | ) & out$"Polynomial representations of (x-1)^p for p <= 7 :" & -1:?n & whl ' ( 1+!n:~>7:?n &...
http://rosettacode.org/wiki/Additive_primes
Additive primes
Definitions In mathematics, additive primes are prime numbers for which the sum of their decimal digits are also primes. Task Write a program to determine (and show here) all additive primes less than 500. Optionally, show the number of additive primes. Also see   the OEIS entry:   A046704 additive primes.   ...
#BASIC
BASIC
10 DEFINT A-Z: E=500 20 DIM P(E): P(0)=-1: P(1)=-1 30 FOR I=2 TO SQR(E) 40 IF NOT P(I) THEN FOR J=I*2 TO E STEP I: P(J)=-1: NEXT 50 NEXT 60 FOR I=B TO E: IF P(I) GOTO 100 70 J=I: S=0 80 IF J>0 THEN S=S+J MOD 10: J=J\10: GOTO 80 90 IF NOT P(S) THEN N=N+1: PRINT I, 100 NEXT 110 PRINT: PRINT N;" additive primes found belo...
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.   ...
#BASIC256
BASIC256
print "Prime", "Digit Sum" for i = 2 to 499 if isprime(i) then s = digSum(i) if isPrime(s) then print i, s end if next i end   function isPrime(v) if v < 2 then return False if v mod 2 = 0 then return v = 2 if v mod 3 = 0 then return v = 3 d = 5 while d * d <= v if v ...
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...
#Oz
Oz
fun {Balance Col A X B} case Col#A#X#B of b#t(r t(r A X B) Y C )#Z#D then t(r t(b A X B) Y t(b C Z D)) [] b#t(r A X t(r B Y C))#Z#D then t(r t(b A X B) Y t(b C Z D)) [] b#A #X#t(r t(r B Y C) Z D) then t...
http://rosettacode.org/wiki/Almost_prime
Almost prime
A   k-Almost-prime   is a natural number   n {\displaystyle n}   that is the product of   k {\displaystyle k}   (possibly identical) primes. Example 1-almost-primes,   where   k = 1 {\displaystyle k=1} ,   are the prime numbers themselves. 2-almost-primes,   where   k = 2 {\displaystyl...
#ERRE
ERRE
  PROGRAM ALMOST_PRIME   ! ! for rosettacode.org !   !$INTEGER   PROCEDURE KPRIME(N,K->KP) LOCAL P,F FOR P=2 TO 999 DO EXIT IF NOT((F<K) AND (P*P<=N)) WHILE (N MOD P)=0 DO N/=P F+=1 END WHILE END FOR KP=(F-(N>1)=K) END PROCEDURE   BEGIN PRINT(CHR$(12);)  !CLS FOR K=1 TO 5...
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...
#F.23
F#
let rec genFactor (f, n) = if f > n then None elif n % f = 0 then Some (f, (f, n/f)) else genFactor (f+1, n)     let factorsOf (num) = Seq.unfold (fun (f, n) -> genFactor (f, n)) (2, num)   let kFactors k = Seq.unfold (fun n -> let rec loop m = if Seq.length (factorsOf m) = k then m ...
http://rosettacode.org/wiki/Anagrams
Anagrams
When two or more words are composed of the same characters, but in a different order, they are called anagrams. Task[edit] Using the word list at   http://wiki.puzzlers.org/pub/wordlists/unixdict.txt, find the sets of words that share the same characters that contain the most words in them. Related tasks Word plays ...
#C
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <ctype.h> #include <time.h>   char *sortedWord(const char *word, char *wbuf) { char *p1, *p2, *endwrd; char t; int swaps;   strcpy(wbuf, word); endwrd = wbuf+strlen(wbuf); do { swaps = 0; p1 = wbuf; p2 = endwrd-1; ...
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. ...
#NewLISP
NewLISP
  #!/usr/bin/env newlisp (define (bearing- bearing heading) (sub (mod (add (mod (sub bearing heading) 360.0) 540.0) 360.0) 180.0))   (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.7423...
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...
#PHP
PHP
<?php $words = file( 'http://www.puzzlers.org/pub/wordlists/unixdict.txt', FILE_IGNORE_NEW_LINES ); $length = 0;   foreach ($words as $word) { $chars = str_split($word); sort($chars); $chars = implode("", $chars); $length = strlen($chars); $anagrams[$length][$chars][] = $word; }   krsort($an...
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...
#Lua
Lua
local function Y(x) return (function (f) return f(f) end)(function(y) return x(function(z) return y(y)(z) end) end) end   return Y(function(fibs) return function(n) return n < 2 and 1 or fibs(n - 1) + fibs(n - 2) 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 ...
#jq
jq
# unordered def proper_divisors: . as $n | if $n > 1 then 1, (sqrt|floor as $s | range(2; $s+1) as $i | if ($n % $i) == 0 then $i, (if $i * $i == $n then empty else ($n / $i) end) else empty end) else empty end;   def addup(stream): reduce stream as $i (0; . + $i);   def task(...
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...
#Ring
Ring
  # Project : Animation   Load "guilib.ring" load "stdlib.ring" rotate = false   MyApp = New qApp { win1 = new qWidget() { setwindowtitle("Hello World") setGeometry(100,100,370,250)   lineedit1 = new qlineedit(win1) { ...
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...
#Ruby
Ruby
require 'tk' $str = TkVariable.new("Hello World! ") $dir = :right   def animate $str.value = shift_char($str.value, $dir) $root.after(125) {animate} end   def shift_char(str, dir) case dir when :right then str[-1,1] + str[0..-2] when :left then str[1..-1] + str[0,1] end end   $root = TkRoot.new("title" => ...
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.
#MATLAB
MATLAB
%This is a numerical simulation of a pendulum with a massless pivot arm.   %% User Defined Parameters %Define external parameters g = -9.8; deltaTime = 1/50; %Decreasing this will increase simulation accuracy endTime = 16;   %Define pendulum rodPivotPoint = [2 2]; %rectangular coordinates rodLength = 1; mass = 1; %of t...
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...
#Egison
Egison
  ; We don't need 'amb' in the code since pattern-matching of Egison automatically do backtracking. (match-all {{"the" "that" "a"} {"frog" "elephant" "thing"} {"walked" "treaded" "grows"} {"slowly" "quickly"}} (list (multiset string)) [<cons <cons (& <snoc $c_1 _> $w_1) _> (loop $i [2 $n] <cons <c...
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.
#Go
Go
package main   import ( "log" "github.com/jtblin/go-ldap-client" )   func main() { client := &ldap.LDAPClient{ Base: "dc=example,dc=com", Host: "ldap.example.com", Port: 389, UseSSL: false, BindDN: "uid=readonlyuser,ou=People,dc=exa...
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.
#Haskell
Haskell
{-# LANGUAGE OverloadedStrings #-}   module Main (main) where   import Data.Foldable (for_) import qualified Data.Text.Encoding as Text (encodeUtf8) import Ldap.Client (Attr(..), Filter(..)) import qualified Ldap.Client as Ldap (Dn(..), Host(..), search, with, typesOnly)   main :: IO () main = do ...
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.
#Java
Java
import java.io.IOException; import org.apache.directory.api.ldap.model.exception.LdapException; import org.apache.directory.ldap.client.api.LdapConnection; import org.apache.directory.ldap.client.api.LdapNetworkConnection;   public class LdapConnectionDemo {   public static void main(String[] args) throws LdapExcep...
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...
#CLU
CLU
% This program uses the 'bigint' cluster from PCLU's 'misc.lib'   % Remove leading and trailing whitespace (bigint$unparse adds a lot) strip = proc (s: string) returns (string) ac = array[char] sc = sequence[char] cs: ac := string$s2ac(s) while ~ac$empty(cs) cand ac$bottom(cs)=' ' do ac$reml(cs) end ...
http://rosettacode.org/wiki/Active_Directory/Search_for_a_user
Active Directory/Search for a user
Make sure you Connect to Active Directory
#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)}) if res...
http://rosettacode.org/wiki/Active_Directory/Search_for_a_user
Active Directory/Search for a user
Make sure you Connect to Active Directory
#PHP
PHP
<?php   $l = ldap_connect('ldap.example.com'); ldap_set_option($l, LDAP_OPT_PROTOCOL_VERSION, 3); ldap_set_option($l, LDAP_OPT_REFERRALS, false);   $bind = ldap_bind($l, 'me@example.com', 'password');   $base = 'dc=example, dc=com'; $criteria = '(&(objectClass=user)(sAMAccountName=username))'; $attributes = array('disp...
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...
#Elena
Elena
import extensions;   class Extender : BaseExtender { prop object foo;   constructor(object) { theObject := object } }   public program() { var object := 234;   // extending an object with a field object := new Extender(object);   object.foo := "bar";   console.printLine(objec...
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...
#Falcon
Falcon
vect = [ 'alpha', 'beta', 'gamma' ] vect.dump = function () for n in [0: self.len()] > @"$(n): ", self[n] end end vect += 'delta' vect.dump()
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...
#FBSL
FBSL
#APPTYPE CONSOLE   CLASS Growable   PRIVATE:   DIM instructions AS STRING = "Sleep(1)" :ExecCode DIM dummy AS INTEGER = EXECLINE(instructions, 1)   PUBLIC:   METHOD Absorb(code AS STRING) instructions = code GOTO ExecCode END METHOD   METHOD Yield() AS VARIANT RETURN result END METHOD   END CLASS   DIM S...
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 |...
#Forth
Forth
variable foo foo . \ some large number, an address 8 foo ! foo @ . \ 8
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 |...
#Fortran
Fortran
program test_loc implicit none   integer :: i real :: r   i = loc(r) print *, i end program
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 |...
#FreeBASIC
FreeBASIC
' FB 1.05.0 Win64 Dim a As Integer = 3 Dim p As Integer Ptr = @a Print a, p
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
C
#include <stdio.h> #include <stdlib.h>   long long c[100];   void coef(int n) { int i, j;   if (n < 0 || n > 63) abort(); // gracefully deal with range issue   for (c[i=0] = 1; i < n; c[0] = -c[0], i++) for (c[1 + (j=i)] = 1; j > 0; j--) c[j] = c[j-1] - c[j]; }   int is_prime(int n) { int i;   coef(n); c[0] ...
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.   ...
#BCPL
BCPL
get "libhdr" manifest $( limit = 500 $)   let dsum(n) = n=0 -> 0, dsum(n/10) + n rem 10   let sieve(prime, n) be $( 0!prime := false 1!prime := false for i=2 to n do i!prime := true for i=2 to n/2 if i!prime $( let j=i+i while j<=n $( j!prime := false ...
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.   ...
#C
C
  #include <stdbool.h> #include <stdio.h> #include <string.h>   void memoizeIsPrime( bool * result, const int N ) { result[2] = true; result[3] = true; int prime[N]; prime[0] = 3; int end = 1; for (int n = 5; n < N; n += 2) { bool n_is_prime = true; for (int i = 0; i < 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-bla...
#Perl
Perl
#!perl use 5.010; use strict; use warnings qw(FATAL all);   my $balanced = qr{([^<>,]++|<(?-1),(?-1),(?-1),(?-1)>)}; my ($a, $b, $c, $d, $x, $y, $z) = map +qr((?<$_>$balanced)), 'a'..'d', 'x'..'z'; my $col = qr{(?<col>[RB])};   sub balance { local $_ = shift; if( /^<B,<R,<R,$a,$x,$b>,$y,$c>,$z,$d>\z/ or /^<B,<R,$a...
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...
#Factor
Factor
USING: formatting fry kernel lists lists.lazy locals math.combinatorics math.primes.factors math.ranges sequences ; IN: rosetta-code.almost-prime   : k-almost-prime? ( n k -- ? ) '[ factors _ <combinations> [ product ] map ] [ [ = ] curry ] bi any? ;   :: first10 ( k -- seq ) 10 0 lfrom [ k k-almost-prime? ...
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...
#FOCAL
FOCAL
01.10 F K=1,5;D 3 01.20 Q   02.10 S N=I;S P=1;S G=0 02.20 S P=P+1 02.30 I (K-G)2.7,2.7;I (N-P*P)2.7 02.40 S Z=FITR(N/P) 02.50 I (Z*P-N)2.2 02.60 S N=Z;S G=G+1;G 2.4 02.70 I (1-N)2.8;R 02.80 S G=G+1   03.10 T "K",%1,K,":" 03.20 S I=2;S C=0 03.30 D 2;I (G-K)3.6,3.4,3.6 03.40 T " ",%3,I 03.50 S C=C+1 03.60 S I=I+1 03.70 I...
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 ...
#C.23
C#
using System; using System.IO; using System.Linq; using System.Net; using System.Text.RegularExpressions;   namespace Anagram { class Program { const string DICO_URL = "http://wiki.puzzlers.org/pub/wordlists/unixdict.txt";   static void Main( string[] args ) { WebRequest requ...
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. ...
#Nim
Nim
import math import strutils     proc delta(b1, b2: float) : float = result = (b2 - b1) mod 360.0   if result < -180.0: result += 360.0 elif result >= 180.0: result -= 360.0     let testVectors : seq[tuple[b1, b2: float]] = @[ (20.00, 45.00 ), (-45.00, 45.00 ), (-85.00, 90...
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...
#Picat
Picat
go => M = [W:W in read_file_lines("unixdict.txt")].group(sort), Deranged = [Value : _Key=Value in M, Value.length > 1, allderanged(Value)], MaxLen = max([V[1].length : V in Deranged]), println([V : V in Deranged, V[1].length==MaxLen]), nl.   % A and B are deranged: i.e. there is no % position with the same ch...
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...
#M2000_Interpreter
M2000 Interpreter
  A$={{ Module "Fibonacci" : Read X  :If X<0 then {Error {X<0}} Else Fib=Lambda (x)->if(x>1->fib(x-1)+fib(x-2), x) : =fib(x)}} Try Ok { Print Function(A$, -12) } If Error or Not Ok Then Print Error$ Print Function(A$, 12)=144 ' true  
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 ...
#Julia
Julia
using Primes, Printf   function pcontrib(p::Int64, a::Int64) n = one(p) pcon = one(p) for i in 1:a n *= p pcon += n end return pcon end   function divisorsum(n::Int64) dsum = one(n) for (p, a) in factor(n) dsum *= pcontrib(p, a) end dsum -= n end   function am...
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...
#Rust
Rust
#[cfg(feature = "gtk")] mod graphical { extern crate gtk;   use self::gtk::traits::*; use self::gtk::{Inhibit, Window, WindowType}; use std::ops::Not; use std::sync::{Arc, RwLock};   pub fn create_window() { gtk::init().expect("Failed to initialize GTK");   let window = Window::n...
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...
#Scala
Scala
import scala.actors.Actor.{actor, loop, reactWithin, exit} import scala.actors.TIMEOUT import scala.swing.{SimpleSwingApplication, MainFrame, Label} import scala.swing.event.MouseClicked   case object Revert   object BasicAnimation extends SimpleSwingApplication { val label = new Label("Hello World! ") val rotator ...
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.
#Nim
Nim
# Pendulum simulation.   import math import times   import opengl import opengl/glut   var # Simulation variables. lg: float # Pendulum length. g: float # Gravity (should be positive). currTime: Time # Current time. theta0: float # Initial angle. theta: float # Current angle. ...
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...
#Ela
Ela
open list core   amb xs = x where (Some x) = & join xs "" join (x::xs) = amb' x (join xs) join [] = \_ -> Some "" eq' [] x = true eq' w x = last w == head x amb' [] _ _ = None amb' (x::xs) n w | eq' w x = match n x with Some v = Some (x ++ " " ++ v) _ = amb' xs n w | els...
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.
#Julia
Julia
using LDAPClient   conn = LDAPClient.LDAPConnection("ldap://localhost:10389") LDAPClient.simple_bind(conn, "user", "password") LDAPClient.unbind(conn)  
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.
#Kotlin
Kotlin
  import org.apache.directory.api.ldap.model.exception.LdapException import org.apache.directory.ldap.client.api.LdapNetworkConnection import java.io.IOException import java.util.logging.Level import java.util.logging.Logger   class LDAP(map: Map<String, String>) { fun run() { var connection: LdapNetworkCon...
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...
#11l
11l
V txt = ‘Given$a$txt$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$j...
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...
#Ada
Ada
with Ada.Calendar; use Ada.Calendar; with Ada.Numerics; use Ada.Numerics; with Ada.Numerics.Elementary_Functions; use Ada.Numerics.Elementary_Functions; with Ada.Text_IO; use Ada.Text_IO;   procedure Test_Integrator is type Func is access function (...
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...
#AArch64_Assembly
AArch64 Assembly
  /* ARM assembly AARCH64 Raspberry PI 3B */ /* program achilleNumber.s */   /************************************/ /* Constantes */ /************************************/ .include "../includeConstantesARM64.inc" .equ NBFACT, 33 .equ MAXI, 50 .equ MAXI1, 20 .equ MAXI2, 1000000 ...
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...
#Common_Lisp
Common Lisp
(defparameter *nlimit* 16) (defparameter *klimit* (expt 2 47)) (defparameter *asht* (make-hash-table)) (load "proper-divisors")   (defun ht-insert (v n) (setf (gethash v *asht*) n))   (defun ht-find (v n) (let ((nprev (gethash v *asht*))) (if nprev (- n nprev) nil)))   (defun ht-list () (defun sort-keys (&op...
http://rosettacode.org/wiki/Active_Directory/Search_for_a_user
Active Directory/Search for a user
Make sure you Connect to Active Directory
#PicoLisp
PicoLisp
(de ldapsearch (Sn) (in (list "ldapsearch" "-xH" "ldap://db.debian.org" "-b" "dc=debian,dc=org" (pack "sn=" Sn) ) (list (cons 'cn (prog (from "cn: ") (line T))) (cons 'uid (prog (from "uid: ") (line T))) ) ) )
http://rosettacode.org/wiki/Active_Directory/Search_for_a_user
Active Directory/Search for a user
Make sure you Connect to Active Directory
#PowerShell
PowerShell
  Import-Module ActiveDirectory   $searchData = "user name" $searchBase = "DC=example,DC=com"   #searches by some of the most common unique identifiers get-aduser -Filter((DistinguishedName -eq $searchdata) -or (UserPrincipalName -eq $searchdata) -or (SamAccountName -eq $searchdata)) -SearchBase $searchBase    
http://rosettacode.org/wiki/Active_Directory/Search_for_a_user
Active Directory/Search for a user
Make sure you Connect to Active Directory
#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")   base = "dc=example, dc=com" criteria = "(&(objectClass=user)(sAMAccountName=username))" attributes = [...
http://rosettacode.org/wiki/Active_Directory/Search_for_a_user
Active Directory/Search for a user
Make sure you Connect to Active Directory
#Raku
Raku
    # 20190718 Raku programming solution # https://github.com/perl6/doc/issues/2898 # https://www.facebook.com/groups/perl6/permalink/2379873082279037/   # Reference: # https://github.com/Altai-man/cro-ldap # https://www.forumsys.com/tutorials/integration-how-to/ldap/online-ldap-test-server/   use v6.d; use Cro::LDAP::...
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...
#Forth
Forth
include FMS-SI.f include FMS-SILib.f       \ We can add any number of variables at runtime by adding \ objects of any type to an instance at run time. The added \ objects are then accessible via an index number.   :class foo object-list inst-objects \ a dynamically growable object container  :m init: inst-objects i...
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...
#FreeBASIC
FreeBASIC
  ' Class ... End Class ' Esta característica aún no está implementada en el compilador.  
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...
#Go
Go
package main   import ( "bufio" "fmt" "log" "os" )   type SomeStruct struct { runtimeFields map[string]string }   func check(err error) { if err != nil { log.Fatal(err) } }   func main() { ss := SomeStruct{make(map[string]string)} scanner := bufio.NewScanner(os.Stdin) fmt...
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 |...
#FutureBasic
FutureBasic
window 1   short i = 575 ptr j   j = @i   printf @"Address of i = %ld",j print @"Value of i = ";peek word(j)   HandleEvents
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 |...
#Go
Go
package main   import ( "fmt" "unsafe" )   func main() { myVar := 3.14 myPointer := &myVar fmt.Println("Address:", myPointer, &myVar) fmt.Printf("Address: %p %p\n", myPointer, &myVar)   var addr64 int64 var addr32 int32 ptr := unsafe.Pointer(myPointer) if unsafe.Sizeof(ptr) <= unsafe.Sizeof(addr64) { addr64...
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.23
C#
  using System; public class AksTest { static long[] c = new long[100];   static void Main(string[] args) { for (int n = 0; n < 10; n++) { coef(n); Console.Write("(x-1)^" + n + " = "); show(n); Console.WriteLine(""); } Console.Write("Primes:"); for (int n = 1; n...
http://rosettacode.org/wiki/Additive_primes
Additive primes
Definitions In mathematics, additive primes are prime numbers for which the sum of their decimal digits are also primes. Task Write a program to determine (and show here) all additive primes less than 500. Optionally, show the number of additive primes. Also see   the OEIS entry:   A046704 additive primes.   ...
#C.2B.2B
C++
#include <iomanip> #include <iostream>   bool is_prime(unsigned int n) { if (n < 2) return false; if (n % 2 == 0) return n == 2; if (n % 3 == 0) return n == 3; for (unsigned int p = 5; p * p <= n; p += 4) { if (n % p == 0) return false; p += 2; ...
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...
#Phix
Phix
-- -- demo\rosetta\Pattern_matching.exw -- ================================= -- -- 1). Lightly modified copy of demo\rosetta\VisualiseTree.exw with javascript_semantics -- To the theme tune of the Milk Tray Ad iyrt, -- All because the Windows console hates utf8: constant TL = '\#DA', -- aka '┌' VT = '\#B3', ...
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...
#Fortran
Fortran
  program almost_prime use iso_fortran_env, only: output_unit implicit none   integer :: i, c, k   do k = 1, 5 write(output_unit,'(A3,x,I0,x,A1,x)', advance="no") "k =", k, ":" i = 2 c = 0 do if (c >= 10) exit   if (kprime(i, k)) then ...
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 ...
#C.2B.2B
C++
#include <iostream> #include <fstream> #include <string> #include <map> #include <vector> #include <algorithm> #include <iterator>   int main() { std::ifstream in("unixdict.txt"); typedef std::map<std::string, std::vector<std::string> > AnagramMap; AnagramMap anagrams;   std::string word; size_t count = 0; ...
http://rosettacode.org/wiki/Angle_difference_between_two_bearings
Angle difference between two bearings
Finding the angle between two bearings is often confusing.[1] Task Find the angle which is the result of the subtraction b2 - b1, where b1 and b2 are the bearings. Input bearings are expressed in the range   -180   to   +180   degrees. The  result  is also expressed in the range   -180   to   +180   degrees. ...
#Objeck
Objeck
class AngleBearings { function : Main(args : String[]) ~ Nil { "Input in -180 to +180 range"->PrintLine(); GetDifference(20.0, 45.0)->PrintLine(); GetDifference(-45.0, 45.0)->PrintLine(); GetDifference(-85.0, 90.0)->PrintLine(); GetDifference(-95.0, 90.0)->PrintLine(); GetDifferen...
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...
#PicoLisp
PicoLisp
(let Words NIL (in "unixdict.txt" (while (line) (let (Word @ Key (pack (sort (copy @)))) (if (idx 'Words Key T) (push (car @) Word) (set Key (list Word)) ) ) ) ) (maxi '((X) (length (car X))) (extract '((Key) (pick ...
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...
#Maple
Maple
  Fib := proc( n :: nonnegint ) proc( k ) option remember; # automatically memoise if k = 0 then 0 elif k = 1 then 1 else # Recurse, anonymously thispr...
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 ...
#K
K
  propdivs:{1+&0=x!'1+!x%2} (8,2)#v@&{(x=+/propdivs[a])&~x=a:+/propdivs[x]}' v:1+!20000 (220 284 1184 1210 2620 2924 5020 5564 6232 6368 10744 10856 12285 14595 17296 18416)