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/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... | #D | D | import std.stdio;
void main() {
auto x = acc(1);
x(5);
acc(3);
writeln(x(2.3));
}
auto acc(U = real, T)(T initvalue) { // U is type of the accumulator
auto accum = cast(U)initvalue ;
return (U n) { return accum += n ; } ;
} |
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... | #Dart | Dart | makeAccumulator(s) => (n) => s += n; |
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
... | #AArch64_Assembly | AArch64 Assembly |
/* ARM assembly AARCH64 Raspberry PI 3B or android 64 bits */
/* program ackermann64.s */
/*******************************************/
/* Constantes file */
/*******************************************/
/* for this file see task include a file in language AArch64 assembly*/
.include "..... |
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)... | #ARM_Assembly | ARM Assembly |
/* ARM assembly Raspberry PI */
/* program numberClassif.s */
/* REMARK 1 : this program use routines in a include file
see task Include a file language arm assembly
for the routine affichageMess conversion10
see at end of this program the instruction include */
/* for constantes see task include a ... |
http://rosettacode.org/wiki/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... | #AWK | AWK |
# syntax: GAWK -f ALIGN_COLUMNS.AWK ALIGN_COLUMNS.TXT
BEGIN {
colsep = " " # separator between columns
report("raw data")
}
{ printf("%s\n",$0)
arr[NR] = $0
n = split($0,tmp_arr,"$")
for (j=1; j<=n; j++) {
width = max(width,length(tmp_arr[j]))
}
}
END {
report("left justified")
... |
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... | #Groovy | Groovy | /**
* Integrates input function K over time
* S + (t1 - t0) * (K(t1) + K(t0)) / 2
*/
class Integrator {
interface Function {
double apply(double timeSinceStartInSeconds)
}
private final long start
private volatile boolean running
private Function func
private double t0
private... |
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... | #Mathematica_.2F_Wolfram_Language | Mathematica / Wolfram Language | seq[n_] :=
NestList[If[# == 0, 0,
DivisorSum[#, # &, Function[div, div != #]]] &, n, 16];
class[seq_] :=
Which[Length[seq] < 2, "Non-terminating", MemberQ[seq, 0],
"Terminating", seq[[1]] == seq[[2]], "Perfect",
Length[seq] > 2 && seq[[1]] == seq[[3]], "Amicable",
Length[seq] > 3 && MemberQ[seq[... |
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 |... | #VBA | VBA | Option Explicit
Declare Sub GetMem1 Lib "msvbvm60" (ByVal ptr As Long, ByRef x As Byte)
Declare Sub GetMem2 Lib "msvbvm60" (ByVal ptr As Long, ByRef x As Integer)
Declare Sub GetMem4 Lib "msvbvm60" (ByVal ptr As Long, ByRef x As Long)
Declare Sub PutMem1 Lib "msvbvm60" (ByVal ptr As Long, ByVal x As Byte)
Declare Sub P... |
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 |... | #Visual_Basic_.NET | Visual Basic .NET | Dim x = 5
Dim ptrX As IntPtr
ptrX = Marshal.AllocHGlobal(Marshal.SizeOf(GetType(Integer)))
Marshal.StructureToPtr(5, ptrX, False)
Dim addressX = ptrX.ToInt64
|
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 |... | #Wart | Wart | addr.x
=> 27975840 |
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 ... | #FreeBASIC | FreeBASIC | 'METHOD -- Use the Pascal triangle to retrieve the coefficients
'UPPER LIMIT OF FREEBASIC ULONGINT GETS PRIMES UP TO 70
Sub string_split(s_in As String,char As String,result() As String)
Dim As String s=s_in,var1,var2
Dim As Integer n,pst
#macro split(stri,char,var1,var2)
pst=Instr(stri,char)
var1="... |
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.
... | #Pascal | Pascal | program AdditivePrimes;
{$IFDEF FPC}
{$MODE DELPHI}{$CODEALIGN proc=16}
{$ELSE}
{$APPTYPE CONSOLE}
{$ENDIF}
{$DEFINE DO_OUTPUT}
uses
sysutils;
const
RANGE = 500; // 1000*1000;//
MAX_OFFSET = 0; // 1000*1000*1000;//
type
tNum = array [0 .. 15] of byte;
tNumSum = record
dgtNum, dgtSum: tNum;
dgt... |
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... | #Maple | Maple | AlmostPrimes:=proc(k, numvalues::posint:=10)
local aprimes, i, intfactors;
aprimes := Array([]);
i := 0;
do
i := i + 1;
intfactors := ifactors(i)[2];
intfactors := [seq(seq(intfactors[i][1], j=1..intfactors[i][2]),i = 1..numelems(intfactors))];
if numelems(intfactors) =... |
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... | #MAD | MAD | NORMAL MODE IS INTEGER
INTERNAL FUNCTION(NN,KK)
ENTRY TO KPRIME.
F = 0
N = NN
THROUGH SCAN, FOR P=2, 1, F.GE.KK .OR. P*P.G.N
DIV WHENEVER N.E.N/P*P
N = N/P
F = F+1
TRANSFER TO 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
... | #Elixir | Elixir | defmodule Anagrams do
def find(file) do
File.read!(file)
|> String.split
|> Enum.group_by(fn word -> String.codepoints(word) |> Enum.sort end)
|> Enum.group_by(fn {_,v} -> length(v) end)
|> Enum.max
|> print
end
defp print({_,y}) do
Enum.each(y, fn {_,e} -> Enum.sort(e) |> Enum.joi... |
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.
... | #Scala | Scala | object AngleDifference extends App {
private def getDifference(b1: Double, b2: Double) = {
val r = (b2 - b1) % 360.0
if (r < -180.0) r + 360.0 else if (r >= 180.0) r - 360.0 else r
}
println("Input in -180 to +180 range")
println(getDifference(20.0, 45.0))
println(getDifference(-45.0, 45.0))
print... |
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... | #Scheme | Scheme | (import (scheme base)
(scheme char)
(scheme cxr)
(scheme file)
(scheme write)
(srfi 1) ; lists
(srfi 132)) ; sorting library
;; read in word list, and sort into decreasing length
(define (read-ordered-words)
(with-input-from-file
"unixdict.txt"
(lambda ()
... |
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... | #PostScript | PostScript | % primitive recursion
/pfact {
{1} {*} primrec}.
%linear recursion
/lfact {
{dup 0 eq}
{pop 1}
{dup pred}
{*}
linrec}.
% general recursion
/gfact {
{0 eq}
{succ}
{dup pred}
{i *}
genrec}.
% binary recursion
/fib {
{2 lt} {} {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
... | #Phixmonti | Phixmonti | def sumDivs
var n
1 var sum n sqrt
2 swap 2 tolist
for
var d
n d mod not if
sum d + n d / + var sum
endif
endfor
sum
enddef
2 20000 2 tolist for
var i
i sumDivs var m
m i > if
m sumDivs i == if i print "\t" print m print nl endif
endi... |
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.
| #RLaB | RLaB |
//
// example: solve ODE for pendulum
//
// we first define the first derivative function for the solver
dudt = function(t, u, p)
{
// t-> time
// u->[theta, dtheta/dt ]
// p-> g/L, parameter
rval = zeros(2,1);
rval[1] = u[2];
rval[2] = -p[1] * sin(u[1]);
return rval;
};
// now we solve the problem... |
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... | #Latitude | Latitude | ;; This is the exception that will be thrown if an amb expression is
;; unsatisfiable.
AmbError ::= Exception clone tap {
self message := "Amb expression failed".
AmbError := self.
}.
;; The Amb object itself is primarily for internal use. It stores the
;; "next" backtracking point if an amb expression outr... |
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... | #D.C3.A9j.C3.A0_Vu | Déjà Vu | accum n:
labda i:
set :n + n i
n
local :x accum 1
drop x 5
drop accum 3
!print x 2.3 |
http://rosettacode.org/wiki/Accumulator_factory | Accumulator factory | A problem posed by Paul Graham is that of creating a function that takes a single (numeric) argument and which returns another function that is an accumulator. The returned accumulator function in turn also takes a single numeric argument, and returns the sum of all the numeric values passed in so far to that accumulat... | #Delphi | Delphi |
program Accumulator_factory;
{$APPTYPE CONSOLE}
uses
System.SysUtils,
System.Variants;
type
TFn = TFunc<variant, variant>;
function Foo(n: variant): TFn;
begin
Result :=
function(i: variant): variant
begin
n:= n + i;
Result := n;
end;
end;
begin
var x := Foo(1);
x(5);
F... |
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
... | #ABAP | ABAP |
REPORT zhuberv_ackermann.
CLASS zcl_ackermann DEFINITION.
PUBLIC SECTION.
CLASS-METHODS ackermann IMPORTING m TYPE i
n TYPE i
RETURNING value(v) TYPE i.
ENDCLASS. "zcl_ackermann DEFINITION
CLASS zcl_ackermann IMPLEMENTATION.
... |
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)... | #Arturo | Arturo | properDivisors: function [n]->
(factors n) -- n
abundant: new 0 deficient: new 0 perfect: new 0
loop 1..20000 'x [
s: sum properDivisors x
case [s]
when? [<x] -> inc 'deficient
when? [>x] -> inc 'abundant
else -> inc 'perfect
]
print ["Found" abundant "abundant,"
... |
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... | #BaCon | BaCon |
DECLARE in$[] = { "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$spa... |
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... | #Haskell | Haskell | module Integrator (
newIntegrator, input, output, stop,
Time, timeInterval
) where
import Control.Concurrent (forkIO, threadDelay)
import Control.Concurrent.MVar (MVar, newMVar, modifyMVar_, modifyMVar, readMVar)
import Control.Exception (evaluate)
import Data.Time (UTCTime)
import Data.Time.Clock (getCurrentTime, ... |
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... | #Nim | Nim |
import math
import strformat
from strutils import addSep
import times
type
# Classification categories.
Category = enum
Unknown
Terminating = "terminating"
Perfect = "perfect"
Amicable = "amicable"
Sociable = "sociable"
Aspiring = "aspiring"
Cyclic = "cyclic"
NonTerminating = "... |
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 |... | #Wren | Wren | var a = [1, 2, 3, 4]
var b = a // now 'a' and 'b' both point to the same List data
b[3] = 5
System.print("'b' is %(b)")
System.print("'a' is %(a)") // the previous change is of course reflected in 'a' as well
var t = Object.same(a, b) // tells you whether 'a' and 'b' refer to the same object in memory
System.print("... |
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 |... | #X86_Assembly | X86 Assembly | movl my_variable, %eax |
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 |... | #XLISP | XLISP | (%ADDRESS-OF X) |
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 ... | #Go | Go | package main
import "fmt"
func bc(p int) []int64 {
c := make([]int64, p+1)
r := int64(1)
for i, half := 0, p/2; i <= half; i++ {
c[i] = r
c[p-i] = r
r = r * int64(p-i) / int64(i+1)
}
for i := p - 1; i >= 0; i -= 2 {
c[i] = -c[i]
}
return c
}
func main() ... |
http://rosettacode.org/wiki/Additive_primes | Additive primes | Definitions
In mathematics, additive primes are prime numbers for which the sum of their decimal digits are also primes.
Task
Write a program to determine (and show here) all additive primes less than 500.
Optionally, show the number of additive primes.
Also see
the OEIS entry: A046704 additive primes.
... | #Perl | Perl | use strict;
use warnings;
use ntheory 'is_prime';
use List::Util <sum max>;
sub pp {
my $format = ('%' . (my $cw = 1+length max @_) . 'd') x @_;
my $width = ".{@{[$cw * int 60/$cw]}}";
(sprintf($format, @_)) =~ s/($width)/$1\n/gr;
}
my($limit, @ap) = 500;
is_prime($_) and is_prime(sum(split '',$_)) and... |
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.
... | #Phix | Phix | with javascript_semantics
function additive(string p) return is_prime(sum(sq_sub(p,'0'))) end function
sequence res = filter(apply(get_primes_le(500),sprint),additive)
printf(1,"%d additive primes found: %s\n",{length(res),join(shorten(res,"",6))})
|
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... | #Mathematica_.2F_Wolfram_Language | Mathematica / Wolfram Language | kprimes[k_,n_] :=
(* generates a list of the n smallest k-almost-primes *)
Module[{firstnprimes, runningkprimes = {}},
firstnprimes = Prime[Range[n]];
runningkprimes = firstnprimes;
Do[
runningkprimes =
Outer[Times, firstnprimes , runningkprimes ] // Flatten // Union // Take[#, n] & ;
(* only ke... |
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... | #Modula-2 | Modula-2 | MODULE AlmostPrime;
FROM FormatString IMPORT FormatString;
FROM Terminal IMPORT WriteString,WriteLn,ReadChar;
PROCEDURE KPrime(n,k : INTEGER) : BOOLEAN;
VAR p,f : INTEGER;
BEGIN
f := 0;
p := 2;
WHILE (f<k) AND (p*p<=n) DO
WHILE n MOD p = 0 DO
n := n DIV p;
INC(f)
EN... |
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
... | #Erlang | Erlang | -module(anagrams).
-compile(export_all).
play() ->
{ok, P} = file:read_file('unixdict.txt'),
D = dict:new(),
E=fetch(string:tokens(binary_to_list(P), "\n"), D),
get_value(dict:fetch_keys(E), E).
fetch([H|T], D) ->
fetch(T, dict:append(lists:sort(H), H, D));
fetch([], D) ->
D.
get_value(L, ... |
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.
... | #Scheme | Scheme | #!r6rs
(import (rnrs base (6))
(rnrs io simple (6)))
(define (bearing-difference bearing-2 bearing-1)
(- (mod (+ (mod (- bearing-2 bearing-1)
360)
540)
360)
180))
(define (bearing-difference-test)
(define test-cases
'((20 45)
(-45 45)
(-85 ... |
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... | #Sidef | Sidef | func find_deranged(Array a) {
for i in (^a) {
for j in (i+1 .. a.end) {
overlaps(a[i], a[j]) || (
printf("length %d: %s => %s\n", a[i].len, a[i], a[j])
return true
)
}
}
return false
}
func main(File file) {
file.open_r(\var fh,... |
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... | #Prolog | Prolog | :- use_module(lambda).
fib(N, _F) :-
N < 0, !,
write('fib is undefined for negative numbers.'), nl.
fib(N, F) :-
% code of Fibonacci
PF = \Nb^R^Rr1^(Nb < 2 ->
R = Nb
;
N1 is Nb - 1,
N2 is Nb - 2,
call(Rr1,N1,R1,Rr1),
call(Rr1,N2,R2,Rr1),
R is R1 + ... |
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
... | #PHP | PHP | <?php
function sumDivs ($n) {
$sum = 1;
for ($d = 2; $d <= sqrt($n); $d++) {
if ($n % $d == 0) $sum += $n / $d + $d;
}
return $sum;
}
for ($n = 2; $n < 20000; $n++) {
$m = sumDivs($n);
if ($m > $n) {
if (sumDivs($m) == $n) echo $n." ".$m."<br />";
}
}
?> |
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.
| #Ruby | Ruby | require 'tk'
$root = TkRoot.new("title" => "Pendulum Animation")
$canvas = TkCanvas.new($root) do
width 320
height 200
create TkcLine, 0,25,320,25, 'tags' => 'plate', 'width' => 2, 'fill' => 'grey50'
create TkcOval, 155,20,165,30, 'tags' => 'pivot', 'outline' => "", 'fill' => 'grey50'
create TkcLine, 1,1,... |
http://rosettacode.org/wiki/Amb | Amb | Define and give an example of the Amb operator.
The Amb operator (short for "ambiguous") expresses nondeterminism. This doesn't refer to randomness (as in "nondeterministic universe") but is closely related to the term as it is used in automata theory ("non-deterministic finite automaton").
The Amb operator takes a v... | #Lua | Lua | function amb (set)
local workset = {}
if (#set == 0) or (type(set) ~= 'table') then return end
if #set == 1 then return set end
if #set > 2 then
local first = table.remove(set,1)
set = amb(set)
for i,v in next,first do
for j,u in next,set do
if v:byte(... |
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... | #E | E | def foo(var x) {
return fn y { x += y }
} |
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... | #EchoLisp | EchoLisp |
(define-syntax-rule (inc x v) (set! x (+ x v)))
(define (accumulator (sum 0)) (lambda(x) (inc sum x) sum))
(define x (accumulator 1)) → x
(x 5) → 6
;; another closure
(accumulator 3) → (🔒 λ (_x) (📝 #set! sum (#+ sum _x)) sum)
(x 2.3) → 8.3
|
http://rosettacode.org/wiki/Ackermann_function | Ackermann function | The Ackermann function is a classic example of a recursive function, notable especially because it is not a primitive recursive function. It grows very quickly in value, as does the size of its call tree.
The Ackermann function is usually defined as follows:
A
(
m
,
n
)
=
{
n
+
1
if
m
=
0
A
(
m
... | #Action.21 | Action! | DEFINE MAXSIZE="1000"
CARD ARRAY stack(MAXSIZE)
CARD stacksize=[0]
BYTE FUNC IsEmpty()
IF stacksize=0 THEN
RETURN (1)
FI
RETURN (0)
PROC Push(BYTE v)
IF stacksize=maxsize THEN
PrintE("Error: stack is full!")
Break()
FI
stack(stacksize)=v
stacksize==+1
RETURN
BYTE FUNC Pop()
IF IsEmpty() ... |
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)... | #AutoHotkey | AutoHotkey | Loop
{
m := A_index
; getting factors=====================
loop % floor(sqrt(m))
{
if ( mod(m, A_index) == "0" )
{
if ( A_index ** 2 == m )
{
list .= A_index . ":"
sum := sum + A_index
continue
}
... |
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... | #BASIC | BASIC | DATA 6
DATA "Given$a$text$file$of$many$lines,$where$fields$within$a$line$"
DATA "are$delineated$by$a$single$'dollar'$character,$write$a$program"
DATA "that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$"
DATA "column$are$separated$by$at$least$one$space."
DATA "Further,$... |
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... | #J | J | coclass 'activeobject'
require'dates'
create=:setinput NB. constructor
T=:3 :0
if. nc<'T0' do. T0=:tsrep 6!:0'' end.
0.001*(tsrep 6!:0'')-T0
)
F=:G=:0:
Zero=:0
setinput=:3 :0
zero=. getoutput''
'`F ignore'=: y,_:`''
G=: F f.d._1
Zero=: zero-G T ''
getoutput''
)
getoutput=:3 :0
Zero+G T''
) |
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... | #Java | Java | /**
* Integrates input function K over time
* S + (t1 - t0) * (K(t1) + K(t0)) / 2
*/
public class Integrator {
public interface Function {
double apply(double timeSinceStartInSeconds);
}
private final long start;
private volatile boolean running;
private Function func;
private d... |
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... | #Oforth | Oforth | import: mapping
import: quicksort
import: math
Object method: sum ( coll -- m )
#+ self reduce dup ifNull: [ drop 0 ] ;
Integer method: properDivs
| i l |
Array new dup 1 over add ->l
2 self nsqrt tuck for: i [ self i mod ifFalse: [ i l add self i / l add ] ]
sq self == ifTrue: [ l pop drop ]
dup so... |
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 |... | #XPL0 | XPL0 | include c:\cxpl\codes;
int A, B;
[B:= addr A;
HexOut(0, B); CrLf(0);
B(0):= $1234ABCD;
HexOut(0, A); CrLf(0);
] |
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 |... | #Yorick | Yorick | > foo = 1
> bar = &foo
> bar
0x15f42c18
> baz = bar
> *baz = 5
> *bar
5
> *baz
5 |
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 |... | #Z80_Assembly | Z80 Assembly | foo equ &C000
bar equ &C001
ld (foo),a ;store A into memory location &C000
ld a,b ;copy B to A
ld (bar),a ;store "B" into memory location &C001 |
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 |... | #Zig | Zig | const std = @import("std");
pub fn main() !void {
const stdout = std.io.getStdOut().writer();
var i: i32 = undefined;
var address_of_i: *i32 = &i;
try stdout.print("{x}\n", .{@ptrToInt(address_of_i)});
} |
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 ... | #Haskell | Haskell | expand p = scanl (\z i -> z * (p-i+1) `div` i) 1 [1..p]
test p | p < 2 = False
| otherwise = and [mod n p == 0 | n <- init . tail $ expand p]
printPoly [1] = "1"
printPoly p = concat [ unwords [pow i, sgn (l-i), show (p!!(i-1))]
| i <- [l-1,l-2..1] ] where
l = length p
... |
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.
... | #Phixmonti | Phixmonti | /# Rosetta Code problem: http://rosettacode.org/wiki/Additive_primes
by Galileo, 05/2022 #/
include ..\Utilitys.pmt
def isprime
dup 1 <= if drop false
else dup 2 == not if
( dup sqrt 2 swap ) for
over swap mod not if drop false exitfor endif
endfor
endif
endif
fal... |
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.
... | #PicoLisp | PicoLisp | (de prime? (N)
(let D 0
(or
(= N 2)
(and
(> N 1)
(bit? 1 N)
(for (D 3 T (+ D 2))
(T (> D (sqrt N)) T)
(T (=0 (% N D)) NIL) ) ) ) ) )
(de additive (N)
(and
(prime? N)
(prime? (sum format (chop N))) ) )
(let C 0
... |
http://rosettacode.org/wiki/Additive_primes | Additive primes | Definitions
In mathematics, additive primes are prime numbers for which the sum of their decimal digits are also primes.
Task
Write a program to determine (and show here) all additive primes less than 500.
Optionally, show the number of additive primes.
Also see
the OEIS entry: A046704 additive primes.
... | #PILOT | PILOT | C :z=2
:c=0
:max=500
*number
C :n=z
U :*digsum
C :n=s
U :*prime
J (p=0):*next
C :n=z
U :*prime
J (p=0):*next
T :#z
C :c=c+1
*next
C :z=z+1
J (z<max):*number
T :There are #c additive primes below #max
E :
*prime
C :p=1
E (n<4):
C :p=0
E (n=2*(n/2)):
C :i=3
:m=n/2
*ptest
E (n=i*(n/i)):
C :i=i+2
J (i<=m):*ptest
C... |
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... | #Nascom_BASIC | Nascom BASIC |
10 REM Almost prime
20 FOR K=1 TO 5
30 PRINT "k =";STR$(K);":";
40 I=2
50 C=0
60 IF C>=10 THEN 110
70 AN=I:GOSUB 1000
80 IF ISKPRIME=0 THEN 90
82 REM Print I in 4 fields
84 S$=STR$(I)
86 PRINT SPC(4-LEN(S$));S$;
88 C=C+1
90 I=I+1
100 GOTO 60
110 PRINT
120 NEXT K
130 END
995 REM Check if N (AN) is a K prime
1000 F=0
1... |
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... | #Nim | Nim | proc prime(k: int, listLen: int): seq[int] =
result = @[]
var
test: int = 2
curseur: int = 0
while curseur < listLen:
var
i: int = 2
compte = 0
n = test
while i <= n:
if (n mod i)==0:
n = n div i
compte += 1
else:
i += 1
if compte == k:
result.add(test)
curseur += 1
test ... |
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
... | #Euphoria | Euphoria | include sort.e
function compare_keys(sequence a, sequence b)
return compare(a[1],b[1])
end function
constant fn = open("unixdict.txt","r")
sequence words, anagrams
object word
words = {}
while 1 do
word = gets(fn)
if atom(word) then
exit
end if
word = word[1..$-1] -- truncate new-line ch... |
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.
... | #Seed7 | Seed7 | $ include "seed7_05.s7i";
include "float.s7i";
const func float: getDifference (in float: b1, in float: b2) is func
result
var float: difference is 0.0;
begin
difference := (b2 - b1) mod 360.0;
if difference > 180.0 then
difference -:= 360.0;
end if;
end func;
const proc: main is func
... |
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... | #Simula | Simula | ! cim --memory-pool-size=512 deranged-anagrams.sim;
BEGIN
CLASS TEXTVECTOR;
BEGIN
CLASS TEXTARRAY(N); INTEGER N;
BEGIN TEXT ARRAY DATA(1:N);
END TEXTARRAY;
PROCEDURE EXPAND(N); INTEGER N;
BEGIN
INTEGER I;
REF(TEXTARRAY) TEMP;
TEMP :- NEW TEXTARRAY(N);... |
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... | #Python | Python | >>> Y = lambda f: (lambda x: x(x))(lambda y: f(lambda *args: y(y)(*args)))
>>> fib = lambda f: lambda n: None if n < 0 else (0 if n == 0 else (1 if n == 1 else f(n-1) + f(n-2)))
>>> [ Y(fib)(i) for i in range(-2, 10) ]
[None, None, 0, 1, 1, 2, 3, 5, 8, 13, 21, 34] |
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
... | #Picat | Picat | * foreach loop (two variants)
* list comprehension
* while loop.
|
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.
| #Rust | Rust |
// using version 0.107.0 of piston_window
use piston_window::{clear, ellipse, line_from_to, PistonWindow, WindowSettings};
const PI: f64 = std::f64::consts::PI;
const WIDTH: u32 = 640;
const HEIGHT: u32 = 480;
const ANCHOR_X: f64 = WIDTH as f64 / 2. - 12.;
const ANCHOR_Y: f64 = HEIGHT as f64 / 4.;
const ANCHOR_EL... |
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... | #M2000_Interpreter | M2000 Interpreter |
Module AmbFunction {
Function Amb (failure) {
// get an array of s items, return an array of 1 item
// we do this so we forget the type of element
getitem=lambda (n, c) -> {
dim z(1) :link c to c()
stock c(n) keep 1, z(0) // copy from c(n)... |
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... | #Elena | Elena | function(acc)
= (n => acc.append:n);
accumulator(n)
= function(new Variable(n));
public program()
{
var x := accumulator(1);
x(5);
var y := accumulator(3);
console.write(x(2.3r))
} |
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... | #Elixir | Elixir | defmodule AccumulatorFactory do
def new(initial) do
{:ok, pid} = Agent.start_link(fn() -> initial end)
fn (a) ->
Agent.get_and_update(pid, fn(old) -> {a + old, a + old} end)
end
end
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
... | #ActionScript | ActionScript | public function ackermann(m:uint, n:uint):uint
{
if (m == 0)
{
return n + 1;
}
if (n == 0)
{
return ackermann(m - 1, 1);
}
return ackermann(m - 1, ackermann(m, n - 1));
} |
http://rosettacode.org/wiki/Abundant,_deficient_and_perfect_number_classifications | Abundant, deficient and perfect number classifications | These define three classifications of positive integers based on their proper divisors.
Let P(n) be the sum of the proper divisors of n where the proper divisors are all positive divisors of n other than n itself.
if P(n) < n then n is classed as deficient (OEIS A005100).
if P(n)... | #AWK | AWK |
#!/bin/gawk -f
function sumprop(num, i,sum,root) {
if (num == 1) return 0
sum=1
root=sqrt(num)
for ( i=2; i < root; i++) {
if (num % i == 0 )
{
sum = sum + i + num/i
}
}
if (num % root == 0)
{
sum = sum + root
}
return sum
}
BEGIN{
limit = 20000
abundant = 0
defiecient =0
perf... |
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... | #Batch_File | Batch File | @echo off
setlocal enabledelayedexpansion
mode con cols=103
echo Given$a$text$file$of$many$lines,$where$fields$within$a$line$ >file.txt
echo are$delineated$by$a$single$'dollar'$character,$write$a$program! >>file.txt
echo that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$>>file.txt
echo column$are$separ... |
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... | #JavaScript | JavaScript | function Integrator(sampleIntervalMS) {
var inputF = function () { return 0.0 };
var sum = 0.0;
var t1 = new Date().getTime();
var input1 = inputF(t1 / 1000);
function update() {
var t2 = new Date().getTime();
var input2 = inputF(t2 / 1000);
var dt = (t2 - t1) / 1000;
... |
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... | #PARI.2FGP | PARI/GP | aliquot(x) =
{
my (L = List(x), M = Map(Mat([x,1])), k, m = "non-term.", n = x);
for (i = 2, 16, n = vecsum(divisors(n)) - n;
if (n > 2^47, break,
n == 0, m = "terminates"; break,
mapisdefined(M, n, &k),
m = if (k == 1,
if (i == 2, "perfect",
i == 3, "am... |
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 ... | #Idris | Idris | import Data.Vect
-- Computes Binomial Coefficients
binCoef : Nat -> Nat -> Nat
binCoef _ Z = (S Z)
binCoef (S n) (S k) =
if n == k then (S Z) else ((S n) * (binCoef n k)) `div` (S k)
-- Binomial Expansion Of (x - 1)^p
expansion : (n : Nat) -> Vect (S n) Integer
expansion n = expansion' n 1
where
expansi... |
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.
... | #PL.2FI | PL/I | /* 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... | #Objeck | Objeck | class Kth_Prime {
function : native : kPrime(n : Int, k : Int) ~ Bool {
f := 0;
for (p := 2; f < k & p*p <= n; p+=1;) {
while (0 = n % p) {
n /= p; f+=1;
};
};
return f + ((n > 1) ? 1 : 0) = k;
}
function : Main(args : String[]) ~ Nil {
for (k := 1; k <= 5; k+=1;) {
... |
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
... | #F.23 | F# | let xss = Seq.groupBy (Array.ofSeq >> Array.sort) (System.IO.File.ReadAllLines "unixdict.txt")
Seq.map snd xss |> Seq.filter (Seq.length >> ( = ) (Seq.map (snd >> Seq.length) xss |> Seq.max)) |
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.
... | #Sidef | Sidef | func bearingAngleDiff(b1, b2) {
(var b = ((b2 - b1 + 720) % 360)) > 180 ? (b - 360) : b
}
printf("%25s %25s %25s\n", "B1", "B2", "Difference")
printf("%25s %25s %25s\n", "-"*20, "-"*20, "-"*20)
for b1,b2 in ([
20, 45
-45, ... |
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... | #Tcl | Tcl | package require Tcl 8.5
package require http
# Fetch the words
set t [http::geturl "http://www.puzzlers.org/pub/wordlists/unixdict.txt"]
set wordlist [split [http::data $t] \n]
http::cleanup $t
# Group by characters in word
foreach word $wordlist {
dict lappend w [lsort [split $word ""]] [split $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... | #QBasic | QBasic | DECLARE FUNCTION Fibonacci! (num!)
PRINT Fibonacci(20)
PRINT Fibonacci(30)
PRINT Fibonacci(-10)
PRINT Fibonacci(10)
END
FUNCTION Fibonacci (num)
IF num < 0 THEN
PRINT "Invalid argument: ";
Fibonacci = num
END IF
IF num < 2 THEN
Fibonacci = num
ELSE
Fibonacci = Fibonacci(num - 1) + Fibonacc... |
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
... | #PicoLisp | PicoLisp | (de accud (Var Key)
(if (assoc Key (val Var))
(con @ (inc (cdr @)))
(push Var (cons Key 1)) )
Key )
(de **sum (L)
(let S 1
(for I (cdr L)
(inc 'S (** (car L) I)) )
S ) )
(de factor-sum (N)
(if (=1 N)
0
(let
(R NIL
D 2
L (1 2 2 . (... |
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.
| #Scala | Scala | import java.awt.Color
import java.util.concurrent.{Executors, TimeUnit}
import scala.swing.{Graphics2D, MainFrame, Panel, SimpleSwingApplication}
import scala.swing.Swing.pair2Dimension
object Pendulum extends SimpleSwingApplication {
val length = 100
lazy val ui = new Panel {
import scala.math.{cos, Pi, ... |
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... | #Mathematica_.2F_Wolfram_Language | Mathematica / Wolfram Language | CheckValid[i_List]:=If[Length[i]<=1,True,And@@(StringTake[#[[1]],-1]==StringTake[#[[2]],1]&/@Partition[i,2,1])]
sets={{"the","that","a"},{"frog","elephant","thing"},{"walked","treaded","grows"},{"slowly","quickly"}};
Select[Tuples[sets],CheckValid] |
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... | #Erlang | Erlang |
-module(acc_factory).
-export([loop/1,new/1]).
loop(N)->
receive
{P,I}->
S =N+I, P!S, loop(S)
end.
new(N)->
P=spawn(acc_factory,loop,[N]),
fun(I)->
P!{self(),I},
receive
V-> V
end
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
... | #Ada | Ada | with Ada.Text_IO; use Ada.Text_IO;
procedure Test_Ackermann is
function Ackermann (M, N : Natural) return Natural is
begin
if M = 0 then
return N + 1;
elsif N = 0 then
return Ackermann (M - 1, 1);
else
return Ackermann (M - 1, Ackermann (M, N - 1));
end if;
... |
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)... | #Batch_File | Batch File |
@echo off
setlocal enabledelayedexpansion
:_main
for /l %%i in (1,1,20000) do (
echo Processing %%i
call:_P %%i
set Pn=!errorlevel!
if !Pn! lss %%i set /a deficient+=1
if !Pn!==%%i set /a perfect+=1
if !Pn! gtr %%i set /a abundant+=1
cls
)
echo Deficient - %deficient% ^| Perfect - %perfect% ^|... |
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... | #Beads | Beads | beads 1 program 'Align columns'
const
text = '''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$c... |
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... | #Julia | Julia | mutable struct Integrator
func::Function
runningsum::Float64
dt::Float64
running::Bool
function Integrator(f::Function, dt::Float64)
this = new()
this.func = f
this.runningsum = 0.0
this.dt = dt
this.running = false
return this
end
end
function r... |
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... | #Kotlin | Kotlin | // version 1.2.0
import kotlin.math.*
typealias Function = (Double) -> Double
/**
* Integrates input function K over time
* S + (t1 - t0) * (K(t1) + K(t0)) / 2
*/
class Integrator {
private val start: Long
private @Volatile var running = false
private lateinit var func: Function
private var t0 ... |
http://rosettacode.org/wiki/Aliquot_sequence_classifications | Aliquot sequence classifications | An aliquot sequence of a positive integer K is defined recursively as the first member
being K and subsequent members being the sum of the Proper divisors of the previous term.
If the terms eventually reach 0 then the series for K is said to terminate.
There are several classifications for non termination:
If the s... | #Perl | Perl | use ntheory qw/divisor_sum/;
sub aliquot {
my($n, $maxterms, $maxn) = @_;
$maxterms = 16 unless defined $maxterms;
$maxn = 2**47 unless defined $maxn;
my %terms = ($n => 1);
my @allterms = ($n);
for my $term (2 .. $maxterms) {
$n = divisor_sum($n)-$n;
# push onto allterms here if we want the cyc... |
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 ... | #J | J | binomialExpansion =: (!~ * _1 ^ 2 | ]) i.&.:<: NB. 1) Create a function that gives the coefficients of (x-1)^p.
testAKS =: 0 *./ .= ] | binomialExpansion NB. 3) Use that function to create another which determines whether p is prime using AKS. |
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.
... | #PL.2FM | 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... | #Oforth | Oforth | : kprime?( n k -- b )
| i |
0 2 n for: i [
while( n i /mod swap 0 = ) [ ->n 1+ ] drop
]
k ==
;
: table( k -- [] )
| l |
Array new dup ->l
2 while (l size 10 <>) [ dup k kprime? if dup l add then 1+ ]
drop
; |
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... | #PARI.2FGP | PARI/GP | almost(k)=my(n); for(i=1,10,while(bigomega(n++)!=k,); print1(n", "));
for(k=1,5,almost(k);print) |
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
... | #Fantom | Fantom | class Main
{
// take given word and return a string rearranging characters in order
static Str toOrderedChars (Str word)
{
Str[] chars := [,]
word.each |Int c| { chars.add (c.toChar) }
return chars.sort.join("")
}
// add given word to anagrams map
static Void addWord (Str:Str[] anagrams, Str w... |
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.
... | #Swift | Swift | func angleDifference(a1: Double, a2: Double) -> Double {
let diff = (a2 - a1).truncatingRemainder(dividingBy: 360)
if diff < -180.0 {
return 360.0 + diff
} else if diff > 180.0 {
return -360.0 + diff
} else {
return diff
}
}
let testCases = [
(20.0, 45.0),
(-45, 45),
(-85, 90),
(-95, 9... |
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.
... | #Tcl | Tcl |
proc angleDiff {b1 b2} {
set angle [::tcl::mathfunc::fmod [expr ($b2 - $b1)] 360]
if {$angle < -180.0} {
set angle [expr $angle + 360.0]
}
if {$angle >= 180.0} {
set angle [expr $angle - 360.0]
}
return $angle
}
puts "Input in -180 to +180 range"
puts [angleDiff 20.0 45.0]
puts [angleDiff -45.0 ... |
http://rosettacode.org/wiki/Anagrams/Deranged_anagrams | Anagrams/Deranged anagrams | Two or more words are said to be anagrams if they have the same characters, but in a different order.
By analogy with derangements we define a deranged anagram as two words with the same characters, but in which the same character does not appear in the same position in both words.
Task[edit]
Use the word list at uni... | #TUSCRIPT | TUSCRIPT | $$ MODE TUSCRIPT,{}
requestdata = REQUEST ("http://www.puzzlers.org/pub/wordlists/unixdict.txt")
DICT anagramm CREATE 99999
COMPILE
LOOP word=requestdata
-> ? : any character
charsInWord=STRINGS (word," ? ")
charString =ALPHA_SORT (charsInWord)
DICT anagramm LOOKUP charString,num,freq,wordalt,wlalt
IF ... |
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.