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/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 |... | #PARI.2FGP | PARI/GP | issquare(n, &m) |
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 |... | #Pascal | Pascal | use Scalar::Util qw(refaddr);
print refaddr(\my $v), "\n"; # 140502490125712 |
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 |... | #Perl | Perl | use Scalar::Util qw(refaddr);
print refaddr(\my $v), "\n"; # 140502490125712 |
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 ... | #Delphi | Delphi |
(lib 'math.lib)
;; 1 - x^p : P = (1 0 0 0 ... 0 -1)
(define (mono p) (append (list 1) (make-list (1- p) 0) (list -1)))
;; compute (x-1)^p , p >= 1
(define (aks-poly p)
(poly-pow (list -1 1) p))
;;
(define (show-them n)
(for ((p (in-range 1 n)))
(writeln 'p p (poly->string 'x (aks-poly p)))))
;; aks-tes... |
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.
... | #FreeBASIC | FreeBASIC | #include "isprime.bas"
function digsum( n as uinteger ) as uinteger
dim as uinteger s
while n
s+=n mod 10
n\=10
wend
return s
end function
dim as uinteger s
print "Prime","Digit Sum"
for i as uinteger = 2 to 499
if isprime(i) then
s = digsum(i)
if isprime(s) the... |
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.
... | #Free_Pascal | Free Pascal |
Program AdditivePrimes;
Const max_number = 500;
Var is_prime : array Of Boolean;
Procedure sieve(Var arr: Array Of boolean );
{use Sieve of Eratosthenes to find all primes to max number}
Var i,j : NativeUInt;
Begin
For i := 2 To high(arr) Do
arr[i] := True; // set all bits to be True
For i := 2 To high... |
http://rosettacode.org/wiki/Algebraic_data_types | Algebraic data types | Some languages offer direct support for algebraic data types and pattern matching on them. While this of course can always be simulated with manual tagging and conditionals, it allows for terse code which is easy to read, and can represent the algorithm directly.
Task
As an example, implement insertion in a red-bla... | #Tailspin | Tailspin |
processor RedBlackTree
data node <{VOID}|{colour: <='black'|='red'>, left: <node>, right: <node>, value: <> VOID}> local
@: {};
sink insert
templates balance
when <{colour: <='black'>, left: <{ colour: <='red'> left: <{colour: <='red'>}>}>}>
do { colour: 'red',
left: { $.left.left...... |
http://rosettacode.org/wiki/Algebraic_data_types | Algebraic data types | Some languages offer direct support for algebraic data types and pattern matching on them. While this of course can always be simulated with manual tagging and conditionals, it allows for terse code which is easy to read, and can represent the algorithm directly.
Task
As an example, implement insertion in a red-bla... | #Tcl | Tcl | # From http://wiki.tcl.tk/9547
package require Tcl 8.5
package provide datatype 0.1
namespace eval ::datatype {
namespace export define match matches
namespace ensemble create
# Datatype definitions
proc define {type = args} {
set ns [uplevel 1 { namespace current }]
fore... |
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... | #Icon_and_Unicon | Icon and Unicon | link "factors"
procedure main()
every writes(k := 1 to 5,": ") do
every writes(right(genKap(k),5)\10|"\n")
end
procedure genKap(k)
suspend (k = *factors(n := seq(q)), n)
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
... | #Crystal | Crystal | require "http/client"
response = HTTP::Client.get("http://wiki.puzzlers.org/pub/wordlists/unixdict.txt")
if response.body?
words : Array(String) = response.body.split
anagram = {} of String => Array(String)
words.each do |word|
key = word.split("").sort.join
if !anagram[key]?
anagram[key] ... |
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.
... | #PowerShell | PowerShell |
<#
.Synopsis
Gets the difference between two angles between the values of -180 and 180.
To see examples use "Get-Examples"
.DESCRIPTION
This code uses the modulo operator, this is represented with the "%".
The modulo operator returns the remainder after division, as displayed below
3 % 2 = 1
20 % 1... |
http://rosettacode.org/wiki/Anagrams/Deranged_anagrams | Anagrams/Deranged anagrams | Two or more words are said to be anagrams if they have the same characters, but in a different order.
By analogy with derangements we define a deranged anagram as two words with the same characters, but in which the same character does not appear in the same position in both words.
Task[edit]
Use the word list at uni... | #Racket | Racket | #lang racket
(define word-list-file "data/unixdict.txt")
(define (read-words-into-anagram-keyed-hash)
(define (anagram-key word) (sort (string->list word) char<?))
(for/fold ((hsh (hash)))
((word (in-lines)))
(hash-update hsh (anagram-key word) (curry cons word) null)))
(define anagrams-list
(sort
... |
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... | #Ol | Ol |
(define (fibonacci n)
(if (> 0 n)
"error: negative argument."
(let loop ((a 1) (b 0) (count n))
(if (= count 0)
b
(loop (+ a b) a (- count 1))))))
(print
(map fibonacci '(1 2 3 4 5 6 7 8 9 10)))
|
http://rosettacode.org/wiki/Amicable_pairs | Amicable pairs | Two integers
N
{\displaystyle N}
and
M
{\displaystyle M}
are said to be amicable pairs if
N
≠
M
{\displaystyle N\neq M}
and the sum of the proper divisors of
N
{\displaystyle N}
(
s
u
m
(
p
r
o
p
D
i
v
s
(
N
)
)
{\displaystyle \mathrm {sum} (\mathrm {propDivs} (N))}
)
=
M
... | #Nim | Nim |
from math import sqrt
const N = 524_000_000.int32
proc sumProperDivisors(someNum: int32, chk4less: bool): int32 =
result = 1
let maxPD = sqrt(someNum.float).int32
let offset = someNum mod 2
for divNum in countup(2 + offset, maxPD, 1 + offset):
if someNum mod divNum == 0:
result... |
http://rosettacode.org/wiki/Animation | Animation |
Animation is integral to many parts of GUIs, including both the fancy effects when things change used in window managers, and of course games. The core of any animation system is a scheme for periodically changing the display while still remaining responsive to the user. This task demonstrates this.
Task
Creat... | #ZX_Spectrum_Basic | ZX Spectrum Basic | 10 LET t$="Hello world! ": LET lt=LEN t$
20 LET direction=1
30 PRINT AT 0,0;t$
40 IF direction THEN LET t$=t$(2 TO )+t$(1): GO TO 60
50 LET t$=t$(lt)+t$( TO lt-1)
60 IF INKEY$<>"" THEN LET direction=NOT direction
70 PAUSE 5: GO TO 30 |
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.
| #PureBasic | PureBasic | Procedure handleError(x, msg.s)
If Not x
MessageRequester("Error", msg)
End
EndIf
EndProcedure
#ScreenW = 320
#ScreenH = 210
handleError(OpenWindow(0, 0, 0, #ScreenW, #ScreenH, "Animated Pendulum", #PB_Window_SystemMenu), "Can't open window.")
handleError(InitSprite(), "Can't setup sprite display.")
handl... |
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... | #Haxe | Haxe | class RosettaDemo
{
static var setA = ['the', 'that', 'a'];
static var setB = ['frog', 'elephant', 'thing'];
static var setC = ['walked', 'treaded', 'grows'];
static var setD = ['slowly', 'quickly'];
static public function main()
{
Sys.print(ambParse([ setA, setB, setC, setD ]).toString());
}
static funct... |
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... | #Astro | Astro | fun accumulator(var sum): :: Real -> _
n => sum += n
let f = accumulator!(5)
print f(5) # 10
print f(10) # 20
print f(2.4) # 22.4 |
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... | #BBC_BASIC | BBC BASIC | x = FNaccumulator(1)
dummy = FN(x)(5)
dummy = FNaccumulator(3)
PRINT FN(x)(2.3)
END
DEF FNaccumulator(sum)
LOCAL I%, P%, Q%
DIM P% 53 : Q% = !^FNdummy()
FOR I% = 0 TO 49 : P%?I% = Q%?I% : NEXT
P%!I% = P% : sum = FN(P%+I%)(sum)
= P%+I%
DEF FNdum... |
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)... | #8086_Assembly | 8086 Assembly | LIMIT: equ 20000
cpu 8086
org 100h
mov ax,data ; Set DS and ES to point right after the
mov cl,4 ; program, so we can store the array there
shr ax,cl
mov dx,cs
add ax,dx
inc ax
mov ds,ax
mov es,ax
mov ax,1 ; Set each element to 1 at the beginning
xor di,di
mov cx,LIMIT+1
rep stosw
mov [2],cx ; Except... |
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... | #ALGOL_68 | ALGOL 68 | STRING nl = REPR 10;
STRING text in list := "Given$a$text$file$of$many$lines,$where$fields$within$a$line$"+nl+
"are$delineated$by$a$single$'dollar'$character,$write$a$program"+nl+
"that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$"+nl+
"column$are$separated$by$at$least$one$space."+nl+
"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... | #Delphi | Delphi |
program Active_object;
{$APPTYPE CONSOLE}
uses
System.SysUtils,
System.Classes;
type
TIntegrator = class(TThread)
private
{ Private declarations }
interval, s: double;
IsRunning: Boolean;
protected
procedure Execute; override;
public
k: Tfunc<Double, Double>;
constructor Crea... |
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... | #Phix | Phix | with javascript_semantics
requires("1.0.2") -- [join_by(fmt)]
atom t0 = time()
constant maxDigits = iff(platform()=JS?10:12)
integer pps = new_dict()
procedure getPerfectPowers(integer maxExp)
atom hi = power(10, maxExp)
integer imax = floor(sqrt(hi))
for i=2 to imax do
atom p = i
while tr... |
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... | #Haskell | Haskell | divisors :: (Integral a) => a -> [a]
divisors n = filter ((0 ==) . (n `mod`)) [1 .. (n `div` 2)]
data Class
= Terminating
| Perfect
| Amicable
| Sociable
| Aspiring
| Cyclic
| Nonterminating
deriving (Show)
aliquot :: (Integral a) => a -> [a]
aliquot 0 = [0]
aliquot n = n : (aliquot $ sum $ divisors... |
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... | #Oz | Oz | declare
%% Creates a new class derived from BaseClass
%% with an added feature (==public immutable attribute)
fun {AddFeature BaseClass FeatureName FeatureValue}
class DerivedClass from BaseClass
feat
%% "FeatureName" is escaped, otherwise a new variable
%% refering to a private feature would... |
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... | #Perl | Perl | package Empty;
# Constructor. Object is hash.
sub new { return bless {}, shift; }
package main;
# Object.
my $o = Empty->new;
# Set runtime variable (key => value).
$o->{'foo'} = 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... | #Phix | Phix | class wobbly dynamic
-- (pre-define a few fields/methods if you like)
end class
wobbly wobble = new()
?wobble.jelly -- 0
--?wobble["jelly"] -- for dynamic names use []
wobble.jelly = "green"
?wobble.jelly -- "green"
|
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 |... | #Phix | Phix | procedure address()
object V
integer addr4 -- stored /4 (assuming dword aligned, which it will be)
#ilASM{
[32]
lea eax,[V]
shr eax,2
mov [addr4],eax
[64]
lea rax,[V]
shr rax,2
mov [addr4],rax
[]
}
if machine_bits()=32 then
poke4(addr4*4,12... |
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 |... | #PicoLisp | PicoLisp | : (setq X 7)
-> 7
: (adr 'X)
-> -2985527269106
: (val (adr -2985527269106))
-> 7
: (set (adr -2985527269106) '(a b c))
-> (a b c)
: X
-> (a b c) |
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 |... | #PL.2FI | PL/I |
declare addr builtin; /* retrieve address of a variable */
declare ptradd builtin; /* pointer addition */
declare cstg builtin; /* retrieve length of the storage of a variable */
declare hbound builtin; /* retrieve the number of elements in an array */
declare p pointe... |
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 ... | #EchoLisp | EchoLisp |
(lib 'math.lib)
;; 1 - x^p : P = (1 0 0 0 ... 0 -1)
(define (mono p) (append (list 1) (make-list (1- p) 0) (list -1)))
;; compute (x-1)^p , p >= 1
(define (aks-poly p)
(poly-pow (list -1 1) p))
;;
(define (show-them n)
(for ((p (in-range 1 n)))
(writeln 'p p (poly->string 'x (aks-poly p)))))
;; aks-tes... |
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.
... | #Frink | Frink | vals = toArray[select[primes[2, 500], {|x| isPrime[sum[integerDigits[x]]]}]]
println[formatTable[columnize[vals, 10]]]
println["\n" + length[vals] + " values found."] |
http://rosettacode.org/wiki/Additive_primes | Additive primes | Definitions
In mathematics, additive primes are prime numbers for which the sum of their decimal digits are also primes.
Task
Write a program to determine (and show here) all additive primes less than 500.
Optionally, show the number of additive primes.
Also see
the OEIS entry: A046704 additive primes.
... | #Go | Go | package main
import "fmt"
func isPrime(n int) bool {
switch {
case n < 2:
return false
case n%2 == 0:
return n == 2
case n%3 == 0:
return n == 3
default:
d := 5
for d*d <= n {
if n%d == 0 {
return false
}
... |
http://rosettacode.org/wiki/Algebraic_data_types | Algebraic data types | Some languages offer direct support for algebraic data types and pattern matching on them. While this of course can always be simulated with manual tagging and conditionals, it allows for terse code which is easy to read, and can represent the algorithm directly.
Task
As an example, implement insertion in a red-bla... | #Wren | Wren | var R = "R"
var B = "B"
class Tree {
ins(x) {} // overridden by child classes
insert(x) { // inherited by child classes
var t = ins(x)
if (t.type == T) return T.new(B, t.le, t.aa, t.ri)
if (t.type == E) return E.new()
return null
}
}
class T is Tree {
construct... |
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... | #J | J | (10 {. [:~.[:/:~[:,*/~)^:(i.5)~p:i.10
2 3 5 7 11 13 17 19 23 29
4 6 9 10 14 15 21 22 25 26
8 12 18 20 27 28 30 42 44 45
16 24 36 40 54 56 60 81 84 88
32 48 72 80 108 112 120 162 168 176 |
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
... | #D | D | import std.stdio, std.algorithm, std.string, std.exception, std.file;
void main() {
string[][ubyte[]] an;
foreach (w; "unixdict.txt".readText.splitLines)
an[w.dup.representation.sort().release.assumeUnique] ~= w;
immutable m = an.byValue.map!q{ a.length }.reduce!max;
writefln("%(%s\n%)", an.by... |
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.
... | #PureBasic | PureBasic | Procedure.f getDifference (b1.f, b2.f)
r.f = Mod((b2 - b1), 360)
If r >= 180: r - 360
EndIf
PrintN(StrF(b1) + #TAB$ + StrF(b2) + #TAB$ + StrF(r));
EndProcedure
If OpenConsole()
PrintN("Input in -180 to +180 range:")
getDifference(20.0, 45.0)
getDifference(-45.0, 45.0)
getDifference(-85.0, 90.0)
getD... |
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... | #Raku | Raku | my @anagrams = 'unixdict.txt'.IO.words
.map(*.comb.cache) # explode words into lists of characters
.classify(*.sort.join).values # group words with the same characters
.grep(* > 1) # only take groups with more than one word
.sort(-*[0]) # sort by length o... |
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... | #OxygenBasic | OxygenBasic |
function fiboRatio() as double
function fibo( double i, j ) as double
if j > 2e12 then return j / i
return fibo j, i + j
end function
return fibo 1, 1
end function
print fiboRatio
|
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
... | #Oberon-2 | Oberon-2 |
MODULE AmicablePairs;
IMPORT
Out;
CONST
max = 20000;
VAR
i,j: INTEGER;
pd: ARRAY max + 1 OF LONGINT;
PROCEDURE ProperDivisorsSum(n: LONGINT): LONGINT;
VAR
i,sum: LONGINT;
BEGIN
sum := 0;
IF n > 1 THEN
INC(sum,1);i := 2;
WHILE (i < n) DO
IF (n MOD i) = 0 THEN INC(sum,i) END;
IN... |
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.
| #Python | Python | import pygame, sys
from pygame.locals import *
from math import sin, cos, radians
pygame.init()
WINDOWSIZE = 250
TIMETICK = 100
BOBSIZE = 15
window = pygame.display.set_mode((WINDOWSIZE, WINDOWSIZE))
pygame.display.set_caption("Pendulum")
screen = pygame.display.get_surface()
screen.fill((255,255,255))
PIVOT ... |
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... | #Icon_and_Unicon | Icon and Unicon | procedure main()
s1 := ["the","that","a"]
s2 := ["frog","elephant","thing"]
s3 := ["walked","treaded","grows"]
s4 := ["slowly","quickly"]
write(amb(!s1,!s2,!s3,!s4))
end
procedure amb(exprs[])
s := ""
every e := !exprs do {
if \c ~== e[1] then fail
c := e[-1]
s ||... |
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... | #Bracmat | Bracmat | ( ( accumulator
=
.
' ( add sum object
. (object=add=$arg+!arg)
& !(object.add):?sum
& '($($sum)+!arg):(=?(object.add))
& !sum
)
)
& accumulator$1:(=?x)
& x$5
& accumulator$3
& out$(x$23/10)
) |
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... | #Brat | Brat | accumulator = { sum |
{ n | sum = sum + n }
}
x = accumulator 1
x 5
accumulator 3 #Does not affect x
p x 2.3 #Prints 8.3 (1 + 5 + 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
... | #11l | 11l | F ack2(m, n) -> Int
R I m == 0 {(n + 1)
} E I m == 1 {(n + 2)
} E I m == 2 {(2 * n + 3)
} E I m == 3 {(8 * (2 ^ n - 1) + 5)
} E I n == 0 {ack2(m - 1, 1)
} E ack2(m - 1, ack2(m, n - 1))
print(ack2(0, 0))
print(ack2(3, 4))
print(ack2(4, 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)... | #AArch64_Assembly | AArch64 Assembly |
/* ARM assembly AARCH64 Raspberry PI 3B or android 64 bits */
/* program numberClassif64.s */
/*******************************************/
/* Constantes file */
/*******************************************/
/* for this file see task include a file in language AArch64 assembly*/
.include "... |
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... | #Amazing_Hopper | Amazing Hopper |
#define IGet(__N__,__X__) [__N__]SGet(__X__)
#include <hbasic.h>
#define MAX_LINE 1000
Begin
Option Stack 15
Declare as Numeric ( fd, i, index, max token )
as Numeric ( num tokens, size Column, tCells )
as Alpha ( line )
as Numeric ( display Left, display Right, display ... |
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... | #E | E | def makeIntegrator() {
var value := 0.0
var input := fn { 0.0 }
var input1 := input()
var t1 := timer.now()
def update() {
def t2 := timer.now()
def input2 :float64 := input()
def dt := (t2 - t1) / 1000
value += (input1 + input2) * dt / 2
t1 := t2
... |
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... | #Raku | Raku | use Prime::Factor;
use Math::Root;
sub is-square-free (Int \n) {
constant @p = ^100 .map: { next unless .is-prime; .² };
for @p -> \p { return False if n %% p }
True
}
sub powerful (\n, \k = 2) {
my @p;
p(1, 2*k - 1);
sub p (\m, \r) {
@p.push(m) and return if r < k;
for 1 .. ... |
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... | #J | J | proper_divisors=: [: */@>@}:@,@{ [: (^ i.@>:)&.>/ 2 p: x:
aliquot=: +/@proper_divisors ::0:
rc_aliquot_sequence=: aliquot^:(i.16)&>
rc_classify=: 3 :0
if. 16 ~:# y do. ' invalid '
elseif. 6 > {: y do. ' terminate '
elseif. (+./y>2^47) +. 16 = #~.y do. ' non-terminat... |
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... | #PHP | PHP | class E {};
$e=new E();
$e->foo=1;
$e->{"foo"} = 1; // using a runtime name
$x = "foo";
$e->$x = 1; // using a runtime name in a variable |
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... | #PicoLisp | PicoLisp | : (setq MyObject (new '(+MyClass))) # Create some object
-> $385605941
: (put MyObject 'newvar '(some value)) # Set variable
-> (some value)
: (show MyObject) # Show the object
$385605941 (+MyClass)
newvar (some value)
-> $385605941 |
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... | #Pike | Pike | class CSV
{
mapping variables = ([]);
mixed `->(string name)
{
return variables[name];
}
void `->=(string name, mixed value)
{
variables[name] = value;
}
array _indices()
{
return indices(variables);
}
}
object csv = CSV();
csv->greeting = "hello w... |
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 |... | #PL.2FM | PL/M | 100H:
/* THERE IS NO STANDARD LIBRARY
THIS DEFINES SOME BASIC I/O USING CP/M */
BDOS: PROCEDURE (F,A); DECLARE F BYTE, A ADDRESS; GO TO 5; END BDOS;
EXIT: PROCEDURE; CALL BDOS(0,0); END EXIT;
PUT$CHAR: PROCEDURE (C); DECLARE C BYTE; CALL BDOS(2,C); END PUT$CHAR;
PRINT: PROCEDURE (S); DECLARE S ADDRESS; CALL BDOS(9,S... |
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 ... | #Elena | Elena | import extensions;
singleton AksTest
{
static long[] c := new long[](100);
coef(int n)
{
int i := 0;
int j := 0;
if ((n < 0) || (n > 63)) { AbortException.raise() }; // gracefully deal with range issue
c[i] := 1l;
for (int i := 0, i < n, i += 1) {
... |
http://rosettacode.org/wiki/Additive_primes | Additive primes | Definitions
In mathematics, additive primes are prime numbers for which the sum of their decimal digits are also primes.
Task
Write a program to determine (and show here) all additive primes less than 500.
Optionally, show the number of additive primes.
Also see
the OEIS entry: A046704 additive primes.
... | #J | J | (#~ 1 p: [:+/@|: 10&#.inv) i.&.(p:inv) 500
2 3 5 7 11 23 29 41 43 47 61 67 83 89 101 113 131 137 139 151 157 173 179 191 193 197 199 223 227 229 241 263 269 281 283 311 313 317 331 337 353 359 373 379 397 401 409 421 443 449 461 463 467 487 |
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.
... | #Java | Java | public class additivePrimes {
public static void main(String[] args) {
int additive_primes = 0;
for (int i = 2; i < 500; i++) {
if(isPrime(i) && isPrime(digitSum(i))){
additive_primes++;
System.out.print(i + " ");
}
}
System.o... |
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... | #Java | Java | public class AlmostPrime {
public static void main(String[] args) {
for (int k = 1; k <= 5; k++) {
System.out.print("k = " + k + ":");
for (int i = 2, c = 0; c < 10; i++) {
if (kprime(i, k)) {
System.out.print(" " + i);
c++;
... |
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
... | #Delphi | Delphi |
program AnagramsTest;
{$APPTYPE CONSOLE}
{$R *.res}
uses
System.SysUtils,
System.Classes,
System.Diagnostics;
function Sort(s: string): string;
var
c: Char;
i, j, aLength: Integer;
begin
aLength := s.Length;
if aLength = 0 then
exit('');
Result := s;
for i := 1 to aLength - 1 do
... |
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.
... | #Python | Python | from __future__ import print_function
def getDifference(b1, b2):
r = (b2 - b1) % 360.0
# Python modulus has same sign as divisor, which is positive here,
# so no need to consider negative case
if r >= 180.0:
r -= 360.0
return r
if __name__ == "__main__":
print ("Input in -180 to +180 range")
print (getDiff... |
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... | #REXX | REXX | /*REXX program finds the largest deranged word (within an identified dictionary). */
iFID= 'unixdict.txt'; words=0 /*input file ID; number of words so far*/
wL.=0 /*number of words of length L. so far*/
do while lines(iFID)\==0 ... |
http://rosettacode.org/wiki/Anonymous_recursion | Anonymous recursion | While implementing a recursive function, it often happens that we must resort to a separate helper function to handle the actual recursion.
This is usually the case when directly calling the current function would waste too many resources (stack space, execution time), causing unwanted side-effects, and/or the f... | #PARI.2FGP | PARI/GP | Fib(n)={
my(F=(k,f)->if(k<2,k,f(k-1,f)+f(k-2,f)));
if(n<0,(-1)^(n+1),1)*F(abs(n),F)
}; |
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
... | #Oforth | Oforth | import: mapping
Integer method: properDivs -- []
#[ self swap mod 0 == ] self 2 / seq filter ;
: amicables
| i j |
Array new
20000 loop: i [
i properDivs sum dup ->j i <= if continue then
j properDivs sum i <> if continue then
[ i, j ] over add
]
; |
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.
| #QB64 | QB64 | 'declare and initialize variables
CONST PI = 3.141592
DIM SHARED Bob_X, Bob_Y, Pivot_X, Pivot_Y, Rod_Length, Rod_Angle, Bob_Angular_Acceleration, Bob_Angular_Velocity, Delta_Time, Drawing_Scale, G AS DOUBLE
DIM SHARED exit_flag AS INTEGER
'set gravity to Earth's by default (in m/s squared)
G = -9.80665
'set the p... |
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... | #J | J | amb=. ([ , ' ' , ])&>/&.>@:((({:@:[ = {.@:])&>/&> # ])@:,@:({@(,&<)))
>@(amb&.>/) ('the';'that';'a');('frog';'elephant';'thing');('walked';'treaded';'grows');(<'slowly';'quickly')
+-----------------------+
|that thing grows slowly|
+-----------------------+ |
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... | #BQN | BQN | Acc ← {
𝕊 sum:
{sum+↩𝕩}
}
x ← Acc 1
X 5
Acc 3
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... | #C | C | #include <stdio.h>
//~ Take a number n and return a function that takes a number i
#define ACCUMULATOR(name,n) __typeof__(n) name (__typeof__(n) i) { \
static __typeof__(n) _n=n; LOGIC; }
//~ have it return n incremented by the accumulation of i
#define LOGIC return _n+=i
ACCUMULATOR(x,1.0)
ACCUMULATOR(y,3)
ACCUMUL... |
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
... | #360_Assembly | 360 Assembly | * Ackermann function 07/09/2015
&LAB XDECO ®,&TARGET
.*-----------------------------------------------------------------*
.* THIS MACRO DISPLAYS THE REGISTER CONTENTS AS A TRUE *
.* DECIMAL VALUE. XDECO IS NOT PART OF STANDARD S360 MACROS! *
*--------------------------------------... |
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)... | #Action.21 | Action! | PROC FillSumOfDivisors(CARD ARRAY pds CARD size,maxNum,offset)
CARD i,j
FOR i=0 TO size-1
DO
pds(i)=1
OD
FOR i=2 TO maxNum DO
FOR j=i+i TO maxNum STEP i
DO
IF j>=offset THEN
pds(j-offset)==+i
FI
OD
OD
RETURN
PROC Main()
DEFINE MAXNUM="20000"
DEFINE HALFNUM="10000"... |
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... | #AppleScript | AppleScript | -- COLUMN ALIGNMENTS ---------------------------------------------------------
property pstrLines : ¬
"Given$a$text$file$of$many$lines,$where$fields$within$a$line$\n" & ¬
"are$delineated$by$a$single$'dollar'$character,$write$a$program\n" & ¬
"that$aligns$each$column$of$fields$by$ensuring$that$words$in$eac... |
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... | #EchoLisp | EchoLisp |
(require 'timer)
;; returns an 'object' : (&lamdba; message [values])
;; messages : input, output, sample, inspect
(define (make-active)
(let [
(t0 #f) (dt 0)
(t 0) (Kt 0) ; K(t)
(S 0) (K 0)]
(lambda (message . args)
(case message
((output) (// S 2))
((input ) (set! K (car args)) (set! t0 #f)... |
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... | #Rust | Rust | fn perfect_powers(n: u128) -> Vec<u128> {
let mut powers = Vec::<u128>::new();
let sqrt = (n as f64).sqrt() as u128;
for i in 2..=sqrt {
let mut p = i * i;
while p < n {
powers.push(p);
p *= i;
}
}
powers.sort();
powers.dedup();
powers
}
fn b... |
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... | #Wren | Wren | import "./math" for Int
import "./seq" for Lst
import "./fmt" for Fmt
var maxDigits = 8
var limit = 10.pow(maxDigits)
var c = Int.primeSieve(limit-1, false)
var totient = Fn.new { |n|
var tot = n
var i = 2
while (i*i <= n) {
if (n%i == 0) {
while(n%i == 0) n = (n/i).floor
... |
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... | #Java | Java | import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.LongStream;
public class AliquotSequenceClassifications {
private static Long properDivsSum(long n) {
return LongStream.rangeClosed(1, (n + 1) / 2).filter(i -> n % i == 0 && n != i).sum();
}
sta... |
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... | #Pop11 | Pop11 | lib objectclass;
define :class foo;
enddefine;
define define_named_method(method, class);
lvars method_str = method >< '';
lvars class_str = class >< '';
lvars method_hash_str = 'hash_' >< length(class_str) >< '_'
>< class_str >< '_' >< length(method_str)
... |
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... | #PowerShell | PowerShell | $x = 42 `
| Add-Member -PassThru `
NoteProperty `
Title `
"The answer to the question about life, the universe and everything" |
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... | #Python | Python | class empty(object):
pass
e = empty() |
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... | #Raku | Raku | class Bar { } # an empty class
my $object = Bar.new; # new instance
role a_role { # role to add a variable: foo,
has $.foo is rw = 2; # with an initial value of 2
}
$object does a_role; # compose in the role
say $object.foo; # prints: 2
$object.foo = 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 |... | #PowerBASIC | PowerBASIC | 'get a variable's address:
DIM x AS INTEGER, y AS LONG
y = VARPTR(x)
'can't set the address of a single variable, but can access memory locations
DIM z AS INTEGER
z = PEEK(INTEGER, y)
'or can do it one byte at a time
DIM zz(1) AS BYTE
zz(0) = PEEK(BYTE, y)
zz(1) = PEEK(BYTE, y + 1)
'(MAK creates an INTEGER, LONG, o... |
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 |... | #PureBasic | PureBasic | a.i = 5
MessageRequester("Address",Str(@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 |... | #Python | Python | foo = object() # Create (instantiate) an empty object
address = id(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 |... | #QB64 | QB64 |
' Adapted from QB64wiki example a demo of _MEM type data and _MEM functions
Type points
x As Integer
y As Integer
z As Integer
End Type
Dim Shared m(3) As _MEM
Dim Shared Saved As points, first As points
m(1) = _Mem(first.x)
m(2) = _Mem(first.y)
m(3) = _Mem(first.z)
print "QB64 way to manage address... |
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 ... | #Elixir | Elixir | defmodule AKS do
def iterate(f, x), do: fn -> [x | iterate(f, f.(x))] end
def take(0, _lazy), do: []
def take(n, lazy) do
[value | next] = lazy.()
[value | take(n-1, next)]
end
def pascal, do: iterate(fn row -> [1 | sum_adj(row)] end, [1])
defp sum_adj([_] = l), do: l
defp sum_adj([a, b | _]... |
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.
... | #jq | jq | def is_prime:
. as $n
| if ($n < 2) then false
elif ($n % 2 == 0) then $n == 2
elif ($n % 3 == 0) then $n == 3
elif ($n % 5 == 0) then $n == 5
elif ($n % 7 == 0) then $n == 7
elif ($n % 11 == 0) then $n == 11
elif ($n % 13 == 0) then $n == 13
elif ($n % 17 == 0) then $n == 17... |
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.
... | #Haskell | Haskell | import Data.List (unfoldr)
-- infinite list of primes
primes = 2 : sieve [3,5..]
where sieve (x:xs) = x : sieve (filter (\y -> y `mod` x /= 0) xs)
-- primarity test, effective for numbers less then billion
isPrime n = all (\p -> n `mod` p /= 0) $ takeWhile (< sqrtN) primes
where sqrtN = round . sqrt . fromInteg... |
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... | #JavaScript | JavaScript | function almostPrime (n, k) {
var divisor = 2, count = 0
while(count < k + 1 && n != 1) {
if (n % divisor == 0) {
n = n / divisor
count = count + 1
} else {
divisor++
}
}
return count == k
}
for (var k = 1; k <= 5; k++) {
document.write("... |
http://rosettacode.org/wiki/Anagrams | Anagrams | When two or more words are composed of the same characters, but in a different order, they are called anagrams.
Task[edit]
Using the word list at http://wiki.puzzlers.org/pub/wordlists/unixdict.txt,
find the sets of words that share the same characters that contain the most words in them.
Related tasks
Word plays
... | #E | E | println("Downloading...")
when (def wordText := <http://wiki.puzzlers.org/pub/wordlists/unixdict.txt> <- getText()) -> {
def words := wordText.split("\n")
def storage := [].asMap().diverge()
def anagramTable extends storage {
to get(key) { return storage.fetch(key, fn { storage[key] := [].diverge(... |
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.
... | #Quackery | Quackery | [ $ "bigrat.qky" loadfile ] now!
[ v- -v
proper rot
360 mod
unrot improper
180 1 2over v< iff
[ 360 1 v- ] done
2dup -180 1 v< if
[ 360 1 v+ ] ] is angledelta ( n/d n/d --> n/d )
' [ [ $ "20" $ "45" ]
[ $ "-45" $ ... |
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.
... | #Racket | Racket | #lang racket
(define (% a b) (- a (* b (truncate (/ a b)))))
(define (bearing- bearing heading)
(- (% (+ (% (- bearing heading) 360) 540) 360) 180))
(module+ main
(bearing- 20 45)
(bearing- -45 45)
(bearing- -85 90)
(bearing- -95 90)
(bearing- -45 125)
(bearing- -45 145)
(bearing- 29.4803 -88.6381)
... |
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... | #Ring | Ring | # Project : Anagrams/Deranged anagrams
load "stdlib.ring"
fn1 = "unixdict.txt"
fp = fopen(fn1,"r")
str = fread(fp, getFileSize(fp))
fclose(fp)
strlist = str2list(str)
anagram = newlist(len(strlist), 5)
anag = list(len(strlist))
result = list(len(strlist))
for x = 1 to len(result)
result[x] = 0
next
for x = 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... | #Pascal | Pascal |
program AnonymousRecursion;
function Fib(X: Integer): integer;
function DoFib(N: Integer): Integer;
begin
if N < 2 then DoFib:=N
else DoFib:=DoFib(N-1) + DoFib(N-2);
end;
begin
if X < 0 then Fib:=X
else Fib:=DoFib(X);
end;
var I,V: integer;
begin
for I:=-1 to 15 do
begin
V:=Fib(I);
Write(I:3,' - '... |
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
... | #OCaml | OCaml | let rec isqrt n =
if n = 1 then 1
else let _n = isqrt (n - 1) in
(_n + (n / _n)) / 2
let sum_divs n =
let sum = ref 1 in
for d = 2 to isqrt n do
if (n mod d) = 0 then sum := !sum + (n / d + d);
done;
!sum
let () =
for n = 2 to 20000 do
let m = sum_divs n in
if (m > n) then
if (su... |
http://rosettacode.org/wiki/Animate_a_pendulum | Animate a pendulum |
One good way of making an animation is by simulating a physical system and illustrating the variables in that system using a dynamically changing graphical display.
The classic such physical system is a simple gravity pendulum.
Task
Create a simple physical model of a pendulum and animate it.
| #R | R | library(DescTools)
pendulum<-function(length=5,radius=1,circle.color="white",bg.color="white"){
tseq = c(seq(0,pi,by=.1),seq(pi,0,by=-.1))
slow=.27;fast=.07
sseq = c(seq(slow,fast,length.out = length(tseq)/4),seq(fast,slow,length.out = length(tseq)/4),seq(slow,fast,length.out = length(tseq)/4),seq(fast,slow,len... |
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... | #JavaScript | JavaScript | function ambRun(func) {
var choices = [];
var index;
function amb(values) {
if (values.length == 0) {
fail();
}
if (index == choices.length) {
choices.push({i: 0,
count: values.length});
}
var choice = choices[index+... |
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... | #C.23 | C# | using System;
class Program
{
static Func<dynamic, dynamic> Foo(dynamic n)
{
return i => n += i;
}
static void Main(string[] args)
{
var x = Foo(1);
x(5);
Foo(3);
Console.WriteLine(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... | #C.2B.2B | C++ | #include <iostream>
class Acc
{
public:
Acc(int init)
: _type(intType)
, _intVal(init)
{}
Acc(float init)
: _type(floatType)
, _floatVal(init)
{}
int operator()(int x)
{
if( _type == intType )
{
_intVal += x;
return _i... |
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
... | #68000_Assembly | 68000 Assembly | ;
; Ackermann function for Motorola 68000 under AmigaOs 2+ by Thorham
;
; Set stack space to 60000 for m = 3, n = 5.
;
; The program will print the ackermann values for the range m = 0..3, n = 0..5
;
_LVOOpenLibrary equ -552
_LVOCloseLibrary equ -414
_LVOVPrintf equ -954
m equ 3 ; Nr of iterations for the main loop.
... |
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)... | #Ada | Ada | with Ada.Text_IO, Generic_Divisors;
procedure ADB_Classification is
function Same(P: Positive) return Positive is (P);
package Divisor_Sum is new Generic_Divisors
(Result_Type => Natural, None => 0, One => Same, Add => "+");
type Class_Type is (Deficient, Perfect, Abundant);
function Class(D_... |
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... | #ARM_Assembly | ARM Assembly |
/* ARM assembly Raspberry PI */
/* program alignColumn.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/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... | #Erlang | Erlang |
-module( active_object ).
-export( [delete/1, input/2, new/0, output/1, task/1] ).
-compile({no_auto_import,[time/0]}).
delete( Object ) ->
Object ! stop.
input( Object, Fun ) ->
Object ! {input, Fun}.
new( ) ->
K = fun zero/1,
S = 0,
T0 = seconds_with_decimals(),
erlang:spaw... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.