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/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... | #Qi | Qi |
(define fib
N -> (let A (/. A N
(if (< N 2)
N
(+ (A A (- N 2))
(A A (- N 1)))))
(A A 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
... | #PL.2FI | PL/I | *process source xref;
ami: Proc Options(main);
p9a=time();
Dcl (p9a,p9b,p9c) Pic'(9)9';
Dcl sumpd(20000) Bin Fixed(31);
Dcl pd(300) Bin Fixed(31);
Dcl npd Bin Fixed(31);
Dcl (x,y) Bin Fixed(31);
Do x=1 To 20000;
Call proper_divisors(x,pd,npd);
sumpd(x)=sum(pd,npd);
End;
p9b=time();
Put Edit('... |
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.
| #Scheme | Scheme | #!r6rs
;;; R6RS implementation of Pendulum Animation
(import (rnrs)
(lib pstk main) ; change this for your pstk installation
)
(define PI 3.14159)
(define *conv-radians* (/ PI 180))
(define *theta* 45.0)
(define *d-theta* 0.0)
(define *length* 150)
(define *home-x* 160)
(define *home-y* 25)
;;; ... |
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... | #Mercury | Mercury | :- module amb.
:- interface.
:- import_module io.
:- pred main(io::di, io::uo) is cc_multi.
:- implementation.
:- import_module list, string, char, int.
main(!IO) :-
( solution(S) -> io.write_string(S, !IO), io.nl(!IO)
; io.write_string("No solutions found :-(\n", !IO) ).
:- pred solution(string::ou... |
http://rosettacode.org/wiki/Accumulator_factory | Accumulator factory | A problem posed by Paul Graham is that of creating a function that takes a single (numeric) argument and which returns another function that is an accumulator. The returned accumulator function in turn also takes a single numeric argument, and returns the sum of all the numeric values passed in so far to that accumulat... | #ERRE | ERRE | PROGRAM ACCUMULATOR
PROCEDURE ACCUMULATOR(SUM,N,A->SUM)
IF NOT A THEN SUM=N ELSE SUM=SUM+N
END PROCEDURE
BEGIN
PRINT(CHR$(12);) ! CLS
ACCUMULATOR(X,1,FALSE->X) ! INIT FIRST ACCUMULATOR
ACCUMULATOR(X,-15,TRUE->X)
ACCUMULATOR(X,2.3,TRUE->X)
ACCUMULATOR(Z,3,FALSE->Z) ! INIT SECOND ACCUMULATOR
... |
http://rosettacode.org/wiki/Accumulator_factory | Accumulator factory | A problem posed by Paul Graham is that of creating a function that takes a single (numeric) argument and which returns another function that is an accumulator. The returned accumulator function in turn also takes a single numeric argument, and returns the sum of all the numeric values passed in so far to that accumulat... | #F.23 | F# | // dynamically typed add
let add (x: obj) (y: obj) =
match x, y with
| (:? int as m), (:? int as n) -> box(m+n)
| (:? int as n), (:? float as x)
| (:? float as x), (:? int as n) -> box(x + float n)
| (:? float as x), (:? float as y) -> box(x + y)
| _ -> failwith "Run-time type error"
let acc init =
let ... |
http://rosettacode.org/wiki/Ackermann_function | Ackermann function | The Ackermann function is a classic example of a recursive function, notable especially because it is not a primitive recursive function. It grows very quickly in value, as does the size of its call tree.
The Ackermann function is usually defined as follows:
A
(
m
,
n
)
=
{
n
+
1
if
m
=
0
A
(
m
... | #Agda | Agda |
open import Data.Nat
open import Data.Nat.Show
open import IO
module Ackermann where
ack : ℕ -> ℕ -> ℕ
ack zero n = n + 1
ack (suc m) zero = ack m 1
ack (suc m) (suc n) = ack m (ack (suc m) n)
main = run (putStrLn (show (ack 3 9)))
|
http://rosettacode.org/wiki/Abundant,_deficient_and_perfect_number_classifications | Abundant, deficient and perfect number classifications | These define three classifications of positive integers based on their proper divisors.
Let P(n) be the sum of the proper divisors of n where the proper divisors are all positive divisors of n other than n itself.
if P(n) < n then n is classed as deficient (OEIS A005100).
if P(n)... | #BASIC | BASIC | 10 DEFINT A-Z: LM=20000
20 DIM P(LM)
30 FOR I=1 TO LM: P(I)=-32767: NEXT
40 FOR I=1 TO LM/2: FOR J=I+I TO LM STEP I: P(J)=P(J)+I: NEXT: NEXT
50 FOR I=1 TO LM
60 X=I-32767
70 IF P(I)<X THEN D=D+1 ELSE IF P(I)=X THEN P=P+1 ELSE A=A+1
80 NEXT
90 PRINT "DEFICIENT:";D
100 PRINT "PERFECT:";P
110 PRINT "ABUNDANT:";A |
http://rosettacode.org/wiki/Align_columns | Align columns | Given a text file of many lines, where fields within a line
are delineated by a single 'dollar' character, write a program
that aligns each column of fields by ensuring that words in each
column are separated by at least one space.
Further, allow for each word in a column to be either left
justified, right justified, o... | #BQN | BQN | Split ← (⊢-˜+`׬)∘=⊔⊢
PadRow ← {
w‿t𝕊𝕩: # t → type.
# 0 → left
# 1 → right
# 2 → center
pstyle←t⊑⟨{0‿𝕩},{𝕩‿0},{⟨⌊𝕩÷2,⌈𝕩÷2⟩}⟩
𝕩{(⊣∾𝕨∾⊢)´(Pstyle 𝕩)/¨<w}¨(⌈´-⊢)≠¨𝕩
}
Align ← {{𝕨∾' '∾𝕩}´˘⍉" "‿𝕨⊸PadRow˘⍉>⟨""⟩‿0 PadRow '$' Split¨(@+10) Split 𝕩}
1 Align text |
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... | #Lingo | Lingo | property _sum
property _func
property _timeLast
property _valueLast
property _ms0
property _updateTimer
on new (me, func)
if voidP(func) then func = "0.0"
me._sum = 0.0
-- update frequency: 100/sec (arbitrary)
me._updateTimer = timeout().new("update", 10, #_update, me)
me.input(func)
return me... |
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... | #Lua | Lua | local seconds = os.clock
local integrator = {
new = function(self, fn)
return setmetatable({fn=fn,t0=seconds(),v0=0,sum=0,nup=0},self)
end,
update = function(self)
self.t1 = seconds()
self.v1 = self.fn(self.t1)
self.sum = self.sum + (self.v0 + self.v1) * (self.t1 - self.t0) / 2
self.t0, self... |
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... | #Phix | Phix | function aliquot(atom n)
sequence s = {n}
integer k
if n=0 then return {"terminating",{0}} end if
while length(s)<16
and n<140737488355328 do
n = sum(factors(n,-1))
k = find(n,s)
if k then
if k=1 then
if length(s)=1 then ... |
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 ... | #Java | Java | public class AksTest {
private static final long[] c = new long[64];
public static void main(String[] args) {
for (int n = 0; n < 10; n++) {
coeff(n);
show(n);
}
System.out.print("Primes:");
for (int n = 1; n < c.length; n++)
if (isPrime(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.
... | #Polyglot:PL.2FI_and_PL.2FM | Polyglot:PL/I and PL/M | /* FIND ADDITIVE PRIMES - PRIMES WHOSE DIGIT SUM IS ALSO PRIME */
additive_primes_100H: procedure options (main);
/* PROGRAM-SPECIFIC %REPLACE STATEMENTS MUST APPEAR BEFORE THE %INCLUDE AS */
/* E.G. THE CP/M PL/I COMPILER DOESN'T LIKE THEM TO FOLLOW PROCEDURES */
/* PL... |
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... | #Pascal | Pascal | program AlmostPrime;
{$IFDEF FPC}
{$Mode Delphi}
{$ENDIF}
uses
primtrial;
var
i,K,cnt : longWord;
BEGIN
K := 1;
repeat
cnt := 0;
i := 2;
write('K=',K:2,':');
repeat
if isAlmostPrime(i,K) then
Begin
write(i:6,' ');
inc(cnt);
end;
inc(i);
until cnt = 9... |
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
... | #Fortran | Fortran | !***************************************************************************************
module anagram_routines
!***************************************************************************************
implicit none
!the dictionary file:
integer,parameter :: file_unit = 1000
character(len=*),parameter :: filenam... |
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.
... | #VBA | VBA | Private Function tx(a As Variant) As String
Dim s As String
s = CStr(Format(a, "0.######"))
If Right(s, 1) = "," Then
s = Mid(s, 1, Len(s) - 1) & " "
Else
i = InStr(1, s, ",")
s = s & String$(6 - Len(s) + i, " ")
End If
tx = s
End Function
Private Sub test(b1 As Var... |
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... | #UNIX_Shell | UNIX Shell | function get_words {
typeset host=www.puzzlers.org
typeset page=/pub/wordlists/unixdict.txt
exec 7<>/dev/tcp/$host/80
print -e -u7 "GET $page HTTP/1.1\r\nhost: $host\r\nConnection: close\r\n\r\n"
# remove the http header and save the word list
sed 's/\r$//; 1,/^$/d' <&7 >"$1"
exec 7<&-
}
... |
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... | #Quackery | Quackery | [ dup 0 < iff
$ "negative argument passed to fibonacci"
fail
[ dup 2 < if done
dup 1 - recurse
swap 2 - recurse + ] ] is fibonacci ( n --> 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
... | #PL.2FM | PL/M | 100H:
/* CP/M CALLS */
BDOS: PROCEDURE (FN, ARG); DECLARE FN BYTE, ARG ADDRESS; GO TO 5; END BDOS;
EXIT: PROCEDURE; CALL BDOS(0,0); END EXIT;
PRINT: PROCEDURE (S); DECLARE S ADDRESS; CALL BDOS(9,S); END PRINT;
/* PRINT A NUMBER */
PRINT$NUMBER: PROCEDURE (N);
DECLARE S (6) BYTE INITIAL ('.....$');
DECLARE (N,... |
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.
| #Scilab | Scilab | //Input variables (Assumptions: massless pivot, no energy loss)
bob_mass=10;
g=-9.81;
L=2;
theta0=-%pi/6;
v0=0;
t0=0;
//No. of steps
steps=300;
//Setting deltaT or duration (comment either of the lines below)
//deltaT=0.1; t_max=t0+deltaT*steps;
t_max=5; deltaT=(t_max-t0)/steps;
if t_max<=t0 then
error("Check... |
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... | #NetRexx | NetRexx | /* REXX **************************************************************
* 25.08.2013 Walter Pachl derived from REXX version 2
*********************************************************************/
w=''
l=0
mm=0
mkset(1,'the that a if',w,mm,l)
mkset(2,'frog elephant thing',w,mm,l)
mkset(3,'walked treaded grows t... |
http://rosettacode.org/wiki/Accumulator_factory | Accumulator factory | A problem posed by Paul Graham is that of creating a function that takes a single (numeric) argument and which returns another function that is an accumulator. The returned accumulator function in turn also takes a single numeric argument, and returns the sum of all the numeric values passed in so far to that accumulat... | #Factor | Factor | USE: locals
:: accumulator ( n! -- quot ) [ n + dup n! ] ;
1 accumulator
[ 5 swap call drop ]
[ drop 3 accumulator drop ]
[ 2.3 swap call ] tri . |
http://rosettacode.org/wiki/Accumulator_factory | Accumulator factory | A problem posed by Paul Graham is that of creating a function that takes a single (numeric) argument and which returns another function that is an accumulator. The returned accumulator function in turn also takes a single numeric argument, and returns the sum of all the numeric values passed in so far to that accumulat... | #Fantom | Fantom | class AccumulatorFactory
{
static |Num -> Num| accumulator (Num sum)
{
return |Num a -> Num|
{ // switch on type of sum
if (sum is Int)
{ // and then type of a
if (a is Int)
return sum = sum->plus(a)
else if (a is Float)
return sum = sum->plusFloat(a)
... |
http://rosettacode.org/wiki/Ackermann_function | Ackermann function | The Ackermann function is a classic example of a recursive function, notable especially because it is not a primitive recursive function. It grows very quickly in value, as does the size of its call tree.
The Ackermann function is usually defined as follows:
A
(
m
,
n
)
=
{
n
+
1
if
m
=
0
A
(
m
... | #ALGOL_60 | ALGOL 60 | begin
integer procedure ackermann(m,n);value m,n;integer m,n;
ackermann:=if m=0 then n+1
else if n=0 then ackermann(m-1,1)
else ackermann(m-1,ackermann(m,n-1));
integer m,n;
for m:=0 step 1 until 3 do begin
for n:=0 step 1 until 6 do
outinteger(1,ackermann(m,n))... |
http://rosettacode.org/wiki/Abundant,_deficient_and_perfect_number_classifications | Abundant, deficient and perfect number classifications | These define three classifications of positive integers based on their proper divisors.
Let P(n) be the sum of the proper divisors of n where the proper divisors are all positive divisors of n other than n itself.
if P(n) < n then n is classed as deficient (OEIS A005100).
if P(n)... | #BCPL | BCPL | get "libhdr"
manifest $( maximum = 20000 $)
let calcpdivs(p, max) be
$( for i=0 to max do p!i := 0
for i=1 to max/2
$( let j = i+i
while 0 < j <= max
$( p!j := p!j + i
j := j + i
$)
$)
$)
let classify(p, n, def, per, ab) be
$( let z = 0<=p!n<n -> def, p!n=n -> pe... |
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... | #C | C | using System;
class ColumnAlignerProgram
{
delegate string Justification(string s, int width);
static string[] AlignColumns(string[] lines, Justification justification)
{
const char Separator = '$';
// build input table and calculate columns count
string[][] table = new string[line... |
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... | #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | Block[{start = SessionTime[], K, t0 = 0, t1, kt0, S = 0},
K[t_] = Sin[2 Pi f t] /. f -> 0.5; kt0 = K[t0];
While[True, t1 = SessionTime[] - start;
S += (kt0 + (kt0 = K[t1])) (t1 - t0)/2; t0 = t1;
If[t1 > 2, K[t_] = 0; If[t1 > 2.5, Break[]]]]; S] |
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... | #Nim | Nim |
# Active object.
# Compile with "nim c --threads:on".
import locks
import os
import std/monotimes
type
# Function to use for integration.
TimeFunction = proc (t: float): float {.gcsafe.}
# Integrator object.
Integrator = ptr TIntegrator
TIntegrator = object
k: TimeFunction # The ... |
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... | #Picat | Picat | divisor_sum(N) = R =>
Total = 1,
Power = 2,
% Deal with powers of 2 first
while (N mod 2 == 0)
Total := Total + Power,
Power := Power*2,
N := N div 2
end,
% Odd prime factors up to the square root
P = 3,
while (P*P =< N)
Sum = 1,
Power1 = 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 ... | #JavaScript | JavaScript | var i, p, pascal, primerow, primes, show, _i;
pascal = function() {
var a;
a = [];
return function() {
var b, i;
if (a.length === 0) {
return a = [1];
} else {
b = (function() {
var _i, _ref, _results;
_results = [];
for (i = _i = 0, _ref = a.length - 1; 0 <= _ref... |
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.
... | #Processing | Processing | IntList primes = new IntList();
void setup() {
sieve(500);
int count = 0;
for (int i = 2; i < 500; i++) {
if (primes.hasValue(i) && primes.hasValue(sumDigits(i))) {
print(i + " ");
count++;
}
}
println();
print("Number of additive primes less than 500: " + count);
}
int sumDigits(int... |
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.
... | #PureBasic | PureBasic | #MAX=500
Global Dim P.b(#MAX) : FillMemory(@P(),#MAX,1,#PB_Byte)
If OpenConsole()=0 : End 1 : EndIf
For n=2 To Sqr(#MAX)+1 : If P(n) : m=n*n : While m<=#MAX : P(m)=0 : m+n : Wend : EndIf : Next
Procedure.i qsum(v.i)
While v : qs+v%10 : v/10 : Wend
ProcedureReturn qs
EndProcedure
For i=2 To #MAX
If P(i) And P(... |
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... | #Perl | Perl | use ntheory qw/factor/;
sub almost {
my($k,$n) = @_;
my $i = 1;
map { $i++ while scalar factor($i) != $k; $i++ } 1..$n;
}
say "$_ : ", join(" ", almost($_,10)) for 1..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
... | #FBSL | FBSL | #APPTYPE CONSOLE
DIM gtc = GetTickCount()
Anagram()
PRINT "Done in ", (GetTickCount() - gtc) / 1000, " seconds"
PAUSE
DYNC Anagram()
#include <windows.h>
#include <stdio.h>
char* sortedWord(const char* word, char* wbuf)
{
char* p1, *p2, *endwrd;
char t;
int swaps;
strcpy(wbuf, word);
endwrd = wb... |
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.
... | #Visual_Basic_.NET | Visual Basic .NET | Module Module1
Function Delta_Bearing(b1 As Decimal, b2 As Decimal) As Decimal
Dim d As Decimal = 0
' Convert bearing to W.C.B
While b1 < 0
b1 += 360
End While
While b1 > 360
b1 -= 360
End While
While b2 < 0
b2 += 360
... |
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... | #Ursala | Ursala | #import std
anagrams = |=tK33lrDSL2SL ~=&& ==+ ~~ -<&
deranged = filter not zip; any ==
#cast %sW
main = leql$^&l deranged anagrams unixdict_dot_txt |
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... | #R | R | fib2 <- function(n) {
(n >= 0) || stop("bad argument")
( function(n) if (n <= 1) 1 else Recall(n-1)+Recall(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
... | #PowerShell | PowerShell |
function Get-ProperDivisorSum ( [int]$N )
{
$Sum = 1
If ( $N -gt 3 )
{
$SqrtN = [math]::Sqrt( $N )
ForEach ( $Divisor1 in 2..$SqrtN )
{
$Divisor2 = $N / $Divisor1
If ( $Divisor2 -is [int] ) { $Sum += $Divisor1 + $Divisor2 }
}
... |
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.
| #SequenceL | SequenceL | import <Utilities/Sequence.sl>;
import <Utilities/Conversion.sl>;
import <Utilities/Math.sl>;
//region Types
Point ::= (x: int(0), y: int(0));
Color ::= (red: int(0), green: int(0), blue: int(0));
Image ::= (kind: char(1), iColor: Color(0), vert1: Point(0), vert2: Point(0), vert3: Point(0), center: Point(0),
... |
http://rosettacode.org/wiki/Amb | Amb | Define and give an example of the Amb operator.
The Amb operator (short for "ambiguous") expresses nondeterminism. This doesn't refer to randomness (as in "nondeterministic universe") but is closely related to the term as it is used in automata theory ("non-deterministic finite automaton").
The Amb operator takes a v... | #Nim | Nim | import sugar, strutils
proc amb(comp: proc(a, b: string): bool,
options: seq[seq[string]],
prev: string = ""): seq[string] =
if options.len == 0: return @[]
for opt in options[0]:
# If this is the base call, prev is nil and we need to continue.
if prev.len != 0 and not comp(prev, opt... |
http://rosettacode.org/wiki/Accumulator_factory | Accumulator factory | A problem posed by Paul Graham is that of creating a function that takes a single (numeric) argument and which returns another function that is an accumulator. The returned accumulator function in turn also takes a single numeric argument, and returns the sum of all the numeric values passed in so far to that accumulat... | #Forth | Forth | : accumulator
create ( n -- ) ,
does> ( n -- acc+n ) tuck +! @ ;
0 accumulator foo
1 foo . \ 1
2 foo . \ 3
3 foo . \ 6 |
http://rosettacode.org/wiki/Accumulator_factory | Accumulator factory | A problem posed by Paul Graham is that of creating a function that takes a single (numeric) argument and which returns another function that is an accumulator. The returned accumulator function in turn also takes a single numeric argument, and returns the sum of all the numeric values passed in so far to that accumulat... | #Fortran | Fortran | #define foo(type,g,nn) \
typex function g(i);\
typex i,s,n;\
data s,n/0,nn/;\
s=s+i;\
g=s+n;\
end
foo(real,x,1)
foo(integer,y,3)
program acc
real x, temp
integer y, itemp
temp = x(5.0)
print *, x(2.3)
itemp = y(5)
print *, y(2)
stop
end |
http://rosettacode.org/wiki/Ackermann_function | Ackermann function | The Ackermann function is a classic example of a recursive function, notable especially because it is not a primitive recursive function. It grows very quickly in value, as does the size of its call tree.
The Ackermann function is usually defined as follows:
A
(
m
,
n
)
=
{
n
+
1
if
m
=
0
A
(
m
... | #ALGOL_68 | ALGOL 68 | PROC test ackermann = VOID:
BEGIN
PROC ackermann = (INT m, n)INT:
BEGIN
IF m = 0 THEN
n + 1
ELIF n = 0 THEN
ackermann (m - 1, 1)
ELSE
ackermann (m - 1, ackermann (m, n - 1))
FI
END # ackermann #;
FOR m FROM 0 TO 3 DO
FOR n FROM 0 TO 6 DO
p... |
http://rosettacode.org/wiki/Abundant,_deficient_and_perfect_number_classifications | Abundant, deficient and perfect number classifications | These define three classifications of positive integers based on their proper divisors.
Let P(n) be the sum of the proper divisors of n where the proper divisors are all positive divisors of n other than n itself.
if P(n) < n then n is classed as deficient (OEIS A005100).
if P(n)... | #Befunge | Befunge | p0"2":*8*>::2/\:2/\28*:*:**+>::28*:*:*/\28*:*:*%%#v_\:28*:*:*%v>00p:0`\0\`-1v
++\1-:1`#^_$:28*:*:*/\28*vv_^#<<<!%*:*:*82:-1\-1\<<<\+**:*:*82<+>*:*:**\2-!#+
v"There are "0\g00+1%*:*:<>28*:*:*/\28*:*:*/:0\`28*:*:**+-:!00g^^82!:g01\p01<
>:#,_\." ,tneicifed">:#,_\." dna ,tcefrep">:#,_\.55+".srebmun tnadnuba">:#,_@ |
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... | #C.23 | C# | using System;
class ColumnAlignerProgram
{
delegate string Justification(string s, int width);
static string[] AlignColumns(string[] lines, Justification justification)
{
const char Separator = '$';
// build input table and calculate columns count
string[][] table = new string[line... |
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... | #ooRexx | ooRexx |
integrater = .integrater~new(.routines~sine) -- start the integrater function
call syssleep 2
integrater~input = .routines~zero -- update the integrater function
call syssleep .5
say integrater~output
integrater~stop -- terminate the updater thread
::class integrater
::method init
expose... |
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... | #OxygenBasic | OxygenBasic |
double MainTime
'===============
class RingMaster
'===============
'
indexbase 1
sys List[512] 'limit of 512 objects per ringmaster
sys max,acts
'
method Register(sys meth,obj) as sys
sys i
for i=1 to max step 2
if list[i]=0 then exit for 'vacant slot
next
if i>=max then max+=2
List[i]<=meth,obj
ret... |
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... | #PowerShell | PowerShell | function Get-NextAliquot ( [int]$X )
{
If ( $X -gt 1 )
{
$NextAliquot = 0
(1..($X/2)).Where{ $x % $_ -eq 0 }.ForEach{ $NextAliquot += $_ }.Where{ $_ }
return $NextAliquot
}
}
function Get-AliquotSequence ( [int]$K, [int]$N )
{
$X = $K
$X
(1..($N-1)).... |
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 ... | #jq | jq | # add_pairs is a helper function for optpascal/0
# Input: an OptPascal array
# Output: the next OptPascal array (obtained by adding adjacent items,
# but if the last two items are unequal, then their sum is repeated)
def add_pairs:
if length <= 1 then .
elif length == 2 then (.[0] + .[1]) as $S
| if (.[0] == .[1... |
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.
... | #Python | Python | def is_prime(n: int) -> bool:
if n <= 3:
return n > 1
if n % 2 == 0 or n % 3 == 0:
return False
i = 5
while i ** 2 <= n:
if n % i == 0 or n % (i + 2) == 0:
return False
i += 6
return True
def digit_sum(n: int) -> int:
sum = 0
while n > 0:
... |
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... | #Phixmonti | Phixmonti | /# Rosetta Code problem: http://rosettacode.org/wiki/Almost_prime
by Galileo, 06/2022 #/
include ..\Utilitys.pmt
def test tps over mod not enddef
def kprime?
>ps >ps
0 ( 2 tps ) for
test while
tps over / int ps> drop >ps
swap 1 + swap
test endwhile
dro... |
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... | #Picat | Picat | go =>
N = 10,
Ps = primes(100).take(N),
println(1=Ps),
T = Ps,
foreach(K in 2..5)
T := mul_take(Ps,T,N),
println(K=T)
end,
nl,
foreach(K in 6..25)
T := mul_take(Ps,T,N),
println(K=T)
end,
nl.
% take first N values of L1 x L2
mul_take(L1,L2,N) = [I*J : I in L1, J in L2, I<=J].sort_... |
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
... | #Factor | Factor | "resource:unixdict.txt" utf8 file-lines
[ [ natural-sort >string ] keep ] { } map>assoc sort-keys
[ [ first ] compare +eq+ = ] monotonic-split
dup 0 [ length max ] reduce '[ length _ = ] filter [ values ] map . |
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.
... | #Vlang | Vlang | import math
type Bearing = f64
const test_cases = [
[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],
]
fn main() {
for tc in test_cases {
p... |
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.
... | #Wren | Wren | var subtract = Fn.new { |b1, b2|
var d = (b2 - b1) % 360
if (d < -180) d = d + 360
if (d >= 180) d = d - 360
return (d * 10000).round / 10000 // to 4dp
}
var pairs = [
[ 20, 45],
[-45, 45],
[-85, 90],
[-95, 90],
[-45, 125],
[-45, 145],
[ 29.4803, -88.6381],
[-78.3... |
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... | #VBA | VBA | Sub Main_DerangedAnagrams()
Dim ListeWords() As String, Book As String, i As Long, j As Long, tempLen As Integer, MaxLen As Integer, tempStr As String, IsDeranged As Boolean, count As Integer, bAnag As Boolean
Dim t As Single
t = Timer
Book = Read_File("C:\Users\" & Environ("Username") & "\Desktop\unixdict.txt")
... |
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... | #Racket | Racket |
#lang racket
;; Natural -> Natural
;; Calculate factorial
(define (fact n)
(define (fact-helper n acc)
(if (= n 0)
acc
(fact-helper (sub1 n) (* n acc))))
(unless (exact-nonnegative-integer? n)
(raise-argument-error 'fact "natural" n))
(fact-helper n 1))
;; Unit tests, works in v5.3 a... |
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
... | #Prolog | Prolog | divisor(N, Divisor) :-
UpperBound is round(sqrt(N)),
between(1, UpperBound, D),
0 is N mod D,
(
Divisor = D
;
LargerDivisor is N/D,
LargerDivisor =\= D,
Divisor = LargerDivisor
).
proper_divisor(N, D) :-
divisor(N, D),
D =\= N.
assoc_num_divsSum_in_ran... |
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.
| #Sidef | Sidef | require('Tk')
var root = %s<MainWindow>.new('-title' => 'Pendulum Animation')
var canvas = root.Canvas('-width' => 320, '-height' => 200)
canvas.createLine( 0, 25, 320, 25, '-tags' => <plate>, '-width' => 2, '-fill' => :grey50)
canvas.createOval(155, 20, 165, 30, '-tags' => <pivot outline>, '-fi... |
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... | #OCaml | OCaml | let set_1 = ["the"; "that"; "a"]
let set_2 = ["frog"; "elephant"; "thing"]
let set_3 = ["walked"; "treaded"; "grows"]
let set_4 = ["slowly"; "quickly"]
let combs ll =
let rec aux acc = function
| [] -> (List.map List.rev acc)
| hd::tl ->
let acc =
List.fold_left
(fun _ac l ->
... |
http://rosettacode.org/wiki/Accumulator_factory | Accumulator factory | A problem posed by Paul Graham is that of creating a function that takes a single (numeric) argument and which returns another function that is an accumulator. The returned accumulator function in turn also takes a single numeric argument, and returns the sum of all the numeric values passed in so far to that accumulat... | #FreeBASIC | FreeBASIC | ' FB 1.05.0 Win64
' uses overloaded methods to deal with the integer/float aspect (long and single are both 4 bytes)
Type Bar
Public:
Declare Constructor(As Long)
Declare Constructor(As Single)
Declare Function g(As Long) As Long
Declare Function g(As Single) As Single
Private:
As Single su... |
http://rosettacode.org/wiki/Ackermann_function | Ackermann function | The Ackermann function is a classic example of a recursive function, notable especially because it is not a primitive recursive function. It grows very quickly in value, as does the size of its call tree.
The Ackermann function is usually defined as follows:
A
(
m
,
n
)
=
{
n
+
1
if
m
=
0
A
(
m
... | #ALGOL_W | ALGOL W | begin
integer procedure ackermann( integer value m,n ) ;
if m=0 then n+1
else if n=0 then ackermann(m-1,1)
else ackermann(m-1,ackermann(m,n-1));
for m := 0 until 3 do begin
write( ackermann( m, 0 ) );
for n := 1 until 6 do writeon( ackermann( m, n ) );
end for_m
en... |
http://rosettacode.org/wiki/Abundant,_deficient_and_perfect_number_classifications | Abundant, deficient and perfect number classifications | These define three classifications of positive integers based on their proper divisors.
Let P(n) be the sum of the proper divisors of n where the proper divisors are all positive divisors of n other than n itself.
if P(n) < n then n is classed as deficient (OEIS A005100).
if P(n)... | #Bracmat | Bracmat | ( clk$:?t0
& ( multiples
= prime multiplicity
. !arg:(?prime.?multiplicity)
& !multiplicity:0
& 1
| !prime^!multiplicity*(.!multiplicity)
+ multiples$(!prime.-1+!multiplicity)
)
& ( P
= primeFactors prime exp poly S
. !arg^1/67:?primeFactors
& ( !primeFactor... |
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... | #C.2B.2B | C++ |
(ns rosettacode.align-columns
(:require [clojure.contrib.string :as str]))
(def data "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$s... |
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... | #Oz | Oz | declare
fun {Const X}
fun {$ _} X end
end
fun {Now}
{Int.toFloat {Property.get 'time.total'}} / 1000.0
end
class Integrator from Time.repeat
attr
k:{Const 0.0}
s:0.0
t1 k_t1
t2 k_t2
meth init(SampleIntervalMS)
t1 := {Now}
k_t1 := {@k @t... |
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... | #Prolog | Prolog | % See https://en.wikipedia.org/wiki/Divisor_function
divisor_sum(N, Total):-
divisor_sum_prime(N, 2, 2, Total1, 1, N1),
divisor_sum(N1, 3, Total, Total1).
divisor_sum(1, _, Total, Total):-
!.
divisor_sum(N, Prime, Total, Running_total):-
Prime * Prime =< N,
!,
divisor_sum_prime(N, Prime, Prime... |
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 ... | #Julia | Julia |
function polycoefs(n::Int64)
pc = typeof(n)[]
if n < 0
return pc
end
sgn = one(n)
for k in n:-1:0
push!(pc, sgn*binomial(n, k))
sgn = -sgn
end
return pc
end
|
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.
... | #Quackery | Quackery | 500 eratosthenes
[]
500 times
[ i^ isprime if
[ i^ 10 digitsum
isprime if
[ i^ join ] ] ]
dup echo cr cr
size echo say " additive primes found." |
http://rosettacode.org/wiki/Additive_primes | Additive primes | Definitions
In mathematics, additive primes are prime numbers for which the sum of their decimal digits are also primes.
Task
Write a program to determine (and show here) all additive primes less than 500.
Optionally, show the number of additive primes.
Also see
the OEIS entry: A046704 additive primes.
... | #Racket | Racket | #lang racket
(require math/number-theory)
(define (sum-of-digits n (σ 0))
(if (zero? n) σ (let-values (((q r) (quotient/remainder n 10)))
(sum-of-digits q (+ σ r)))))
(define (additive-prime? n)
(and (prime? n) (prime? (sum-of-digits n))))
(define additive-primes<500 (filter additive-pri... |
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.
... | #Raku | Raku | unit sub MAIN ($limit = 500);
say "{+$_} additive primes < $limit:\n{$_».fmt("%" ~ $limit.chars ~ "d").batch(10).join("\n")}",
with ^$limit .grep: { .is-prime and .comb.sum.is-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... | #PL.2FI | PL/I | almost_prime: procedure options(main);
kprime: procedure(nn, k) returns(bit);
declare (n, nn, k, p, f) fixed;
f = 0;
n = nn;
do p=2 repeat(p+1) while(f<k & p*p <= n);
do n=n repeat(n/p) while(mod(n,p) = 0);
f = f+1;
end;
end;
re... |
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
... | #FreeBASIC | FreeBASIC | ' FB 1.05.0 Win64
Type IndexedWord
As String word
As Integer index
End Type
' selection sort, quick enough for sorting small number of letters
Sub sortWord(s As String)
Dim As Integer i, j, m, n = Len(s)
For i = 0 To n - 2
m = i
For j = i + 1 To n - 1
If s[j] < s[m] Then m = j
Next j
I... |
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.
... | #XBS | XBS | settype Bearing = {Angle:number}
class Bearing {
private method construct(Angle:number=0)
self.Angle=(((Angle%360)+540)%360)-180;
method ToString():string
send tostring(math.nround(self.Angle,4))+"°";
private method __sub(b2:Bearing):Bearing{
send new Bearing(self.Angle-b2.Angle);
}
}
c... |
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... | #Vlang | Vlang | import os
fn deranged(a string, b string) bool {
if a.len != b.len {
return false
}
for i in 0..a.len {
if a[i] == b[i] { return false }
}
return true
}
fn main(){
words := os.read_lines('unixdict.txt')?
mut m := map[string][]string{}
mut best_len, mut w1, mut w2 := 0, '',''
for w in word... |
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... | #Raku | Raku | sub fib($n) {
die "Naughty fib" if $n < 0;
return {
$_ < 2
?? $_
!! &?BLOCK($_-1) + &?BLOCK($_-2);
}($n);
}
say fib(10); |
http://rosettacode.org/wiki/Amicable_pairs | Amicable pairs | Two integers
N
{\displaystyle N}
and
M
{\displaystyle M}
are said to be amicable pairs if
N
≠
M
{\displaystyle N\neq M}
and the sum of the proper divisors of
N
{\displaystyle N}
(
s
u
m
(
p
r
o
p
D
i
v
s
(
N
)
)
{\displaystyle \mathrm {sum} (\mathrm {propDivs} (N))}
)
=
M
... | #PureBasic | PureBasic |
EnableExplicit
Procedure.i SumProperDivisors(Number)
If Number < 2 : ProcedureReturn 0 : EndIf
Protected i, sum = 0
For i = 1 To Number / 2
If Number % i = 0
sum + i
EndIf
Next
ProcedureReturn sum
EndProcedure
Define n, f
Define Dim sum(19999)
If OpenConsole()
For n = 1 To 19999
su... |
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.
| #smart_BASIC | smart BASIC | 'Pendulum
'By Dutchman
' --- constants
g=9.81 ' accelleration of gravity
l=1 ' length of pendulum
GET SCREEN SIZE sw,sh
pivotx=sw/2
pivoty=150
' --- initialise graphics
GRAPHICS
DRAW COLOR 1,0,0
FILL COLOR 0,0,1
DRAW SIZE 2
' --- initialise pendulum
theta=1 ' initial displacement in radians
speed=0
' --- loop
DO
bobx... |
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... | #OpenEdge.2FProgress | OpenEdge/Progress | DEF VAR cset AS CHAR EXTENT 4 INIT [
"the,that,a",
"frog,elephant,thing",
"walked,treaded,grows",
"slowly,quickly"
].
FUNCTION getAmb RETURNS CHARACTER (
i_cwords AS CHAR,
i_iset AS INT
):
DEF VAR cresult AS CHAR.
DEF VAR ii AS INT.
DEF VAR cword AS CHAR.
DO ii = ... |
http://rosettacode.org/wiki/Accumulator_factory | Accumulator factory | A problem posed by Paul Graham is that of creating a function that takes a single (numeric) argument and which returns another function that is an accumulator. The returned accumulator function in turn also takes a single numeric argument, and returns the sum of all the numeric values passed in so far to that accumulat... | #Go | Go | package main
import "fmt"
func accumulator(sum interface{}) func(interface{}) interface{} {
return func(nv interface{}) interface{} {
switch s := sum.(type) {
case int:
switch n := nv.(type) {
case int:
sum = s + n
case float64:
... |
http://rosettacode.org/wiki/Ackermann_function | Ackermann function | The Ackermann function is a classic example of a recursive function, notable especially because it is not a primitive recursive function. It grows very quickly in value, as does the size of its call tree.
The Ackermann function is usually defined as follows:
A
(
m
,
n
)
=
{
n
+
1
if
m
=
0
A
(
m
... | #APL | APL | ackermann←{
0=1⊃⍵:1+2⊃⍵
0=2⊃⍵:∇(¯1+1⊃⍵)1
∇(¯1+1⊃⍵),∇(1⊃⍵),¯1+2⊃⍵
} |
http://rosettacode.org/wiki/Abundant,_deficient_and_perfect_number_classifications | Abundant, deficient and perfect number classifications | These define three classifications of positive integers based on their proper divisors.
Let P(n) be the sum of the proper divisors of n where the proper divisors are all positive divisors of n other than n itself.
if P(n) < n then n is classed as deficient (OEIS A005100).
if P(n)... | #C | C |
#include<stdio.h>
#define de 0
#define pe 1
#define ab 2
int main(){
int sum = 0, i, j;
int try_max = 0;
//1 is deficient by default and can add it deficient list
int count_list[3] = {1,0,0};
for(i=2; i <= 20000; i++){
//Set maximum to check for proper division
try_max = i/2;
//1 is in all proper divis... |
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... | #Clojure | Clojure |
(ns rosettacode.align-columns
(:require [clojure.contrib.string :as str]))
(def data "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$s... |
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... | #Perl | Perl | #!/usr/bin/perl
use strict;
use 5.10.0;
package Integrator;
use threads;
use threads::shared;
sub new {
my $cls = shift;
my $obj = bless { t => 0,
sum => 0,
ref $cls ? %$cls : (),
stop => 0,
tid => 0,
func => shift,
}, ref $cls || $cls;
share($obj->{sum});
share($obj->{stop});
$obj... |
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... | #Python | Python | from proper_divisors import proper_divs
from functools import lru_cache
@lru_cache()
def pdsum(n):
return sum(proper_divs(n))
def aliquot(n, maxlen=16, maxterm=2**47):
if n == 0:
return 'terminating', [0]
s, slen, new = [n], 1, n
while slen <= maxlen and new < maxterm:
new = pds... |
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 ... | #Kotlin | Kotlin | // version 1.1
fun binomial(n: Int, k: Int): Long = when {
n < 0 || k < 0 -> throw IllegalArgumentException("negative numbers not allowed")
k == 0 -> 1L
k == n -> 1L
else -> {
var prod = 1L
var div = 1L
for (i in 1..k) {
prod *= (n + 1 - i... |
http://rosettacode.org/wiki/Additive_primes | Additive primes | Definitions
In mathematics, additive primes are prime numbers for which the sum of their decimal digits are also primes.
Task
Write a program to determine (and show here) all additive primes less than 500.
Optionally, show the number of additive primes.
Also see
the OEIS entry: A046704 additive primes.
... | #Red | Red |
cross-sum: function [n][out: 0 foreach m form n [out: out + to-integer to-string m]]
additive-primes: function [n][collect [foreach p ps: primes n [if find ps cross-sum p [keep p]]]]
length? probe new-line/skip additive-primes 500 true 10
[
2 3 5 7 11 23 29 41 43 47
61 67 83 89 101 113 131 137 139 151
... |
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.
... | #REXX | REXX | /*REXX program counts/displays the number of additive primes under a specified number N.*/
parse arg n cols . /*get optional number of primes to find*/
if n=='' | n=="," then n= 500 /*Not specified? Then assume default.*/
if cols=='' | cols=="," then cols= 10 ... |
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... | #PL.2FM | PL/M | 100H:
BDOS: PROCEDURE (FN, ARG); DECLARE FN BYTE, ARG ADDRESS; GO TO 5; END BDOS;
EXIT: PROCEDURE; CALL BDOS(0,0); END EXIT;
PRINT: PROCEDURE (S); DECLARE S ADDRESS; CALL BDOS(9,S); END PRINT;
PRINT$NUMBER: PROCEDURE (N);
DECLARE S (4) BYTE INITIAL ('...$');
DECLARE P ADDRESS, (N, C BASED P) BYTE;
P = .S(... |
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... | #Phix | Phix | sequence res = columnize({tagset(5)}) -- ie {{1},{2},{3},{4},{5}}
integer n = 2, found = 0
while found<50 do
integer l = length(prime_factors(n,true))
if l<=5 and length(res[l])<=10 then
res[l] &= n
found += 1
end if
n += 1
end while
string fmt = "k = %d: "&join(repeat("%4d",10))&"\n"
fo... |
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
... | #Frink | Frink |
d = new dict
for w = lines["http://wiki.puzzlers.org/pub/wordlists/unixdict.txt"]
{
sorted = sort[charList[w]]
d.addToList[sorted, w]
}
most = sort[toArray[d], {|a,b| length[b@1] <=> length[a@1]}]
longest = length[most@0@1]
i = 0
while length[most@i@1] == longest
{
println[most@i@1]
i = i + 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.
... | #XPL0 | XPL0 | real B1, B2, Ang;
[Text(0, " Bearing 1 Bearing 2 Difference");
loop [B1:= RlIn(1);
B2:= RlIn(1);
Ang:= B2 - B1;
while Ang > 180. do Ang:= Ang - 360.;
while Ang < -180. do Ang:= Ang + 360.;
CrLf(0);
RlOut(0, B1); ChOut(0, 9);
RlOut(0, B2); ChOu... |
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.
... | #Yabasic | Yabasic | // Rosetta Code problem: http://rosettacode.org/wiki/Angle_difference_between_two_bearings
// by Jjuanhdez, 06/2022
print "Input in -180 to +180 range:"
getDifference(20.0, 45.0)
getDifference(-45.0, 45.0)
getDifference(-85.0, 90.0)
getDifference(-95.0, 90.0)
getDifference(-45.0, 125.0)
getDifference(-45.0, 145.0)
ge... |
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... | #Wren | Wren | import "io" for File
import "/sort" for Sort
// assumes w1 and w2 are anagrams of each other
var isDeranged = Fn.new { |w1, w2|
for (i in 0...w1.count) {
if (w1[i] == w2[i]) return false
}
return true
}
var words = File.read("unixdict.txt").split("\n").map { |w| w.trim() }
var wordMap = {}
for (... |
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... | #REBOL | REBOL |
fib: func [n /f][ do f: func [m] [ either m < 2 [m][(f m - 1) + f m - 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
... | #Python | Python | from proper_divisors import proper_divs
def amicable(rangemax=20000):
n2divsum = {n: sum(proper_divs(n)) for n in range(1, rangemax + 1)}
for num, divsum in n2divsum.items():
if num < divsum and divsum <= rangemax and n2divsum[divsum] == num:
yield num, divsum
if __name__ == '__main__':
... |
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.
| #Tcl | Tcl | package require Tcl 8.5
package require Tk
# Make the graphical entities
pack [canvas .c -width 320 -height 200] -fill both -expand 1
.c create line 0 25 320 25 -width 2 -fill grey50 -tags plate
.c create line 1 1 1 1 -tags rod -width 3 -fill black
.c create oval 1 1 2 2 -tags bob -fill yellow -outline black
.c creat... |
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... | #Oz | Oz | declare
fun {Amb Xs}
case Xs of nil then fail
[] [X] then X
[] X|Xr then
choice X
[] {Amb Xr}
end
end
end
fun {Example}
W1 = {Amb ["the" "that" "a"]}
W2 = {Amb ["frog" "elephant" "thing"]}
W3 = {Amb ["walked" "treaded" "grows"]}
W4 = {Amb ["slowl... |
http://rosettacode.org/wiki/Accumulator_factory | Accumulator factory | A problem posed by Paul Graham is that of creating a function that takes a single (numeric) argument and which returns another function that is an accumulator. The returned accumulator function in turn also takes a single numeric argument, and returns the sum of all the numeric values passed in so far to that accumulat... | #Golo | Golo | #!/usr/bin/env golosh
----
An accumulator factory example for Rosetta Code.
This one uses the box function to create an AtomicReference.
----
module rosetta.AccumulatorFactory
function accumulator = |n| {
let number = box(n)
return |i| -> number: accumulateAndGet(i, |a, b| -> a + b)
}
function main = |args| {
... |
http://rosettacode.org/wiki/Accumulator_factory | Accumulator factory | A problem posed by Paul Graham is that of creating a function that takes a single (numeric) argument and which returns another function that is an accumulator. The returned accumulator function in turn also takes a single numeric argument, and returns the sum of all the numeric values passed in so far to that accumulat... | #Groovy | Groovy | def accumulator = { Number n ->
def value = n;
{ it = 0 -> value += it}
} |
Subsets and Splits
Rosetta Code COBOL Python Hard Tasks
Identifies and retrieves challenging tasks that exist in both COBOL and Python, revealing cross-language programming patterns and difficulty levels for comparative analysis.
Rosetta Code Task Comparisons
Identifies tasks common to both COBOL and Python languages that are described as having difficulty levels, revealing cross-language task similarities and providing useful comparative programming examples.
Select Specific Languages Codes
Retrieves specific programming language names and codes from training data, providing basic filtering but limited analytical value beyond identifying these particular languages.