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/Achilles_numbers | Achilles numbers |
This page uses content from Wikipedia. The original article was at Achilles number. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
An Achilles number is a number that is powerful but imperfect. Na... | #XPL0 | XPL0 | func GCD(N, D); \Return the greatest common divisor of N and D
int N, D; \numerator and denominator
int R;
[if D > N then
[R:= D; D:= N; N:= R]; \swap D and N
while D > 0 do
[R:= rem(N/D);
N:= D;
D:= R;
];
return N;
]; \GCD
func Totient(N); \Return the totie... |
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... | #jq | jq | # "until" is available in more recent versions of jq
# than jq 1.4
def until(cond; next):
def _until:
if cond then . else (next|_until) end;
_until;
# unordered
def proper_divisors:
. as $n
| if $n > 1 then 1,
( range(2; 1 + (sqrt|floor)) as $i
| if ($n % $i) == 0 then $i,
(($n /... |
http://rosettacode.org/wiki/Add_a_variable_to_a_class_instance_at_runtime | Add a variable to a class instance at runtime | Demonstrate how to dynamically add variables to an object (a class instance) at runtime.
This is useful when the methods/variables of an instance are based on a data file that isn't available until runtime. Hal Fulton gives an example of creating an OO CSV parser at An Exercise in Metaprogramming with Ruby. This is re... | #REBOL | REBOL |
rebol [
Title: "Add Variables to Class at Runtime"
URL: http://rosettacode.org/wiki/Adding_variables_to_a_class_instance_at_runtime
]
; As I understand it, a REBOL object can only ever have whatever
; properties it was born with. However, this is somewhat offset by the
; fact that every instance can serve as a pr... |
http://rosettacode.org/wiki/Add_a_variable_to_a_class_instance_at_runtime | Add a variable to a class instance at runtime | Demonstrate how to dynamically add variables to an object (a class instance) at runtime.
This is useful when the methods/variables of an instance are based on a data file that isn't available until runtime. Hal Fulton gives an example of creating an OO CSV parser at An Exercise in Metaprogramming with Ruby. This is re... | #Red | Red | person: make object! [
name: none
age: none
]
people: reduce [make person [name: "fred" age: 20] make person [name: "paul" age: 21]]
people/1: make people/1 [skill: "fishing"]
foreach person people [
print reduce [person/age "year old" person/name "is good at" any [select person 'skill "nothing"]]
] |
http://rosettacode.org/wiki/Add_a_variable_to_a_class_instance_at_runtime | Add a variable to a class instance at runtime | Demonstrate how to dynamically add variables to an object (a class instance) at runtime.
This is useful when the methods/variables of an instance are based on a data file that isn't available until runtime. Hal Fulton gives an example of creating an OO CSV parser at An Exercise in Metaprogramming with Ruby. This is re... | #Ring | Ring | o1 = new point
addattribute(o1,"x")
addattribute(o1,"y")
addattribute(o1,"z")
see o1 {x=10 y=20 z=30}
class point |
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 |... | #R | R |
x <- 5
y <- x
pryr::address(x)
pryr::address(y)
y <- y + 1
pryr::address(x)
pryr::address(y)
|
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 |... | #Racket | Racket | #lang racket
(require ffi/unsafe)
(define (madness v) ; i'm so sorry
(cast v _racket _gcpointer)) |
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 |... | #Raku | Raku | my $x;
say $x.WHERE;
my $y := $x; # alias
say $y.WHERE; # same address as $x
say "Same variable" if $y =:= $x;
$x = 42;
say $y; # 42
|
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 ... | #Erlang | Erlang | #! /usr/bin/escript
-import(lists, [all/2, seq/2, zip/2]).
iterate(F, X) -> fun() -> [X | iterate(F, F(X))] end.
take(0, _lazy) -> [];
take(N, Lazy) ->
[Value | Next] = Lazy(),
[Value | take(N-1, Next)].
pascal() -> iterate(fun (Row) -> [1 | sum_adj(Row)] end, [1]).
sum_adj([_] = L) -> L;
sum_adj([A... |
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.
... | #Julia | Julia | using Primes
let
p = primesmask(500)
println("Additive primes under 500:")
pcount = 0
for i in 2:499
if p[i] && p[sum(digits(i))]
pcount += 1
print(lpad(i, 4), pcount % 20 == 0 ? "\n" : "")
end
end
println("\n\n$pcount additive primes found.")
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.
... | #Kotlin | Kotlin | fun isPrime(n: Int): Boolean {
if (n <= 3) return n > 1
if (n % 2 == 0 || n % 3 == 0) return false
var i = 5
while (i * i <= n) {
if (n % i == 0 || n % (i + 2) == 0) return false
i += 6
}
return true
}
fun digitSum(n: Int): Int {
var sum = 0
var num = n
while (num >... |
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.
... | #Ksh | Ksh | #!/bin/ksh
# Prime numbers for which the sum of their decimal digits are also primes
# # Variables:
#
integer MAX_n=500
# # Functions:
#
# # Function _isprime(n) return 1 for prime, 0 for not prime
#
function _isprime {
typeset _n ; integer _n=$1
typeset _i ; integer _i
(( _n < 2 )) && return 0
for (( _i=2 ... |
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... | #jq | jq | # Recent versions of jq (version > 1.4) have the following definition of "until":
def until(cond; next):
def _until:
if cond then . else (next|_until) end;
_until;
# relatively_prime(previous) tests whether the input integer is prime
# relative to the primes in the array "previous":
def relatively_prime(previ... |
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... | #Julia | Julia | using Primes
isalmostprime(n::Integer, k::Integer) = sum(values(factor(n))) == k
function almostprimes(N::Integer, k::Integer) # return first N almost-k primes
P = Vector{typeof(k)}(undef,N)
i = 0; n = 2
while i < N
if isalmostprime(n, k) P[i += 1] = n end
n += 1
end
return P
end... |
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
... | #EchoLisp | EchoLisp |
(require 'struct)
(require 'hash)
(require 'sql)
(require 'words)
(require 'dico.fr.no-accent)
(define mots-français (words-select #:any null 999999))
(string-delimiter "")
(define (string-sort str)
(list->string (list-sort string<? (string->list str))))
(define (ana-sort H words) ;; bump counter for each 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.
... | #Raku | Raku | sub infix:<∠> (Real $b1, Real $b2) {
(my $b = ($b2 - $b1 + 720) % 360) > 180 ?? $b - 360 !! $b;
}
for 20, 45,
-45, 45,
-85, 90,
-95, 90,
-45, 125,
-45, 145,
29.4803, -88.6381,
-78.3251, -159.036,
-70099.74233810938, 29840.67437876723,
-165313.6666297357, 33693.9894517456,
1174.8380510... |
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... | #Ruby | Ruby | def deranged?(a, b)
a.chars.zip(b.chars).all? {|char_a, char_b| char_a != char_b}
end
def find_derangements(list)
list.combination(2) {|a,b| return a,b if deranged?(a,b)}
nil
end
require 'open-uri'
anagram = open('http://www.puzzlers.org/pub/wordlists/unixdict.txt') do |f|
f.read.split.group_by {|s| s.each... |
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... | #Perl | Perl | sub recur (&@) {
my $f = shift;
local *recurse = $f;
$f->(@_);
}
sub fibo {
my $n = shift;
$n < 0 and die 'Negative argument';
recur {
my $m = shift;
$m < 3 ? 1 : recurse($m - 1) + recurse($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
... | #PARI.2FGP | PARI/GP | for(x=1,20000,my(y=sigma(x)-x); if(y>x && x == sigma(y)-y,print(x" "y))) |
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.
| #Racket | Racket |
#lang racket
(require 2htdp/image 2htdp/universe)
(define (pendulum)
(define (accel θ) (- (sin θ)))
(define θ (/ pi 2.5))
(define θ′ 0)
(define θ′′ (accel (/ pi 2.5)))
(define (x θ) (+ 200 (* 150 (sin θ))))
(define (y θ) (* 150 (cos θ)))
(λ (n)
(define p-image (underlay/xy (add-line (empty-scene... |
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... | #jq | jq | def amb: .[];
def joins:
(.[0][-1:]) as $left
| (.[1][0:1]) as $right
| if $left == $right then true else empty end;
|
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... | #Ceylon | Ceylon | shared void run() {
Integer|Float accumulator
(variable Integer|Float n)
(Integer|Float i)
=> switch (i)
case (is Integer)
(n = n.plusInteger(i))
case (is Float)
(n = i + (switch(prev = n)
case (is Flo... |
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... | #Clay | Clay | acc(n) {
return (m) => {
n = n + m;
return n;
};
}
main() {
var x = acc(1.0);
x(5);
acc(3);
println(x(2.3)); // Prints “8.300000000000001”.
} |
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
... | #8080_Assembly | 8080 Assembly | org 100h
jmp demo
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; ACK(M,N); DE=M, HL=N, return value in HL.
ack: mov a,d ; M=0?
ora e
jnz ackm
inx h ; If so, N+1.
ret
ackm: mov a,h ; N=0?
ora l
jnz ackmn
lxi h,1 ; If so, N=1,
dcx d ; N-=1,
jmp ack ; A(M,N) - tail recursion
ackmn... |
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)... | #ALGOL_68 | ALGOL 68 | BEGIN # classify the numbers 1 : 20 000 as abudant, deficient or perfect #
INT abundant count := 0;
INT deficient count := 0;
INT perfect count := 0;
INT abundant example := 0;
INT deficient example := 0;
INT perfect example := 0;
INT max number = 20 000;
# construct ... |
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... | #Arturo | Arturo | 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$column$to$be$either$left... |
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... | #F.23 | F# | open System
open System.Threading
// current time in seconds
let now() = float( DateTime.Now.Ticks / 10000L ) / 1000.0
type Integrator( intervalMs ) as x =
let mutable k = fun _ -> 0.0 // function to integrate
let mutable s = 0.0 // current value
let mutable t0 = now() // last time s was upd... |
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... | #Julia | Julia |
function aliquotclassifier{T<:Integer}(n::T)
a = T[n]
b = divisorsum(a[end])
len = 1
while len < 17 && !(b in a) && 0 < b && b < 2^47+1
push!(a, b)
b = divisorsum(a[end])
len += 1
end
if b in a
1 < len || return ("Perfect", a)
if b == a[1]
2 ... |
http://rosettacode.org/wiki/Add_a_variable_to_a_class_instance_at_runtime | Add a variable to a class instance at runtime | Demonstrate how to dynamically add variables to an object (a class instance) at runtime.
This is useful when the methods/variables of an instance are based on a data file that isn't available until runtime. Hal Fulton gives an example of creating an OO CSV parser at An Exercise in Metaprogramming with Ruby. This is re... | #Ruby | Ruby | class Empty
end
e = Empty.new
class << e
attr_accessor :foo
end
e.foo = 1
puts e.foo # output: "1"
f = Empty.new
f.foo = 1 # raises NoMethodError
|
http://rosettacode.org/wiki/Add_a_variable_to_a_class_instance_at_runtime | Add a variable to a class instance at runtime | Demonstrate how to dynamically add variables to an object (a class instance) at runtime.
This is useful when the methods/variables of an instance are based on a data file that isn't available until runtime. Hal Fulton gives an example of creating an OO CSV parser at An Exercise in Metaprogramming with Ruby. This is re... | #Scala | Scala | import language.dynamics
import scala.collection.mutable.HashMap
class A extends Dynamic {
private val map = new HashMap[String, Any]
def selectDynamic(name: String): Any = {
return map(name)
}
def updateDynamic(name:String)(value: Any) = {
map(name) = value
}
} |
http://rosettacode.org/wiki/Add_a_variable_to_a_class_instance_at_runtime | Add a variable to a class instance at runtime | Demonstrate how to dynamically add variables to an object (a class instance) at runtime.
This is useful when the methods/variables of an instance are based on a data file that isn't available until runtime. Hal Fulton gives an example of creating an OO CSV parser at An Exercise in Metaprogramming with Ruby. This is re... | #Sidef | Sidef | class Empty{};
var e = Empty(); # create a new class instance
e{:foo} = 42; # add variable 'foo'
say e{:foo}; # print the value of 'foo' |
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 |... | #RapidQ | RapidQ |
Dim TheAddress as long
Dim SecVar as byte
Dim MyVar as byte
MyVar = 10
'Get the address of MyVar
TheAddress = varptr(MyVar)
'Set a new value on the address
MEMSET(TheAddress, 102, SizeOf(byte))
'Myvar is now = 102
showmessage "MyVar = " + str$(MyVar)
'...or copy from one address to another using:
MEMCPY(V... |
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 |... | #Retro | Retro | 'a var
&a |
http://rosettacode.org/wiki/Address_of_a_variable | Address of a variable |
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
Concatenation |
Interpolation |... | #REXX | REXX | zzz = storage(xxx) |
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 |... | #Ruby | Ruby | >foo = Object.new # => #<Object:0x10ae32000>
>id = foo.object_id # => 2238812160
>"%x" % (id << 1) # => "10ae32000"
|
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 ... | #Factor | Factor | USING: combinators formatting io kernel make math math.parser
math.polynomials prettyprint sequences ;
IN: rosetta-code.aks-test
! Polynomials are represented by the math.polynomials vocabulary
! as sequences with the highest exponent on the right. Hence
! { -1 1 } represents x - 1.
: (x-1)^ ( n -- seq ) { -1 1 } swa... |
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.
... | #langur | langur | val .isPrime = f .i == 2 or .i > 2 and not any f(.x) .i div .x, pseries 2 to .i ^/ 2
val .sumDigits = f fold f{+}, s2n toString .i
writeln "Additive primes less than 500:"
var .count = 0
for .i in [2] ~ series(3..500, 2) {
if .isPrime(.i) and .isPrime(.sumDigits(.i)) {
write $"\.i:3; "
.cou... |
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.
... | #Lua | Lua | function sumdigits(n)
local sum = 0
while n > 0 do
sum = sum + n % 10
n = math.floor(n/10)
end
return sum
end
primegen:generate(nil, 500)
aprimes = primegen:filter(function(n) return primegen.tbd(sumdigits(n)) end)
print(table.concat(aprimes, " "))
print("Count:", #aprimes) |
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... | #Kotlin | Kotlin | fun Int.k_prime(x: Int): Boolean {
var n = x
var f = 0
var p = 2
while (f < this && p * p <= n) {
while (0 == n % p) { n /= p; f++ }
p++
}
return f + (if (n > 1) 1 else 0) == this
}
fun Int.primes(n : Int) : List<Int> {
var i = 2
var list = mutableListOf<Int>()
whil... |
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
... | #Eiffel | Eiffel |
class
ANAGRAMS
create
make
feature
make
-- Set of Anagrams, containing most words.
local
count: INTEGER
do
read_wordlist
across
words as wo
loop
if wo.item.count > count then
count := wo.item.count
end
end
across
words as wo
loop
if wo.item.count = count t... |
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.
... | #REXX | REXX | /*REXX pgm calculates difference between two angles (in degrees), normalizes the result.*/
numeric digits 25 /*use enough dec. digits for angles*/
call show 20, 45 /*display angular difference (deg).*/
call show -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... | #Run_BASIC | Run BASIC | a$ = httpGet$("http://www.puzzlers.org/pub/wordlists/unixdict.txt")
dim theWord$(30000)
dim ssWord$(30000)
c10$ = chr$(10)
i = 1
while instr(a$,c10$,i) <> 0
j = instr(a$,c10$,i)
ln = j - i
again = 1
sWord$ = mid$(a$,i,j-i)
n = n + 1
theWord$(n) = sWord$
while again = 1
again = 0
for kk = 1... |
http://rosettacode.org/wiki/Anonymous_recursion | Anonymous recursion | While implementing a recursive function, it often happens that we must resort to a separate helper function to handle the actual recursion.
This is usually the case when directly calling the current function would waste too many resources (stack space, execution time), causing unwanted side-effects, and/or the f... | #Phix | Phix | without js -- (no class yet)
class Fib
private function fib_i(integer n)
return iff(n<2?n:this.fib_i(n-1)+this.fib_i(n-2))
end function
public function fib(integer n)
if n<0 then throw("constraint error") end if
return this.fib_i(n)
end function
end class
Fib f = new()
function ... |
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
... | #Pascal | Pascal | Chasing Chains of Sums of Factors of Numbers.
Perfect!! 6,
Perfect!! 28,
Amicable! 220,284,
Perfect!! 496,
Amicable! 1184,1210,
Amicable! 2620,2924,
Amicable! 5020,5564,
Amicable! 6232,6368,
Perfect!! 8128,
Amicable! 10744,10856,
Amicable! 12285,14595,
Sociable: 12496,14288,15472,14536,14264,
Sociable: 14316,19116,3170... |
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.
| #Raku | Raku | use SDL2::Raw;
use Cairo;
my $width = 1000;
my $height = 400;
SDL_Init(VIDEO);
my $window = SDL_CreateWindow(
'Pendulum - Raku',
SDL_WINDOWPOS_CENTERED_MASK,
SDL_WINDOWPOS_CENTERED_MASK,
$width, $height, RESIZABLE
);
my $render = SDL_CreateRenderer($window, -1, ACCELERATED +| PRESENTVSYNC);
my... |
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... | #Julia | Julia | # This is a general purpose AMB function that takes a two-argument failure function and
# arbitrary number of iterable objects and returns the first solution found as an array
# this function is in essence an iterative backtracking solver
function amb(failure, itrs...)
n = length(itrs)
if n == 1 return end
... |
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... | #Clojure | Clojure | (defn accum [n]
(let [acc (atom n)]
(fn [m] (swap! acc + m)))) |
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... | #CoffeeScript | CoffeeScript | accumulator = (sum) ->
(n) -> sum += n
f = accumulator(1)
console.log f(5)
console.log f(2.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
... | #8086_Assembly | 8086 Assembly | cpu 8086
bits 16
org 100h
section .text
jmp demo
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; ACK(M,N); DX=M, AX=N, return value in AX.
ack: and dx,dx ; N=0?
jnz .m
inc ax ; If so, return N+1
ret
.m: and ax,ax ; M=0?
jnz .mn
mov ax,1 ; If so, N=1,
dec dx ; M -= 1
jmp ack ; ACK... |
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)... | #ALGOL_W | ALGOL W | begin % count abundant, perfect and deficient numbers up to 20 000 %
integer MAX_NUMBER;
MAX_NUMBER := 20000;
begin
integer array pds ( 1 :: MAX_NUMBER );
integer aCount, dCount, pCount, dSum;
% construct a table of proper divisor sums %
pds( 1 ... |
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... | #AutoHotkey | AutoHotkey | Alignment := "L" ; Options: L, R, C
Text =
( LTrim
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,$a... |
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... | #Factor | Factor | USING: accessors alarms calendar combinators kernel locals math
math.constants math.functions prettyprint system threads ;
IN: rosettacode.active
TUPLE: active-object alarm function state previous-time ;
: apply-stack-effect ( quot -- quot' )
[ call( x -- x ) ] curry ; inline
: nano-to-seconds ( -- seconds )... |
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... | #FBSL | FBSL | #APPTYPE CONSOLE
#INCLUDE <Include\Windows.inc>
DIM Entity AS NEW Integrator(): SLEEP(2000) ' respawn and do the job
Entity.Relax(): SLEEP(500) ' get some rest
PRINT ">>> ", Entity.Yield(): DELETE Entity ' report and die
PAUSE
' ------------- End Program Code -------------
#DEFINE SpawnMutex CreateMutex(N... |
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... | #Kotlin | Kotlin | // version 1.1.3
data class Classification(val sequence: List<Long>, val aliquot: String)
const val THRESHOLD = 1L shl 47
fun sumProperDivisors(n: Long): Long {
if (n < 2L) return 0L
val sqrt = Math.sqrt(n.toDouble()).toLong()
var sum = 1L + (2L..sqrt)
.filter { n % it == 0L }
.map { i... |
http://rosettacode.org/wiki/Add_a_variable_to_a_class_instance_at_runtime | Add a variable to a class instance at runtime | Demonstrate how to dynamically add variables to an object (a class instance) at runtime.
This is useful when the methods/variables of an instance are based on a data file that isn't available until runtime. Hal Fulton gives an example of creating an OO CSV parser at An Exercise in Metaprogramming with Ruby. This is re... | #Slate | Slate | define: #Empty -> Cloneable clone.
define: #e -> Empty clone.
e addSlotNamed: #foo valued: 1. |
http://rosettacode.org/wiki/Add_a_variable_to_a_class_instance_at_runtime | Add a variable to a class instance at runtime | Demonstrate how to dynamically add variables to an object (a class instance) at runtime.
This is useful when the methods/variables of an instance are based on a data file that isn't available until runtime. Hal Fulton gives an example of creating an OO CSV parser at An Exercise in Metaprogramming with Ruby. This is re... | #Smalltalk | Smalltalk | |addSlot p|
addSlot :=
[:obj :slotName |
|anonCls newObj|
anonCls := obj class
subclass:(obj class name,'+') asSymbol
instanceVariableNames:slotName
classVariableNames:''
poolDictionaries:'' category:nil
inEnvironment:nil.
anonCls compile... |
http://rosettacode.org/wiki/Add_a_variable_to_a_class_instance_at_runtime | Add a variable to a class instance at runtime | Demonstrate how to dynamically add variables to an object (a class instance) at runtime.
This is useful when the methods/variables of an instance are based on a data file that isn't available until runtime. Hal Fulton gives an example of creating an OO CSV parser at An Exercise in Metaprogramming with Ruby. This is re... | #Swift | Swift | import Foundation
let fooKey = UnsafeMutablePointer<UInt8>.alloc(1)
class MyClass { }
let e = MyClass()
// set
objc_setAssociatedObject(e, fooKey, 1, .OBJC_ASSOCIATION_RETAIN)
// get
if let associatedObject = objc_getAssociatedObject(e, fooKey) {
print("associated object: \(associatedObject)")
} else {
prin... |
http://rosettacode.org/wiki/Add_a_variable_to_a_class_instance_at_runtime | Add a variable to a class instance at runtime | Demonstrate how to dynamically add variables to an object (a class instance) at runtime.
This is useful when the methods/variables of an instance are based on a data file that isn't available until runtime. Hal Fulton gives an example of creating an OO CSV parser at An Exercise in Metaprogramming with Ruby. This is re... | #Tcl | Tcl | % package require TclOO
% oo::class create summation {
constructor {} {
variable v 0
}
method add x {
variable v
incr v $x
}
method value {{var v}} {
variable $var
return [set $var]
}
destructor {
variable v
puts "Ended with value $v"
}
}
::summat... |
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 |... | #Rust | Rust | let v1 = vec![vec![1,2,3]; 10];
println!("Original address: {:p}", &v1);
let mut v2;
// Override rust protections on reading from uninitialized memory
unsafe {v2 = mem::uninitialized();}
let addr = &mut v2 as *mut _;
// ptr::write() though it takes v1 by value, v1s destructor is not run when it goes out of
// scope,... |
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 |... | #Scala | Scala | var n = 42;
say Sys.refaddr(\n); # prints the address of the variable
say Sys.refaddr(n); # prints the address of the object at which the variable points to |
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 |... | #Sidef | Sidef | var n = 42;
say Sys.refaddr(\n); # prints the address of the variable
say Sys.refaddr(n); # prints the address of the object at which the variable points to |
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 |... | #Smalltalk | Smalltalk | |p|
p := Point x:10 y:20.
ObjectMemory addressOf:p.
ObjectMemory collectGarbage.
ObjectMemory addressOf:p "may return another value" |
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 ... | #Forth | Forth | : coeffs ( u -- nu ... n0 ) \ coefficients of (x-1)^u
1 swap 1+ dup 1 ?do over over i - i */ negate swap loop drop ;
: prime? ( u -- f )
dup 2 < if drop false exit then
dup >r coeffs 1+
\ if not prime, this loop consumes at most half the coefficients, otherwise all
begin dup 1 <> while
r@ mod 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.
... | #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | ClearAll[AdditivePrimeQ]
AdditivePrimeQ[n_Integer] := PrimeQ[n] \[And] PrimeQ[Total[IntegerDigits[n]]]
Select[Range[500], AdditivePrimeQ] |
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.
... | #Modula-2 | Modula-2 | MODULE AdditivePrimes;
FROM InOut IMPORT WriteString, WriteCard, WriteLn;
CONST
Max = 500;
VAR
N: CARDINAL;
Count: CARDINAL;
Prime: ARRAY [2..Max] OF BOOLEAN;
PROCEDURE DigitSum(n: CARDINAL): CARDINAL;
BEGIN
IF n < 10 THEN
RETURN n;
ELSE
RETURN (n MOD 10) + DigitSum(n DIV... |
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... | #Liberty_BASIC | Liberty BASIC |
' Almost prime
for k = 1 to 5
print "k = "; k; ":";
i = 2
c = 0
while c < 10
if kPrime(i, k) then
print " "; using("###", i);
c = c + 1
end if
i = i + 1
wend
print
next k
end
function kPrime(n, k)
f = 0
for i = 2 to n
while n mod i ... |
http://rosettacode.org/wiki/Anagrams | Anagrams | When two or more words are composed of the same characters, but in a different order, they are called anagrams.
Task[edit]
Using the word list at http://wiki.puzzlers.org/pub/wordlists/unixdict.txt,
find the sets of words that share the same characters that contain the most words in them.
Related tasks
Word plays
... | #Ela | Ela | open monad io list string
groupon f x y = f x == f y
lines = split "\n" << replace "\n\n" "\n" << replace "\r" "\n"
main = do
fh <- readFile "c:\\test\\unixdict.txt" OpenMode
f <- readLines fh
closeFile fh
let words = lines f
let wix = groupBy (groupon fst) << sort $ zip (map sort words) words
let mxl... |
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.
... | #Ring | Ring |
# Project : Angle difference between two bearings
decimals(4)
see "Input in -180 to +180 range:" + nl
see getDifference(20.0, 45.0) + nl
see getDifference(-45.0, 45.0) + nl
see getDifference(-85.0, 90.0) + nl
see getDifference(-95.0, 90.0) + nl
see getDifference(-45.0, 125.0) + nl
see getDifference(-45.0, 145.0) + ... |
http://rosettacode.org/wiki/Angle_difference_between_two_bearings | Angle difference between two bearings | Finding the angle between two bearings is often confusing.[1]
Task
Find the angle which is the result of the subtraction b2 - b1, where b1 and b2 are the bearings.
Input bearings are expressed in the range -180 to +180 degrees.
The result is also expressed in the range -180 to +180 degrees.
... | #Ruby | Ruby | def getDifference(b1, b2)
r = (b2 - b1) % 360.0
# Ruby modulus has same sign as divisor, which is positive here,
# so no need to consider negative case
if r >= 180.0
r -= 360.0
end
return r
end
if __FILE__ == $PROGRAM_NAME
puts "Input in -180 to +180 range"
puts getDifference(20.0, 45.0)
puts getDifference... |
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... | #Rust | Rust | //! Deranged anagrams
use std::cmp::Ordering;
use std::collections::HashMap;
use std::fs::File;
use std::io;
use std::io::BufReader;
use std::io::BufRead;
use std::usize::MAX;
/// Get words from unix dictionary file
pub fn get_words() -> Result<Vec<String>, io::Error> {
let mut words = vec!();
// open file
... |
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... | #PHP | PHP | <?php
function fib($n) {
if ($n < 0)
throw new Exception('Negative numbers not allowed');
$f = function($n) { // This function must be called using call_user_func() only
if ($n < 2)
return 1;
else {
$g = debug_backtrace()[1]['args'][0];
return call_use... |
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
... | #Perl | Perl | use ntheory qw/divisor_sum/;
for my $x (1..20000) {
my $y = divisor_sum($x)-$x;
say "$x $y" if $y > $x && $x == divisor_sum($y)-$y;
} |
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.
| #REXX | REXX | /*REXX program displays the (x, y) coördinates (at the end of a swinging pendulum). */
parse arg cycles Plength theta . /*obtain optional argument from the CL.*/
if cycles=='' | cycles=="," then cycles= 60 /*Not specified? Then use the default.*/
if pLength=='' | pLength=="," then pLength= 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... | #Kotlin | Kotlin | // version 1.2.41
import kotlin.coroutines.experimental.*
import kotlin.coroutines.experimental.intrinsics.*
fun main(args: Array<String>) = amb {
val a = amb("the", "that", "a")
val b = amb("frog", "elephant", "thing")
val c = amb("walked", "treaded", "grows")
val d = amb("slowly", "quickly")
i... |
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... | #Common_Lisp | Common Lisp | (defun accumulator (sum)
(lambda (n)
(incf sum 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... | #Crystal | Crystal |
# Make types a bit easier with an alias
alias Num = Int32 | Int64 | Float32 | Float64
def accumulator(sum : Num)
# This proc is very similar to a Ruby lambda
->(n : Num){ sum += n }
end
x = accumulator(5)
puts x.call(5) #=> 10
puts x.call(10) #=> 20
puts x.call(2.4) #=> 22.4
|
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
... | #8th | 8th |
\ Ackermann function, illustrating use of "memoization".
\ Memoization is a technique whereby intermediate computed values are stored
\ away against later need. It is particularly valuable when calculating those
\ values is time or resource intensive, as with the Ackermann function.
\ make the stack much bigger ... |
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)... | #AppleScript | AppleScript | on aliquotSum(n)
if (n < 2) then return 0
set sum to 1
set sqrt to n ^ 0.5
set limit to sqrt div 1
if (limit = sqrt) then
set sum to sum + limit
set limit to limit - 1
end if
repeat with i from 2 to limit
if (n mod i is 0) then set sum to sum + i + n div i
end rep... |
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... | #AutoIt | AutoIt |
; == If the given text is in an file, it will read with:
#include <File.au3>
Global $aRead
_FileReadToArray($sPath, $aRead) ; == $aRead[0] includes count of lines, every line stored in one item (without linebreak)
; == For example we get the same result with StringSplit()
Global $sText = _
"Given$a$text$file$of$ma... |
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... | #FreeBASIC | FreeBASIC | #define twopi 6.2831853071795864769252867665590057684
dim shared as double S = 0 'set up the state as a global variable
dim shared as double t0, t1, ta
function sine( x as double, f as double ) as double
return sin(twopi*f*x)
end function
function zero( x as double, f as double ) as double
return 0
end ... |
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... | #Go | Go | package main
import (
"fmt"
"math"
"time"
)
// type for input function, k.
// input is duration since an arbitrary start time t0.
type tFunc func(time.Duration) float64
// active integrator object. state variables are not here, but in
// function aif, started as a goroutine in the constructor.
type a... |
http://rosettacode.org/wiki/Aliquot_sequence_classifications | Aliquot sequence classifications | An aliquot sequence of a positive integer K is defined recursively as the first member
being K and subsequent members being the sum of the Proper divisors of the previous term.
If the terms eventually reach 0 then the series for K is said to terminate.
There are several classifications for non termination:
If the s... | #Liberty_BASIC | Liberty BASIC |
print "ROSETTA CODE - Aliquot sequence classifications"
[Start]
input "Enter an integer: "; K
K=abs(int(K)): if K=0 then goto [Quit]
call PrintAS K
goto [Start]
[Quit]
print "Program complete."
end
sub PrintAS K
Length=52
dim Aseq(Length)
n=K: class=0
for element=2 to Length
Aseq(element)=... |
http://rosettacode.org/wiki/Add_a_variable_to_a_class_instance_at_runtime | Add a variable to a class instance at runtime | Demonstrate how to dynamically add variables to an object (a class instance) at runtime.
This is useful when the methods/variables of an instance are based on a data file that isn't available until runtime. Hal Fulton gives an example of creating an OO CSV parser at An Exercise in Metaprogramming with Ruby. This is re... | #Wren | Wren | import "io" for Stdin, Stdout
class Birds {
construct new(userFields) {
_userFields = userFields
}
userFields { _userFields }
}
var userFields = {}
System.print("Enter three fields to add to the Birds class:")
for (i in 0..2) {
System.write("\n name : ")
Stdout.flush()
var name = St... |
http://rosettacode.org/wiki/Add_a_variable_to_a_class_instance_at_runtime | Add a variable to a class instance at runtime | Demonstrate how to dynamically add variables to an object (a class instance) at runtime.
This is useful when the methods/variables of an instance are based on a data file that isn't available until runtime. Hal Fulton gives an example of creating an OO CSV parser at An Exercise in Metaprogramming with Ruby. This is re... | #XBS | XBS | set Object = {}
Object.Hello = "World";
log(Object.Hello); |
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 |... | #Stata | Stata | a = 1
&a
function f(x) {
return(x+1)
}
&f() |
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 |... | #Swift | Swift |
class MyClass { }
func printAddress<T>(of pointer: UnsafePointer<T>) {
print(pointer)
}
func test() {
var x = 42
var y = 3.14
var z = "foo"
var obj = MyClass()
// Use a pointer to a variable on the stack and print its address.
withUnsafePointer(to: &x) { print($0) }
withUnsafeP... |
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 |... | #Tcl | Tcl | package require critcl
# This code assumes an ILP32 architecture, like classic x86 or VAX.
critcl::cproc peek {int addr} int {
union {
int i;
int *a;
} u;
u.i = addr;
return *u.a;
}
critcl::cproc poke {int addr int value} void {
union {
int i;
int *a;
} u;
u... |
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 |... | #Toka | Toka | variable foo
foo .
|
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 ... | #Fortran | Fortran |
program aks
implicit none
! Coefficients of polynomial expansion
integer(kind=16), dimension(:), allocatable :: coeffs
integer(kind=16) :: n
! Character variable for I/O
character(len=40) :: tmp
! Point #2
do n = 0, 7
write(tmp, *) n
call polynomial_expansion(n, coeffs)
write(*, fmt='(... |
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.
... | #Nim | Nim | import math, strutils
const N = 499
# Sieve of Erathostenes.
var composite: array[2..N, bool] # Initialized to false, ie. prime.
for n in 2..sqrt(N.toFloat).int:
if not composite[n]:
for k in countup(n * n, N, n):
composite[k] = true
func digitSum(n: Positive): Natural =
## Compute sum of digit... |
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.
... | #Pari.2FGP | Pari/GP | hasPrimeDigitsum(n)=isprime(sumdigits(n)); \\ see A028834 in the OEIS
v1 = select(isprime, select(hasPrimeDigitsum, [1..499]));
v2 = select(hasPrimeDigitsum, select(isprime, [1..499]));
v3 = select(hasPrimeDigitsum, primes([1, 499]));
s=0; forprime(p=2,499, if(hasPrimeDigitsum(p), s++)); s;
[#v1, #v2, #v3, 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... | #Lua | Lua | -- Returns boolean indicating whether n is k-almost prime
function almostPrime (n, k)
local divisor, count = 2, 0
while count < k + 1 and n ~= 1 do
if n % divisor == 0 then
n = n / divisor
count = count + 1
else
divisor = divisor + 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
... | #Elena | Elena | import system'routines;
import system'calendar;
import system'io;
import system'collections;
import extensions;
import extensions'routines;
import extensions'text;
extension op
{
string normalized()
= self.toArray().ascendant().summarize(new StringWriter());
}
public program()
{
var start := now;
... |
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.
... | #Run_BASIC | Run BASIC | sub getDifference b1, b2
r = (b2 - b1) mod 360
if r >= 180 then r = r - 360
print r
end sub
print "Input in -180 to +180 range:"
call getDifference 20, 45
call getDifference -45, 45
call getDifference -85, 90
call getDifference -95, 90
call getDifference -45, 125
call getDifference -45, 145
call getDif... |
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.
... | #Rust | Rust |
/// Calculate difference between two bearings, in -180 to 180 degrees range
pub fn angle_difference(bearing1: f64, bearing2: f64) -> f64 {
let diff = (bearing2 - bearing1) % 360.0;
if diff < -180.0 {
360.0 + diff
} else if diff > 180.0 {
-360.0 + diff
} else {
diff
}
}
... |
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... | #Scala | Scala | object DerangedAnagrams {
/** Returns a map of anagrams keyed by the sorted characters */
def groupAnagrams(words: Iterable[String]): Map[String, Set[String]] =
words.foldLeft (Map[String, Set[String]]()) { (map, word) =>
val sorted = word.sorted
val entry = map.getOrElse(sorted, Set.empty)
... |
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... | #PicoLisp | PicoLisp | (de fibo (N)
(if (lt0 N)
(quit "Illegal argument" N) )
(recur (N)
(if (> 2 N)
1
(+ (recurse (dec N)) (recurse (- N 2))) ) ) ) |
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
... | #Phix | Phix | integer n
for m=1 to 20000 do
n = sum(factors(m,-1))
if m<n and m=sum(factors(n,-1)) then ?{m,n} end if
end for
|
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.
| #Ring | Ring |
# Project : Animate a pendulum
load "guilib.ring"
load "stdlib.ring"
CounterMan = 1
paint = null
pi = 22/7
theta = pi/180*40
g = 9.81
l = 0.50
speed = 0
new qapp
{
win1 = new qwidget() {
setwindowtitle("Animate a pendulum")
setgeometry(100,100,800,600)
... |
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... | #langur | langur | val .wordsets = [
w/the that a/,
w/frog elephant thing/,
w/walked treaded grows/,
w/slowly quickly/,
]
val .alljoin = f(.words) for[=true] .i of len(.words)-1 {
if last(.words[.i]) != first(.words[.i+1]): break = false
}
# .amb expects 2 or more arguments
val .amb = f(...[2 to -1] .words) if(.al... |
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.