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/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...
#Bracmat
Bracmat
( ( balance = a x b y c zd .  !arg  : ( B . ( ( R . ((R.?a,?x,?b),?y,?c) | (?a,?x,(R.?b,?y,?c)) ) , ?zd ) | ( ?a , ?x , ( 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...
#AWK
AWK
  # syntax: GAWK -f ALMOST_PRIME.AWK BEGIN { for (k=1; k<=5; k++) { printf("%d:",k) c = 0 i = 1 while (c < 10) { if (kprime(++i,k)) { printf(" %d",i) c++ } } printf("\n") } exit(0) } function kprime(n,k, f,p) { for (p=2; f<k && p*p...
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 ...
#ABAP
ABAP
report zz_anagrams no standard page heading. define update_progress. call function 'SAPGUI_PROGRESS_INDICATOR' exporting text = &1. end-of-definition.   " Selection screen segment allowing the person to choose which file will act as input. selection-screen begin of block file_choice. parameters p_file typ...
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. ...
#J
J
relativeBearing=: (180 -~ 360 | 180 + -~)/"1
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...
#Lasso
Lasso
local( anagrams = map, words = include_url('http://www.puzzlers.org/pub/wordlists/unixdict.txt') -> split('\n'), key, max = 0, wordsize, findings = array, derangedtest = { // this code snippet is not executed until the variable is invoked. It will return true if the compared words are a deranged anagram loca...
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...
#J
J
fibN=: (-&2 +&$: -&1)^:(1&<) M."0
http://rosettacode.org/wiki/Amicable_pairs
Amicable pairs
Two integers N {\displaystyle N} and M {\displaystyle M} are said to be amicable pairs if N ≠ M {\displaystyle N\neq M} and the sum of the proper divisors of N {\displaystyle N} ( s u m ( p r o p D i v s ( N ) ) {\displaystyle \mathrm {sum} (\mathrm {propDivs} (N))} ) = M ...
#F.23
F#
  [2..20000 - 1] |> List.map (fun n-> n, ([1..n/2] |> List.filter (fun x->n % x = 0) |> List.sum)) |> List.map (fun (a,b) ->if a<b then (a,b) else (b,a)) |> List.groupBy id |> List.map snd |> List.filter (List.length >> ((=) 2)) |> List.map List.head |> List.iter (printfn "%A")  
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...
#Oz
Oz
functor import Application QTk at 'x-oz://system/wp/QTk.ozf' define proc {Start} Label Window = {CreateWindow ?Label} Animation = {New LabelAnimation init(Label delay:125)} in {Window show} {Animation go} end   fun {CreateWindow ?Label} Courier = {QTk.newFont font(f...
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.
#HicEst
HicEst
REAL :: msec=10, Lrod=1, dBob=0.03, g=9.81, Theta(2), dTheta(2) BobMargins = ALIAS(ls, rs, ts, bs) ! box margins to draw the bob     Theta = (1, 0) ! initial angle and velocity start_t = TIME()   DO i = 1, 1E100 ! "forever" end_t = TIME() ! to integrate in real-time sections: DIFFEQ(Callback="pen...
http://rosettacode.org/wiki/Almkvist-Giullera_formula_for_pi
Almkvist-Giullera formula for pi
The Almkvist-Giullera formula for calculating   1/π2   is based on the Calabi-Yau differential equations of order 4 and 5,   which were originally used to describe certain manifolds in string theory. The formula is: 1/π2 = (25/3) ∑0∞ ((6n)! / (n!6))(532n2 + 126n + 9) / 10002n+1 This formula can be used to calcul...
#Quackery
Quackery
[ $ "bigrat.qky" loadfile ] now!   [ 1 swap times [ i^ 1+ * ] ] is ! ( n --> n )   [ dup dup 2 ** 532 * over 126 * + 9 + swap 6 * ! * 32 * swap ! 6 ** 3 * / ] is intterm ( n --> n )   [ dup intterm 10 rot 6 * 3 + ** reduce ] is vterm ( n --> n/d )   1...
http://rosettacode.org/wiki/Almkvist-Giullera_formula_for_pi
Almkvist-Giullera formula for pi
The Almkvist-Giullera formula for calculating   1/π2   is based on the Calabi-Yau differential equations of order 4 and 5,   which were originally used to describe certain manifolds in string theory. The formula is: 1/π2 = (25/3) ∑0∞ ((6n)! / (n!6))(532n2 + 126n + 9) / 10002n+1 This formula can be used to calcul...
#Raku
Raku
# 20201013 Raku programming solution   use BigRoot; use Rat::Precise; use experimental :cached;   BigRoot.precision = 75 ; my $Precision = 70 ; my $AGcache = 0 ;   sub postfix:<!>(Int $n --> Int) is cached { [*] 1 .. $n }   sub Integral(Int $n --> Int) is cached { (2⁵*(6*$n)! * (532*$n² + 126*$n + 9)) div...
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...
#Ada
Ada
with Ada.Strings.Unbounded; use Ada.Strings.Unbounded; with Ada.Text_IO; use Ada.Text_IO;   procedure Test_Amb is type Alternatives is array (Positive range <>) of Unbounded_String;   type Amb (Count : Positive) is record This : Positive := 1; Left : access Amb; List : Alternatives ...
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...
#C.2B.2B
C++
enum Color { R, B }; template<Color, class, auto, class> struct T; struct E;   template<Color col, class a, auto x, class b> struct balance { using type = T<col, a, x, b>; }; template<class a, auto x, class b, auto y, class c, auto z, class d> struct balance<B, T<R, T<R, a, x, b>, y, c>, z, d> { using type = 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...
#BASIC
BASIC
10 DEFINT A-Z 20 FOR K=1 TO 5 30 PRINT USING "K = #:";K; 40 I=2: C=0 50 F=0: P=2: N=I 60 IF F >= K OR P*P > N THEN 100 70 IF N MOD P = 0 THEN N = N/P: F = F+1: GOTO 70 80 P = P+1 90 GOTO 60 100 IF N > 1 THEN F = F+1 110 IF F = K THEN C = C+1: PRINT USING " ###";I; 120 I = I+1 130 IF C < 10 THEN 50 140 PRINT 150 NEXT K
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...
#BASIC256
BASIC256
function kPrime(n, k) f = 0 for i = 2 to n while n mod i = 0 if f = k then return False f += 1 n /= i end while next i return f = k end function   for k = 1 to 5 print "k = "; k; " :"; i = 2 c = 0 while c < 10 if kPrime(i, 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 ...
#Ada
Ada
with Ada.Text_IO; use Ada.Text_IO;   with Ada.Containers.Indefinite_Ordered_Maps; with Ada.Containers.Indefinite_Ordered_Sets;   procedure Words_Of_Equal_Characters is package Set_Of_Words is new Ada.Containers.Indefinite_Ordered_Sets (String); use Ada.Containers, Set_Of_Words; package Anagrams is new Ada.Con...
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. ...
#Java
Java
public class AngleDifference {   public static double getDifference(double b1, double b2) { double r = (b2 - b1) % 360.0; if (r < -180.0) r += 360.0; if (r >= 180.0) r -= 360.0; return r; }   public static void main(String[] args) { System.out....
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...
#Liberty_BASIC
Liberty BASIC
print "Loading dictionary file." open "unixdict.txt" for input as #1 a$=input$(#1,lof(#1)) close #1   dim theWord$(30000) dim ssWord$(30000)   c10$ = chr$(10) i = 1 print "Creating array of words." while instr(a$,c10$,i) <> 0 j = instr(a$,c10$,i) ln = j - i again = 1 sWord$ = mid$(a$,i,j-i) n = n + 1 ...
http://rosettacode.org/wiki/Anonymous_recursion
Anonymous recursion
While implementing a recursive function, it often happens that we must resort to a separate   helper function   to handle the actual recursion. This is usually the case when directly calling the current function would waste too many resources (stack space, execution time), causing unwanted side-effects,   and/or the f...
#Java
Java
public static long fib(int n) { if (n < 0) throw new IllegalArgumentException("n can not be a negative number");   return new Object() { private long fibInner(int n) { return (n < 2) ? n : (fibInner(n - 1) + fibInner(n - 2)); } }.fibInner(n); }
http://rosettacode.org/wiki/Amicable_pairs
Amicable pairs
Two integers N {\displaystyle N} and M {\displaystyle M} are said to be amicable pairs if N ≠ M {\displaystyle N\neq M} and the sum of the proper divisors of N {\displaystyle N} ( s u m ( p r o p D i v s ( N ) ) {\displaystyle \mathrm {sum} (\mathrm {propDivs} (N))} ) = M ...
#Factor
Factor
  USING: grouping math.primes.factors math.ranges ;   : pdivs ( n -- seq ) divisors but-last ; : dsum ( n -- sum ) pdivs sum ; : dsum= ( n m -- ? ) dsum = ; : both-dsum= ( n m -- ? ) [ dsum= ] [ swap dsum= ] 2bi and ; : amicable? ( n m -- ? ) [ both-dsum= ] [ = not ] 2bi and ; : drange ( ...
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...
#Pascal
Pascal
program HelloWorldAnimatedGUI;   uses {$IFDEF UNIX} {$IFDEF UseCThreads} cthreads, {$ENDIF} {$ENDIF} Interfaces, // this includes the LCL widgetset Forms, Classes, Controls, StdCtrls, ExtCtrls;   type { TFrmHelloWorldAnim } TFrmHelloWorldAnim = class(TForm) constructor CreateNew(AOwner: TComponent...
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.
#Icon_and_Unicon
Icon and Unicon
  import gui $include "guih.icn"   # some constants to define the display and pendulum $define HEIGHT 400 $define WIDTH 500 $define STRING_LENGTH 200 $define HOME_X 250 $define HOME_Y 21 $define SIZE 30 $define START_ANGLE 80   class WindowApp : Dialog ()   # draw the pendulum on given context_window, at position (x,...
http://rosettacode.org/wiki/Almkvist-Giullera_formula_for_pi
Almkvist-Giullera formula for pi
The Almkvist-Giullera formula for calculating   1/π2   is based on the Calabi-Yau differential equations of order 4 and 5,   which were originally used to describe certain manifolds in string theory. The formula is: 1/π2 = (25/3) ∑0∞ ((6n)! / (n!6))(532n2 + 126n + 9) / 10002n+1 This formula can be used to calcul...
#REXX
REXX
/*REXX program uses the Almkvist─Giullera formula for 1 / (pi**2) [or pi ** -2]. */ numeric digits length( pi() ) + length(.); w= 102 say $( , 3) $( , w%2) $('power', 5) $( , w) say $('N', 3) $('integer term', w%2) $('o...
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...
#ALGOL_68
ALGOL 68
MODE PAGE = FLEX[0]STRING; MODE YIELDPAGE = PROC(PAGE)VOID; MODE ITERPAGE = PROC(YIELDPAGE)VOID;   OP INITITERPAGE = (PAGE self)ITERPAGE: (YIELDPAGE yield)VOID: # scope violation # FOR i TO UPB self DO yield(self[i]) OD;   OP + = (ITERPAGE for strings, PAGE b)ITERPAGE: (YIELDPAGE yield)VOID: # scope ...
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...
#C.23
C#
using System;   class Tree { public static void Main() { Tree tree = Tree.E; for (int i = 1; i <= 16; i++) { tree = tree.Insert(i); } tree.Print(); }   private const bool B = false, R = true; public static readonly Tree E = new Tree(B, null, 0, null);   pr...
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...
#BCPL
BCPL
get "libhdr"   let kprime(n, k) = valof $( let f, p = 0, 2 while f<k & p*p<=n do $( while n rem p = 0 do $( n := n/p f := f+1 $) p := p+1 $) if n > 1 then f := f + 1 resultis f = k $)   let start() be $( for k=1 to 5 do $( let i, c = 2, 0 writef("...
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...
#Befunge
Befunge
1>::48*"= k",,,,02p.":",01v |^ v0!`\*:g40:<p402p300:+1< K| >2g03g`*#v_ 1`03g+02g->| F@>/03g1+03p>vpv+1\.:,*48 < P#|!\g40%g40:<4>:9`>#v_\1^| |^>#!1#`+#50#:^#+1,+5>#5$<|
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 ...
#ALGOL_68
ALGOL 68
# find longest list(s) of words that are anagrams in a list of words # # use the associative array in the Associate array/iteration task # PR read "aArray.a68" PR   # returns the number of occurances of ch in text # PROC count = ( STRING text, CHAR ch )INT: BEGIN INT result := 0; FOR c FROM LW...
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. ...
#JavaScript
JavaScript
function relativeBearing(b1Rad, b2Rad) { b1y = Math.cos(b1Rad); b1x = Math.sin(b1Rad); b2y = Math.cos(b2Rad); b2x = Math.sin(b2Rad); crossp = b1y * b2x - b2y * b1x; dotp = b1x * b2x + b1y * b2y; if(crossp > 0.) return Math.acos(dotp); return -Math.acos(dotp); }   function test() { var deg2rad = 3.14159265/18...
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...
#Lua
Lua
string.tacnoc = function(str) -- 'inverse' of table.concat local arr={} for ch in str:gmatch(".") do arr[#arr+1]=ch end return arr end   local function deranged(s1, s2) if s1==s2 then return false end local t1, t2 = s1:tacnoc(), s2:tacnoc() for i,v in ipairs(t1) do if t2[i]==v then return false end end re...
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...
#JavaScript
JavaScript
function fibo(n) { if (n < 0) { throw "Argument cannot be negative"; }   return (function(n) { return (n < 2) ? 1 : arguments.callee(n-1) + arguments.callee(n-2); })(n); }
http://rosettacode.org/wiki/Amicable_pairs
Amicable pairs
Two integers N {\displaystyle N} and M {\displaystyle M} are said to be amicable pairs if N ≠ M {\displaystyle N\neq M} and the sum of the proper divisors of N {\displaystyle N} ( s u m ( p r o p D i v s ( N ) ) {\displaystyle \mathrm {sum} (\mathrm {propDivs} (N))} ) = M ...
#Forth
Forth
: proper-divisors ( n -- 1..n ) dup 2 / 1+ 1 ?do dup i mod 0= if i swap then loop drop ;   : divisors-sum ( 1..n -- n ) dup 1 = if exit then begin over + swap 1 = until ;   : pair ( n -- n ) dup 1 = if exit then proper-divisors divisors-sum ;   : ?paired ( n -- t | f ) dup pair 2dup pair = >r < r>...
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...
#Perl
Perl
use Tk; use Time::HiRes qw(sleep);   my $msg = 'Hello World! '; my $first = '.+'; my $second = '.';   my $mw = Tk::MainWindow->new(-title => 'Animated side-scroller',-bg=>"white"); $mw->geometry ("400x150+0+0");   $mw->optionAdd('*Label.font', 'Courier 24 bold' );   my $scroller = $mw->Label(-text => "$msg")->grid(...
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.
#J
J
require 'gl2 trig' coinsert 'jgl2'   DT =: %30 NB. seconds ANGLE=: 0.45p1 NB. radians L =: 1 NB. metres G =: 9.80665 NB. ms_2 VEL =: 0 NB. ms_1   PEND=: noun define pc pend;pn "Pendulum"; xywh 0 0 320 200;cc isi isigraph rightmove bottommove; pas 0 0;pcenter; rem form end; )   pend_run ...
http://rosettacode.org/wiki/Almkvist-Giullera_formula_for_pi
Almkvist-Giullera formula for pi
The Almkvist-Giullera formula for calculating   1/π2   is based on the Calabi-Yau differential equations of order 4 and 5,   which were originally used to describe certain manifolds in string theory. The formula is: 1/π2 = (25/3) ∑0∞ ((6n)! / (n!6))(532n2 + 126n + 9) / 10002n+1 This formula can be used to calcul...
#Sidef
Sidef
func almkvist_giullera(n) { (32 * (14*n * (38*n + 9) + 9) * (6*n)!) / (3 * n!**6) }   func almkvist_giullera_pi(prec = 70) {   local Num!PREC = (4*(prec+1)).numify   var sum = 0 var target = -1   for n in (0..Inf) { sum += (almkvist_giullera(n) / (10**(6*n + 3))) var curr = (sum**-.5...
http://rosettacode.org/wiki/Almkvist-Giullera_formula_for_pi
Almkvist-Giullera formula for pi
The Almkvist-Giullera formula for calculating   1/π2   is based on the Calabi-Yau differential equations of order 4 and 5,   which were originally used to describe certain manifolds in string theory. The formula is: 1/π2 = (25/3) ∑0∞ ((6n)! / (n!6))(532n2 + 126n + 9) / 10002n+1 This formula can be used to calcul...
#Visual_Basic_.NET
Visual Basic .NET
Imports System, BI = System.Numerics.BigInteger, System.Console   Module Module1   Function isqrt(ByVal x As BI) As BI Dim t As BI, q As BI = 1, r As BI = 0 While q <= x : q <<= 2 : End While While q > 1 : q >>= 2 : t = x - r - q : r >>= 1 If t >= 0 Then x = t : r += q En...
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...
#ATS
ATS
  (* ****** ****** *) // #include "share/atspre_staload.hats" #include "share/HATS/atspre_staload_libats_ML.hats" // (* ****** ****** *) // staload "libats/ML/SATS/monad_list.sats" staload _ = "libats/ML/DATS/monad_list.dats" // (* ****** ****** *) // datatype words = | Sing of stringGt(0) | Comb of (words, words) ...
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 |...
#360_Assembly
360 Assembly
LA R3,I load address of I ... I DS F
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...
#Clojure
Clojure
(mapc #'use-package '(#:toadstool #:toadstool-system)) (defstruct (red-black-tree (:constructor tree (color left val right))) color left val right)   (defcomponent tree (operator macro-mixin)) (defexpand tree (color left val right) `(class red-black-tree red-black-tree-color ,color red-blac...
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...
#C
C
#include <stdio.h>   int kprime(int n, int k) { int p, f = 0; for (p = 2; f < k && p*p <= n; p++) while (0 == n % p) n /= p, f++;   return f + (n > 1) == k; }   int main(void) { int i, c, k;   for (k = 1; k <= 5; k++) { printf("k = %d:", k);   for (i = 2, c = 0; c < 10; i++) if (kprime(i, k)) { pri...
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 ...
#APL
APL
  anagrams←{ tie←⍵ ⎕NTIE 0 dict←⎕NREAD tie 80(⎕NSIZE tie)0 boxes←((⎕UCS 10)≠dict)⊆dict ana←(({⍵[⍋⍵]}¨boxes)({⍵}⌸)boxes) ({~' '∊¨(⊃/¯1↑[2]⍵)}ana)⌿ana ⋄ ⎕NUNTIE }  
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. ...
#Jsish
Jsish
/* Angle difference between bearings, in Jsish */ function angleDifference(bearing1:number, bearing2:number):number { var angle = (bearing2 - bearing1) % 360; if (angle < -180) angle += 360; if (angle >= 180) angle -= 360; return angle; }   if (Interp.conf('unitTest')) { var dataSet = [[20, 45], [-4...
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...
#Maple
Maple
with(StringTools): dict:=Split([HTTP:-Get("www.puzzlers.org/pub/wordlists/unixdict.txt")][2]): L:=[seq(select(t->HammingDistance(t,w)=length(w),[Anagrams(w,dict)])[],w=dict)]: len:=length(ListTools:-FindMaximalElement(L,(a,b)->length(a)<length(b))): select(w->length(w)=len,L)[];
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...
#Joy
Joy
fib == [small] [] [pred dup pred] [+] binrec;
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 ...
#Fortran
Fortran
Perfect!! 6 Perfect!! 28 Amicable! 220 284 Perfect!! 496 Amicable! 1184 1210 Amicable! 2620 2924 Amicable! 5020 5564 Amicable! 6232 6368 Perfect!! 8128 Amicable! 10744 10856 Amicable! 12285 ...
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...
#Phix
Phix
-- demo\rosetta\Animation.exw with javascript_semantics include pGUI.e string hw = "Hello World! " bool direction = true Ihandle label function button_cb(Ihandle /*ih*/, integer /*button*/, pressed, /*x*/, /*y*/, atom /*pStatus*/) if pressed then direction = not direction end if return IUP_CON...
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.
#Java
Java
import java.awt.*; import javax.swing.*;   public class Pendulum extends JPanel implements Runnable {   private double angle = Math.PI / 2; private int length;   public Pendulum(int length) { this.length = length; setDoubleBuffered(true); }   @Override public void paint(Graphics ...
http://rosettacode.org/wiki/Almkvist-Giullera_formula_for_pi
Almkvist-Giullera formula for pi
The Almkvist-Giullera formula for calculating   1/π2   is based on the Calabi-Yau differential equations of order 4 and 5,   which were originally used to describe certain manifolds in string theory. The formula is: 1/π2 = (25/3) ∑0∞ ((6n)! / (n!6))(532n2 + 126n + 9) / 10002n+1 This formula can be used to calcul...
#Wren
Wren
import "/big" for BigInt, BigRat import "/fmt" for Fmt   var factorial = Fn.new { |n| if (n < 2) return BigInt.one var fact = BigInt.one for (i in 2..n) fact = fact * i return fact }   var almkvistGiullera = Fn.new { |n, print| var t1 = factorial.call(6*n) * 32 var t2 = 532*n*n + 126*n + 9 v...
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...
#AutoHotkey
AutoHotkey
set1 := "the that a" set2 := "frog elephant thing" set3 := "walked treaded grows" set4 := "slowly quickly"   MsgBox % amb( "", set1, set2, set3, set4 ) ; this takes a total of 17 iterations to complete   amb( char = "", set1 = "", set2 = "", set3 = "", set4 = "" ) { ; original call to amb must leave char param b...
http://rosettacode.org/wiki/Address_of_a_variable
Address of a variable
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation |...
#6502_Assembly
6502 Assembly
;;;;;;; zero page RAM memory addresses CursorX equ $00 CursorY equ $01 temp equ $02 ;;;;;;; memory-mapped hardware registers BorderColor equ $D020   Joystick1 equ $DC01 Joystick2 equ $DC00
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 |...
#68000_Assembly
68000 Assembly
UserRam equ $100000 Cursor_X equ UserRam ;$100000, byte length Cursor_Y equ UserRam+1 ;$100001, byte length SixteenBitData equ UserRam+2 ;$100002, word length (VASM doesn't allow labels to begin with numbers.) ThirtyTwoBitData equ UserRam+4 ;$100004, long length   ;GET THE ADDRESS   LEA ThirtyTwoBi...
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 |...
#8086_Assembly
8086 Assembly
.model small .stack 1024 .data UserRam 256 DUP (0) ;define the next 256 bytes as user RAM, initialize them all to zero.   .code   mov ax, seg UserRam ;load into AX the segment where UserRam is stored. mov es, ax ;load that value into the Extra Segment register   mov ax, offset UserRam ;loa...
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...
#Common_Lisp
Common Lisp
(mapc #'use-package '(#:toadstool #:toadstool-system)) (defstruct (red-black-tree (:constructor tree (color left val right))) color left val right)   (defcomponent tree (operator macro-mixin)) (defexpand tree (color left val right) `(class red-black-tree red-black-tree-color ,color red-blac...
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...
#C.23
C#
using System; using System.Collections.Generic; using System.Linq;   namespace AlmostPrime { class Program { static void Main(string[] args) { foreach (int k in Enumerable.Range(1, 5)) { KPrime kprime = new KPrime() { K = k }; Console.Write...
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 ...
#AppleScript
AppleScript
use AppleScript version "2.3.1" -- OS X 10.9 (Mavericks) or later — for these 'use' commands! -- Uses the customisable AppleScript-coded sort shown at <https://macscripter.net/viewtopic.php?pid=194430#p194430>. -- It's assumed scripters will know how and where to install it as a library. use sorter : script "Custom Ite...
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. ...
#jq
jq
# Angles are in degrees; the result is rounded to 4 decimal places: def subtract($b1; $b2): 10000 as $scale | (($scale * ($b2 - $b1)) % (360 * $scale)) | round / $scale | if . < -180 then . + 360 elif . >= 180 then . - 360 else . end;   def pairs: [ 20, 45], [-45, 45], [-85, 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...
#Mathematica_.2F_Wolfram_Language
Mathematica / Wolfram Language
words=First/@Import["http://www.puzzlers.org/pub/wordlists/unixdict.txt","Table"]; anagramDegrangement=Function[{w1,w2}, Module[{c1=ToCharacterCode@w1,c2=ToCharacterCode@w2}, Sort@c1==Sort@c2&&Select[c1-c2,#==0&,1]==={}]]; gs=Select[GatherBy[words,{StringLength@#,Union@ToCharacterCode@#}&],Length@#>=2&]; First@Flatte...
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...
#jq
jq
0 | recurse(. + 1)
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 ...
#FreeBASIC
FreeBASIC
  ' FreeBASIC v1.05.0 win64   Function SumProperDivisors(number As Integer) As Integer If number < 2 Then Return 0 Dim sum As Integer = 0 For i As Integer = 1 To number \ 2 If number Mod i = 0 Then sum += i Next Return sum End Function   Dim As Integer n, f Dim As Integer sum(19999)   For n = 1 To 19999 ...
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...
#PicoLisp
PicoLisp
#!/usr/bin/picolisp /usr/lib/picolisp/lib.l   (prin "^[[?9h") # Mouse reporting on   (setq Dir 1 Text (chop "Hello World! "))   (loop (prin (do Dir (rot Text))) (when (= "^[" (key 200)) (key) (key) (when (= " " (key)) # Left button (setq Dir (if (= 1 Dir) 12 1)) ) (key) (key) ) (d...
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...
#Processing
Processing
String txt = "Hello, world! "; boolean dir = true;   void draw(){ background(128); text(txt, 10, height/2); if(frameCount%10==0){ if(dir) { txt = rotate(txt, 1); } else { txt = rotate(txt, txt.length()-1); } } }   void mouseReleased(){ dir = !dir; }   String rotate(String text, int sta...
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.
#JavaScript
JavaScript
<html><head> <title>Pendulum</title> </head><body style="background: gray;">   <canvas id="canvas" width="600" height="600"> <p>Sorry, your browser does not support the &lt;canvas&gt; used to display the pendulum animation.</p> </canvas> <script> function PendulumSim(length_m, gravity_mps2, initialAngle_rad, time...
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...
#BaCon
BaCon
DECLARE (*ambassert)() TYPE NUMBER   FUNCTION amb_recurse$(text$[], nr, total, result$)   LOCAL ctr LOCAL str$, test$   FOR ctr = 1 TO AMOUNT(text$[nr]) str$ = APPEND$(result$, 0, TOKEN$(text$[nr], ctr)) IF nr = total-1 THEN IF ambassert(str$) THEN RETURN str$ ELSE ...
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...
#11l
11l
F pdsum(n) R sum((1 .. (n + 1) I/ 2).filter(x -> @n % x == 0 & @n != x))   F aliquot(n, maxlen = 16, maxterm = 2 ^ 30) I n == 0 R (‘terminating’, [0]) V s = [n] V slen = 1 V new = n L slen <= maxlen & new < maxterm new = pdsum(s.last) I new C s I s[0] == new I sl...
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 |...
#AArch64_Assembly
AArch64 Assembly
  /* ARM assembly AArch64 Raspberry PI 3B */ /* program adrvar.s */ /*************************************/ /* Constantes */ /*************************************/ .equ STDOUT, 1 .equ WRITE, 64 .equ EXIT, 93 /*************************************/ /* Initialized data */ /*...
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 |...
#Action.21
Action!
PROC Main() BYTE v=[123]   PrintF("Value of variable: %B%E",v) PrintF("Address of variable: %H%E",@v) RETURN
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 |...
#Ada
Ada
The_Address : System.Address; I : Integer; The_Address := I'Address;
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...
#E
E
def balance(tree) { return if ( tree =~ term`tree(black, tree(red, tree(red, @a, @x, @b), @y, @c), @z, @d)` || tree =~ term`tree(black, tree(red, @a, @x, tree(red, @b, @y, @c)), @z, @d)` || tree =~ term`tree(black, @a, @x, tree(red, tree(red, @b, @y, @c), @z, @d))` || tree =~ term`tree(black, @a, @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...
#EchoLisp
EchoLisp
  ;; code adapted from Racket and Common Lisp ;; Illustrates matching on structures (require 'match) (require 'struct)     (define (N-tostring n) (format "%s %d" (N-color n) (N-value n))) (struct N (color left value right) #:tostring N-tostring)   (define (balance t) (match t [(N '⚫️ (N '🔴 (N '🔴 a x b) y c) z ...
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...
#C.2B.2B
C++
#include <cstdlib> #include <iostream> #include <sstream> #include <iomanip> #include <list>   bool k_prime(unsigned n, unsigned k) { unsigned f = 0; for (unsigned p = 2; f < k && p * p <= n; p++) while (0 == n % p) { n /= p; f++; } return f + (n > 1 ? 1 : 0) == k; }   std::list<unsigned> primes(uns...
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 ...
#ARM_Assembly
ARM Assembly
  /* ARM assembly Raspberry PI */ /* program anagram.s */   /* REMARK 1 : this program use routines in a include file see task Include a file language arm assembly for the routine affichageMess conversion10 see at end of this program the instruction include */ /* for constantes see task include a file ...
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. ...
#Julia
Julia
using Printf   function angdiff(a, b) r = (b - a) % 360.0 if r ≥ 180.0 r -= 360.0 end   return r end   println("Input in -180 to +180 range:") for (a, b) in [(20.0, 45.0), (-45.0, 45.0), (-85.0, 90.0), (-95.0, 90.0), (-45.0, 125.0), (-45.0, 145.0), (-45.0, 125.0), (-45.0, 145.0), (29.4803, -...
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...
#Nim
Nim
import algorithm import tables import times   var anagrams: Table[seq[char], seq[string]] # Mapping sorted_list_of chars -> list of anagrams.   #---------------------------------------------------------------------------------------------------   func deranged(s1, s2: string): bool = ## Return true if "s1" and "s2" ...
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...
#Julia
Julia
function fib(n) if n < 0 throw(ArgumentError("negative arguments not allowed")) end aux(m) = m < 2 ? one(m) : aux(m-1) + aux(m-2) aux(n) 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 ...
#Frink
Frink
  n = 1 seen = new set   do { n = n + 1 if seen.contains[n] next   sum = sum[allFactors[n, true, false, false]] if sum != n and sum[allFactors[sum, true, false, false]] == n { println["$n, $sum"] seen.put[sum] } } while n <= 20000  
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...
#Prolog
Prolog
:- use_module(library(pce)).   animation :- new(D, window('Animation')), new(Label, label(hello, 'Hello world ! ')), send(D, display, Label, point(1,10)), new(@animation, animation(Label)), send(D, recogniser, new(_G, my_click_gesture(left, ''))),   send(D, done_message, and(message(@an...
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.
#Julia
Julia
using Luxor using Colors using BoundaryValueDiffEq   # constants for differential equations and movie const g = 9.81 const L = 1.0 # pendulum length in meters const bobd = 0.10 # pendulum bob diameter in meters const framerate = 50.0 # intended frame rate/sec c...
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...
#Bracmat
Bracmat
( ( Amb = first last list words word solution .  !arg:(?first.?list) & ( !list: |  !list:(.?words) ?list &  !words  :  ?  %( @(?word:!first ? @?last) & Amb$(!last.!list):?solution & !word !solution:?solution ...
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...
#AArch64_Assembly
AArch64 Assembly
  /* ARM assembly AARCH64 Raspberry PI 3B or android 64 bits */ /* program aliquotSeq64.s */   /*******************************************/ /* Constantes file */ /*******************************************/ /* for this file see task include a file in language AArch64 assembly*/ .include "../...
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 |...
#ALGOL_68
ALGOL 68
[4]INT test := (222,444,666,888); REF INT reference := test[3]; REF INT(reference) := reference + 111; print(("test value is now: ",test))
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 |...
#Applesoft_BASIC
Applesoft BASIC
N = N : PRINT PEEK (131) + PEEK (132) * 256
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 |...
#Argile
Argile
use std, array (: array.arg also defines pointer operators :) let var = 42 let ptr = &var (: value of ptr is address of var :) print var (: prints 42 :) (*ptr)++ (: increments value pointed by ptr :) print var (: prints 43 :)
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 ...
#11l
11l
F expand_x_1(p) V ex = [BigInt(1)] L(i) 0 .< p ex.append(ex.last * -(p - i) I/ (i + 1)) R reversed(ex)   F aks_test(p) I p < 2 R 0B V ex = expand_x_1(p) ex[0]++ R !any(ex[0 .< (len)-1].map(mult -> mult % @p != 0))   print(‘# p: (x-1)^p for small p’) L(p) 12 print(‘#3: #.’.format(p, e...
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.   ...
#11l
11l
F is_prime(a) I a == 2 R 1B I a < 2 | a % 2 == 0 R 0B L(i) (3 .. Int(sqrt(a))).step(2) I a % i == 0 R 0B R 1B   F digit_sum(=n) V sum = 0 L n > 0 sum += n % 10 n I/= 10 R sum   V additive_primes = 0 L(i) 2..499 I is_prime(i) & is_prime(digit_sum(i)) a...
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...
#Elixir
Elixir
defmodule RBtree do def find(nil, _), do: :not_found def find({ key, value, _, _, _ }, key), do: { :found, { key, value } } def find({ key1, _, _, left, _ }, key) when key < key1, do: find(left, key) def find({ key1, _, _, _, right }, key) when key > key1, do: find(right, key)   def new(key, value), do: ins(n...
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...
#Emacs_Lisp
Emacs Lisp
(defun rbt-balance (tree) (pcase tree (`(B (R (R ,a ,x ,b) ,y ,c) ,z ,d) `(R (B ,a ,x ,b) ,y (B ,c ,z ,d))) (`(B (R ,a ,x (R ,b ,y ,c)) ,z ,d) `(R (B ,a ,x ,b) ,y (B ,c ,z ,d))) (`(B ,a ,x (R (R ,b ,y ,c) ,z ,d)) `(R (B ,a ,x ,b) ,y (B ,c ,z ,d))) (`(B ,a ,x (R ,b ,y (R ,c ,z ,d))) `(R (B ,a ,x ,b) ,y...
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...
#Clojure
Clojure
    (ns clojure.examples.almostprime (:gen-class))   (defn divisors [n] " Finds divisors by looping through integers 2, 3,...i.. up to sqrt (n) [note: rather than compute sqrt(), test with i*i <=n] " (let [div (some #(if (= 0 (mod n %)) % nil) (take-while #(<= (* % %) n) (iterate inc 2)))] (if div ...
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 ...
#Arturo
Arturo
wordset: map read.lines relative "unixdict.txt" => strip   anagrams: #[]   loop wordset 'word [ anagram: sort to [:char] word unless key? anagrams anagram -> anagrams\[anagram]: new []   anagrams\[anagram]: anagrams\[anagram] ++ word ]   loop select values anagrams 'x [5 =< size x] 'words -> pri...
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. ...
#K
K
  / Angle difference between two angles / angledif.k   angdif: {[b1;b2]; :[(r:(b2-b1)!360.0)<-180.0;r+:360.0;r>180.0;r-:360.0];:r}  
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...
#OCaml
OCaml
let sort_chars s = let r = String.copy s in for i = 0 to (String.length r) - 2 do for j = i + 1 to (String.length r) - 1 do if r.[i] > r.[j] then begin let tmp = r.[i] in r.[i] <- r.[j]; r.[j] <- tmp; end done done; (r)   let deranged (s1, s2) = let len1 = String.le...
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...
#K
K
fib: {:[x<0; "Error Negative Number"; {:[x<2;x;_f[x-2]+_f[x-1]]}x]}
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 ...
#Futhark
Futhark
  fun divisors(n: int): []int = filter (fn x => n%x == 0) (map (1+) (iota (n/2)))   fun amicable((n: int, nd: int), (m: int, md: int)): bool = n < m && nd == m && md == n   fun getPair (divs: [upper](int, int)) (flat_i: int): ((int,int), (int,int)) = let i = flat_i / upper let j = flat_i % upper in unsafe (di...
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...
#PureBasic
PureBasic
OpenWindow(0,0,0,500,100,"Hello World!",#PB_Window_ScreenCentered|#PB_Window_SystemMenu)   text$ = "Hello World! " direction = 1   LoadFont(0,"",60) ButtonGadget(0,2,2,496,96,text$) : SetGadgetFont(0,FontID(0))   Repeat event = WaitWindowEvent(50) Select event Case #PB_Event_Gadget If EventGadget() = 0 ...
http://rosettacode.org/wiki/Animate_a_pendulum
Animate a pendulum
One good way of making an animation is by simulating a physical system and illustrating the variables in that system using a dynamically changing graphical display. The classic such physical system is a simple gravity pendulum. Task Create a simple physical model of a pendulum and animate it.
#Kotlin
Kotlin
import java.awt.* import java.util.concurrent.* import javax.swing.*   class Pendulum(private val length: Int) : JPanel(), Runnable { init { val f = JFrame("Pendulum") f.add(this) f.defaultCloseOperation = JFrame.EXIT_ON_CLOSE f.pack() f.isVisible = true isDoubleBuffe...
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...
#C
C
typedef const char * amb_t;   amb_t amb(size_t argc, ...) { amb_t *choices; va_list ap; int i;   if(argc) { choices = malloc(argc*sizeof(amb_t)); va_start(ap, argc); i = 0; do { choices[i] = va_arg(ap, amb_t); } while(++i < argc); va_end(ap);   i = 0; do { TRY(choices[i]); } while(++...
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...
#ALGOL_68
ALGOL 68
BEGIN # aliquot sequence classification # # maximum sequence length we consider # INT max sequence length = 16; # possible classifications # STRING perfect classificatio...
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 |...
#ARM_Assembly
ARM Assembly
    /* ARM assembly Raspberry PI */ /* program adrvar.s */   /* Constantes */ .equ STDOUT, 1 .equ WRITE, 4 .equ EXIT, 1 /* Initialized data */ .data szMessage: .asciz "Hello. \n " @ message szRetourLigne: .asciz "\n" iValDeb: .int 5 @ value 5 in array of 4 bytes /* No Initialized data ...
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 ...
#8th
8th
  with: a   : nextrow \ a -- a len [ ( drop [1] ), ( drop [1,1] ), ( ' n:+ y 1 slide 1 push ) ] swap 2 min caseof ;   ;with   with: n   : .x \ n -- dup [ ( drop ), ( drop "x" . ), ( "x^" . . ) ] swap 2 min caseof space ;   : .term \ coef exp -- ; om...
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.   ...
#AArch64_Assembly
AArch64 Assembly
  /* ARM assembly AARCH64 Raspberry PI 3B or android 64 bits */ /* program additivePrime64.s */   /*******************************************/ /* Constantes file */ /*******************************************/ /* for this file see task include a file in language AArch64 assembly*/ .include ...
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.   ...
#Ada
Ada
with Ada.Text_Io;   procedure Additive_Primes is   Last  : constant := 499; Columns : constant := 12;   type Prime_List is array (2 .. Last) of Boolean;   function Get_Primes return Prime_List is Prime : Prime_List := (others => True); begin for P in Prime'Range loop if Prime (P) t...