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/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
{\displaystyle =M}
as well as
s
u
m
(
p
r
o
p
D
i
v
s
(
M
)
)
=
N
{\displaystyle \mathrm {sum} (\mathrm {propDivs} (M))=N}
.
Example
1184 and 1210 are an amicable pair, with proper divisors:
1, 2, 4, 8, 16, 32, 37, 74, 148, 296, 592 and
1, 2, 5, 10, 11, 22, 55, 110, 121, 242, 605 respectively.
Task
Calculate and show here the Amicable pairs below 20,000; (there are eight).
Related tasks
Proper divisors
Abundant, deficient and perfect number classifications
Aliquot sequence classifications and its amicable classification.
| #ReScript | ReScript | let isqrt = (v) => {
Belt.Float.toInt(
sqrt(Belt.Int.toFloat(v)))
}
let sum_divs = (n) => {
let sum = ref(1)
for d in 2 to isqrt(n) {
if mod(n, d) == 0 {
sum.contents = sum.contents + (n / d + d)
}
}
sum.contents
}
{
for n in 2 to 20000 {
let m = sum_divs(n)
if (m > n) {
if sum_divs(m) == n {
Printf.printf("%d %d\n", n, m)
}
}
}
}
|
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 variable number of expressions (or values if that's simpler in the language) and yields a correct one which will satisfy a constraint in some future computation, thereby avoiding failure.
Problems whose solution the Amb operator naturally expresses can be approached with other tools, such as explicit nested iterations over data sets, or with pattern matching. By contrast, the Amb operator appears integrated into the language. Invocations of Amb are not wrapped in any visible loops or other search patterns; they appear to be independent.
Essentially Amb(x, y, z) splits the computation into three possible futures: a future in which the value x is yielded, a future in which the value y is yielded and a future in which the value z is yielded. The future which leads to a successful subsequent computation is chosen. The other "parallel universes" somehow go away. Amb called with no arguments fails.
For simplicity, one of the domain values usable with Amb may denote failure, if that is convenient. For instance, it is convenient if a Boolean false denotes failure, so that Amb(false) fails, and thus constraints can be expressed using Boolean expressions like Amb(x * y == 8) which unless x and y add to four.
A pseudo-code program which satisfies this constraint might look like:
let x = Amb(1, 2, 3)
let y = Amb(7, 6, 4, 5)
Amb(x * y = 8)
print x, y
The output is 2 4 because Amb(1, 2, 3) correctly chooses the future in which x has value 2, Amb(7, 6, 4, 5) chooses 4 and consequently Amb(x * y = 8) produces a success.
Alternatively, failure could be represented using strictly Amb():
unless x * y = 8 do Amb()
Or else Amb could take the form of two operators or functions: one for producing values and one for enforcing constraints:
let x = Ambsel(1, 2, 3)
let y = Ambsel(4, 5, 6)
Ambassert(x * y = 8)
print x, y
where Ambassert behaves like Amb() if the Boolean expression is false, otherwise it allows the future computation to take place, without yielding any value.
The task is to somehow implement Amb, and demonstrate it with a program which chooses one word from each of the following four sets of character strings to generate a four-word sentence:
"the" "that" "a"
"frog" "elephant" "thing"
"walked" "treaded" "grows"
"slowly" "quickly"
The constraint to be satisfied is that the last character of each word (other than the last) is the same as the first character of its successor.
The only successful sentence is "that thing grows slowly"; other combinations do not satisfy the constraint and thus fail.
The goal of this task isn't to simply process the four lists of words with explicit, deterministic program flow such as nested iteration, to trivially demonstrate the correct output. The goal is to implement the Amb operator, or a facsimile thereof that is possible within the language limitations.
| #Prolog | Prolog | amb(E, [E|_]).
amb(E, [_|ES]) :- amb(E, ES).
joins(Left, Right) :-
append(_, [T], Left),
append([R], _, Right),
( T \= R -> amb(_, []) % (explicitly using amb fail as required)
; true ).
amb_example([Word1, Word2, Word3, Word4]) :-
amb(Word1, ["the","that","a"]),
amb(Word2, ["frog","elephant","thing"]),
amb(Word3, ["walked","treaded","grows"]),
amb(Word4, ["slowly","quickly"]),
joins(Word1, Word2),
joins(Word2, Word3),
joins(Word3, Word4). |
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 accumulator (including the initial value passed when the accumulator was created).
Rules
The detailed rules are at http://paulgraham.com/accgensub.html and are reproduced here for simplicity (with additions in small italic text).
Before you submit an example, make sure the function
Takes a number n and returns a function (lets call it g), that takes a number i, and returns n incremented by the accumulation of i from every call of function g(i).
Although these exact function and parameter names need not be used
Works for any numeric type-- i.e. can take both ints and floats and returns functions that can take both ints and floats. (It is not enough simply to convert all input to floats. An accumulator that has only seen integers must return integers.) (i.e., if the language doesn't allow for numeric polymorphism, you have to use overloading or something like that)
Generates functions that return the sum of every number ever passed to them, not just the most recent. (This requires a piece of state to hold the accumulated value, which in turn means that pure functional languages can't be used for this task.)
Returns a real function, meaning something that you can use wherever you could use a function you had defined in the ordinary way in the text of your program. (Follow your language's conventions here.)
Doesn't store the accumulated value or the returned functions in a way that could cause them to be inadvertently modified by other code. (No global variables or other such things.)
E.g. if after the example, you added the following code (in a made-up language) where the factory function is called foo:
x = foo(1);
x(5);
foo(3);
print x(2.3);
It should print 8.3. (There is no need to print the form of the accumulator function returned by foo(3); it's not part of the task at all.)
Task
Create a function that implements the described rules.
It need not handle any special error cases not described above. The simplest way to implement the task as described is typically to use a closure, providing the language supports them.
Where it is not possible to hold exactly to the constraints above, describe the deviations.
| #Lambdatalk | Lambdatalk |
{def acc
{lambda {:a :n}
{+ {A.toS {A.addlast! :n :a}}}}}
-> acc
1) using a global:
{def A {A.new 1}}
-> A
{acc {A} 5}
-> 6
{acc {A} 2.3}
-> 8.3
2) inside a local context:
{let { {:a {A.new 1}}
} {br}{acc :a 5}
{br}{acc :a 2.3}
} ->
6
8.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 accumulator (including the initial value passed when the accumulator was created).
Rules
The detailed rules are at http://paulgraham.com/accgensub.html and are reproduced here for simplicity (with additions in small italic text).
Before you submit an example, make sure the function
Takes a number n and returns a function (lets call it g), that takes a number i, and returns n incremented by the accumulation of i from every call of function g(i).
Although these exact function and parameter names need not be used
Works for any numeric type-- i.e. can take both ints and floats and returns functions that can take both ints and floats. (It is not enough simply to convert all input to floats. An accumulator that has only seen integers must return integers.) (i.e., if the language doesn't allow for numeric polymorphism, you have to use overloading or something like that)
Generates functions that return the sum of every number ever passed to them, not just the most recent. (This requires a piece of state to hold the accumulated value, which in turn means that pure functional languages can't be used for this task.)
Returns a real function, meaning something that you can use wherever you could use a function you had defined in the ordinary way in the text of your program. (Follow your language's conventions here.)
Doesn't store the accumulated value or the returned functions in a way that could cause them to be inadvertently modified by other code. (No global variables or other such things.)
E.g. if after the example, you added the following code (in a made-up language) where the factory function is called foo:
x = foo(1);
x(5);
foo(3);
print x(2.3);
It should print 8.3. (There is no need to print the form of the accumulator function returned by foo(3); it's not part of the task at all.)
Task
Create a function that implements the described rules.
It need not handle any special error cases not described above. The simplest way to implement the task as described is typically to use a closure, providing the language supports them.
Where it is not possible to hold exactly to the constraints above, describe the deviations.
| #LFE | LFE |
(defun accum (m)
(lambda (n)
(let ((sum (+ m n)))
`(#(func ,(accum sum))
#(sum ,sum)))))
|
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
−
1
,
1
)
if
m
>
0
and
n
=
0
A
(
m
−
1
,
A
(
m
,
n
−
1
)
)
if
m
>
0
and
n
>
0.
{\displaystyle A(m,n)={\begin{cases}n+1&{\mbox{if }}m=0\\A(m-1,1)&{\mbox{if }}m>0{\mbox{ and }}n=0\\A(m-1,A(m,n-1))&{\mbox{if }}m>0{\mbox{ and }}n>0.\end{cases}}}
Its arguments are never negative and it always terminates.
Task
Write a function which returns the value of
A
(
m
,
n
)
{\displaystyle A(m,n)}
. Arbitrary precision is preferred (since the function grows so quickly), but not required.
See also
Conway chained arrow notation for the Ackermann function.
| #AutoIt | AutoIt | Func Ackermann($m, $n)
If ($m = 0) Then
Return $n+1
Else
If ($n = 0) Then
Return Ackermann($m-1, 1)
Else
return Ackermann($m-1, Ackermann($m, $n-1))
EndIf
EndIf
EndFunc |
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) == n then n is classed as perfect (OEIS A000396).
if P(n) > n then n is classed as abundant (OEIS A005101).
Example
6 has proper divisors of 1, 2, and 3.
1 + 2 + 3 = 6, so 6 is classed as a perfect number.
Task
Calculate how many of the integers 1 to 20,000 (inclusive) are in each of the three classes.
Show the results here.
Related tasks
Aliquot sequence classifications. (The whole series from which this task is a subset.)
Proper divisors
Amicable pairs
| #Cowgol | Cowgol | include "cowgol.coh";
const MAXIMUM := 20000;
var p: uint16[MAXIMUM+1];
var i: uint16;
var j: uint16;
MemZero(&p as [uint8], @bytesof p);
i := 1;
while i <= MAXIMUM/2 loop
j := i+i;
while j <= MAXIMUM loop
p[j] := p[j]+i;
j := j+i;
end loop;
i := i+1;
end loop;
var def: uint16 := 0;
var per: uint16 := 0;
var ab: uint16 := 0;
i := 1;
while i <= MAXIMUM loop
if p[i]<i then
def := def + 1;
elseif p[i]==i then
per := per + 1;
else
ab := ab + 1;
end if;
i := i + 1;
end loop;
print_i16(def); print(" deficient numbers.\n");
print_i16(per); print(" perfect numbers.\n");
print_i16(ab); print(" abundant numbers.\n"); |
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, or center justified within its column.
Use the following text to test your programs:
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,$or$center$justified$within$its$column.
Note that:
The example input texts lines may, or may not, have trailing dollar characters.
All columns should share the same alignment.
Consecutive space characters produced adjacent to the end of lines are insignificant for the purposes of the task.
Output text will be viewed in a mono-spaced font on a plain text editor or basic terminal.
The minimum space between columns should be computed from the text and not hard-coded.
It is not a requirement to add separating characters between or around columns.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Elixir | Elixir | defmodule Align do
def columns(text, alignment) do
fieldsbyrow = String.split(text, "\n", trim: true)
|> Enum.map(fn row -> String.split(row, "$", trim: true) end)
maxfields = Enum.map(fieldsbyrow, fn field -> length(field) end) |> Enum.max
colwidths = Enum.map(fieldsbyrow, fn field -> field ++ List.duplicate("", maxfields - length(field)) end)
|> List.zip
|> Enum.map(fn column ->
Tuple.to_list(column) |> Enum.map(fn col-> String.length(col) end) |> Enum.max
end)
Enum.each(fieldsbyrow, fn row ->
Enum.zip(row, colwidths)
|> Enum.map(fn {field, width} -> adjust(field, width, alignment) end)
|> Enum.join(" ") |> IO.puts
end)
end
defp adjust(field, width, :Left), do: String.pad_trailing(field, width)
defp adjust(field, width, :Right), do: String.pad_leading(field, width)
defp adjust(field, width, _), do: :string.centre(String.to_charlist(field), width)
end
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$
justified,$right$justified,$or$center$justified$within$its$column.
"""
Enum.each([:Left, :Right, :Center], fn alignment ->
IO.puts "\n# #{alignment} Column-aligned output:"
Align.columns(text, alignment)
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 synchronization mechanism with the encapsulated task in order to prevent object's state corruption.
A typical instance of an active object is an animation widget. The widget state changes with the time, while as an object it has all properties of a normal widget.
The task
Implement an active integrator object. The object has an input and output. The input can be set using the method Input. The input is a function of time. The output can be queried using the method Output. The object integrates its input over the time and the result becomes the object's output. So if the input is K(t) and the output is S, the object state S is changed to S + (K(t1) + K(t0)) * (t1 - t0) / 2, i.e. it integrates K using the trapeze method. Initially K is constant 0 and S is 0.
In order to test the object:
set its input to sin (2π f t), where the frequency f=0.5Hz. The phase is irrelevant.
wait 2s
set the input to constant 0
wait 0.5s
Verify that now the object's output is approximately 0 (the sine has the period of 2s). The accuracy of the result will depend on the OS scheduler time slicing and the accuracy of the clock.
| #SuperCollider | SuperCollider |
(
a = TaskProxy { |envir|
envir.use {
~integral = 0;
~time = 0;
~prev = 0;
~running = true;
loop {
~val = ~input.(~time);
~integral = ~integral + (~val + ~prev * ~dt / 2);
~prev = ~val;
~time = ~time + ~dt;
~dt.wait;
}
}
};
)
// run the test
(
fork {
a.set(\dt, 0.0001);
a.set(\input, { |t| sin(2pi * 0.5 * t) });
a.play(quant: 0); // play immediately
2.wait;
a.set(\input, 0);
0.5.wait;
a.stop;
a.get(\integral).postln; // answers -7.0263424372343e-15
}
)
|
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 synchronization mechanism with the encapsulated task in order to prevent object's state corruption.
A typical instance of an active object is an animation widget. The widget state changes with the time, while as an object it has all properties of a normal widget.
The task
Implement an active integrator object. The object has an input and output. The input can be set using the method Input. The input is a function of time. The output can be queried using the method Output. The object integrates its input over the time and the result becomes the object's output. So if the input is K(t) and the output is S, the object state S is changed to S + (K(t1) + K(t0)) * (t1 - t0) / 2, i.e. it integrates K using the trapeze method. Initially K is constant 0 and S is 0.
In order to test the object:
set its input to sin (2π f t), where the frequency f=0.5Hz. The phase is irrelevant.
wait 2s
set the input to constant 0
wait 0.5s
Verify that now the object's output is approximately 0 (the sine has the period of 2s). The accuracy of the result will depend on the OS scheduler time slicing and the accuracy of the clock.
| #Swift | Swift | // For NSObject, NSTimeInterval and NSThread
import Foundation
// For PI and sin
import Darwin
class ActiveObject:NSObject {
let sampling = 0.1
var K: (t: NSTimeInterval) -> Double
var S: Double
var t0, t1: NSTimeInterval
var thread = NSThread()
func integrateK() {
t0 = t1
t1 += sampling
S += (K(t:t1) + K(t: t0)) * (t1 - t0) / 2
}
func updateObject() {
while true {
integrateK()
usleep(100000)
}
}
init(function: (NSTimeInterval) -> Double) {
S = 0
t0 = 0
t1 = 0
K = function
super.init()
thread = NSThread(target: self, selector: "updateObject", object: nil)
thread.start()
}
func Input(function: (NSTimeInterval) -> Double) {
K = function
}
func Output() -> Double {
return S
}
}
// main
func sine(t: NSTimeInterval) -> Double {
let f = 0.5
return sin(2 * M_PI * f * t)
}
var activeObject = ActiveObject(function: sine)
var date = NSDate()
sleep(2)
activeObject.Input({(t: NSTimeInterval) -> Double in return 0.0})
usleep(500000)
println(activeObject.Output())
|
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 second term is K then all future terms are also K and so the sequence repeats from the first term with period 1 and K is called perfect.
If the third term would be repeating K then the sequence repeats with period 2 and K is called amicable.
If the Nth term would be repeating K for the first time, with N > 3 then the sequence repeats with period N - 1 and K is called sociable.
Perfect, amicable and sociable numbers eventually repeat the original number K; there are other repetitions...
Some K have a sequence that eventually forms a periodic repetition of period 1 but of a number other than K, for example 95 which forms the sequence 95, 25, 6, 6, 6, ... such K are called aspiring.
K that have a sequence that eventually forms a periodic repetition of period >= 2 but of a number other than K, for example 562 which forms the sequence 562, 284, 220, 284, 220, ... such K are called cyclic.
And finally:
Some K form aliquot sequences that are not known to be either terminating or periodic; these K are to be called non-terminating.
For the purposes of this task, K is to be classed as non-terminating if it has not been otherwise classed after generating 16 terms or if any term of the sequence is greater than 2**47 = 140,737,488,355,328.
Task
Create routine(s) to generate the aliquot sequence of a positive integer enough to classify it according to the classifications given above.
Use it to display the classification and sequences of the numbers one to ten inclusive.
Use it to show the classification and sequences of the following integers, in order:
11, 12, 28, 496, 220, 1184, 12496, 1264460, 790, 909, 562, 1064, 1488, and optionally 15355717786080.
Show all output on this page.
Related tasks
Abundant, deficient and perfect number classifications. (Classifications from only the first two members of the whole sequence).
Proper divisors
Amicable pairs
| #Rust | Rust | #[derive(Debug)]
enum AliquotType { Terminating, Perfect, Amicable, Sociable, Aspiring, Cyclic, NonTerminating }
fn classify_aliquot(num: i64) -> (AliquotType, Vec<i64>) {
let limit = 1i64 << 47; //140737488355328
let mut terms = Some(num).into_iter().collect::<Vec<_>>();
for i in 0..16 {
let n = terms[i];
let divsum = (1..(n + 1) / 2 + 1).filter(|&x| n % x == 0 && n != x).fold(0, |sum, x| sum + x);
let classification = if divsum == 0 {
Some(AliquotType::Terminating)
}
else if divsum > limit {
Some(AliquotType::NonTerminating)
}
else if let Some(prev_idx) = terms.iter().position(|&x| x == divsum) {
let cycle_len = terms.len() - prev_idx;
Some(if prev_idx == 0 {
match cycle_len {
1 => AliquotType::Perfect,
2 => AliquotType::Amicable,
_ => AliquotType::Sociable
}
}
else {
if cycle_len == 1 {AliquotType::Aspiring} else {AliquotType::Cyclic}
})
}
else {
None
};
terms.push(divsum);
if let Some(result) = classification {
return (result, terms);
}
}
(AliquotType::NonTerminating, terms)
}
fn main() {
let nums = [1i64, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 28, 496, 220, 1184, 12496, 1264460, 790, 909, 562, 1064, 1488/*, 15355717786080*/];
for num in &nums {
println!("{} {:?}", num, classify_aliquot(*num));
}
} |
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 expansion of
(
x
−
1
)
p
−
(
x
p
−
1
)
{\displaystyle (x-1)^{p}-(x^{p}-1)}
are divisible by
p
{\displaystyle p}
.
Example
Using
p
=
3
{\displaystyle p=3}
:
(x-1)^3 - (x^3 - 1)
= (x^3 - 3x^2 + 3x - 1) - (x^3 - 1)
= -3x^2 + 3x
And all the coefficients are divisible by 3, so 3 is prime.
Note:
This task is not the AKS primality test. It is an inefficient exponential time algorithm discovered in the late 1600s and used as an introductory lemma in the AKS derivation.
Task
Create a function/subroutine/method that given
p
{\displaystyle p}
generates the coefficients of the expanded polynomial representation of
(
x
−
1
)
p
{\displaystyle (x-1)^{p}}
.
Use the function to show here the polynomial expansions of
(
x
−
1
)
p
{\displaystyle (x-1)^{p}}
for
p
{\displaystyle p}
in the range 0 to at least 7, inclusive.
Use the previous function in creating another function that when given
p
{\displaystyle p}
returns whether
p
{\displaystyle p}
is prime using the theorem.
Use your test to generate a list of all primes under 35.
As a stretch goal, generate all primes under 50 (needs integers larger than 31-bit).
References
Agrawal-Kayal-Saxena (AKS) primality test (Wikipedia)
Fool-Proof Test for Primes - Numberphile (Video). The accuracy of this video is disputed -- at best it is an oversimplification.
| #Objeck | Objeck | class AksTest {
@c : static : Int[];
function : Main(args : String[]) ~ Nil {
@c := Int->New[100];
for(n := 0; n < 10; n++;) {
Coef(n);
"(x-1)^ {$n} = "->Print();
Show(n);
'\n'->Print();
};
"\nPrimes:"->PrintLine();
for(n := 2; n <= 63; n++;) {
if(IsPrime(n)) {
" {$n}"->Print();
};
};
'\n'->Print();
}
function : native : Coef(n : Int) ~ Nil {
i := 0; j := 0;
if (n < 0 | n > 63) {
Runtime->Exit(0);
};
for(@c[0] := 1; i < n; i++;) {
j := i;
for(@c[1 + j] := 1; j > 0; j--;) {
@c[j] := @c[j-1] - @c[j];
};
@c[0] := @c[0] * -1;
};
}
function : native : IsPrime(n : Int) ~ Bool {
Coef(n);
@c[0] += 1; @c[n] -= 1;
i:=n;
while (i <> 0 & (@c[i] % n) = 0) {
i--;
};
return i = 0;
}
function : Show(n : Int) ~ Nil {
do {
value := @c[n];
"+{$value}x^{$n}"->Print();
} while (n-- <> 0);
}
} |
http://rosettacode.org/wiki/Almost_prime | Almost prime | A k-Almost-prime is a natural number
n
{\displaystyle n}
that is the product of
k
{\displaystyle k}
(possibly identical) primes.
Example
1-almost-primes, where
k
=
1
{\displaystyle k=1}
, are the prime numbers themselves.
2-almost-primes, where
k
=
2
{\displaystyle k=2}
, are the semiprimes.
Task
Write a function/method/subroutine/... that generates k-almost primes and use it to create a table here of the first ten members of k-Almost primes for
1
<=
K
<=
5
{\displaystyle 1<=K<=5}
.
Related tasks
Semiprime
Category:Prime Numbers
| #REXX | REXX | /*REXX program computes and displays the first N K─almost primes from 1 ──► K. */
parse arg N K . /*get optional arguments from the C.L. */
if N=='' | N=="," then N=10 /*N not specified? Then use default.*/
if K=='' | K=="," then K= 5 /*K " " " " " */
/*W: is the width of K, used for output*/
do m=1 for K; $=2**m; fir=$ /*generate & assign 1st K─almost prime.*/
#=1; if #==N then leave /*#: K─almost primes; Enough are found?*/
#=2; $=$ 3*(2**(m-1)) /*generate & append 2nd K─almost prime.*/
if #==N then leave /*#: K─almost primes; Enough are found?*/
if m==1 then _=fir + fir /* [↓] gen & append 3rd K─almost prime*/
else do; _=9 * (2**(m-2)); #=3; $=$ _; end
do j=_ + m - 1 until #==N /*process an K─almost prime N times.*/
if factr()\==m then iterate /*not the correct K─almost prime? */
#=# + 1; $=$ j /*bump K─almost counter; append it to $*/
end /*j*/ /* [↑] generate N K─almost primes.*/
say right(m, length(K))"─almost ("N') primes:' $
end /*m*/ /* [↑] display a line for each K─prime*/
exit /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
factr: z=j; do f=0 while z// 2==0; z=z% 2; end /*divisible by 2.*/
do f=f while z// 3==0; z=z% 3; end /*divisible " 3.*/
do f=f while z// 5==0; z=z% 5; end /*divisible " 5.*/
do f=f while z// 7==0; z=z% 7; end /*divisible " 7.*/
do f=f while z//11==0; z=z%11; end /*divisible " 11.*/
do f=f while z//13==0; z=z%13; end /*divisible " 13.*/
do p=17 by 6 while p<=z /*insure P isn't divisible by three. */
parse var p '' -1 _ /*obtain the right─most decimal digit. */
/* [↓] fast check for divisible by 5. */
if _\==5 then do; do f=f+1 while z//p==0; z=z%p; end; f=f-1; end /*÷ by P? */
if _ ==3 then iterate /*fast check for X divisible by five.*/
x=p+2; do f=f+1 while z//x==0; z=z%x; end; f=f-1 /*÷ by X? */
end /*i*/ /* [↑] find all the factors in Z. */
if f==0 then return 1 /*if prime (f==0), then return unity.*/
return f /*return to invoker the number of divs.*/ |
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
Ordered words
Palindrome detection
Semordnilap
Anagrams
Anagrams/Deranged anagrams
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #J | J | (#~ a: ~: {:"1) (]/.~ /:~&>) <;._2 ] 1!:1 <'unixdict.txt'
+-----+-----+-----+-----+-----+
|abel |able |bale |bela |elba |
+-----+-----+-----+-----+-----+
|alger|glare|lager|large|regal|
+-----+-----+-----+-----+-----+
|angel|angle|galen|glean|lange|
+-----+-----+-----+-----+-----+
|caret|carte|cater|crate|trace|
+-----+-----+-----+-----+-----+
|elan |lane |lean |lena |neal |
+-----+-----+-----+-----+-----+
|evil |levi |live |veil |vile |
+-----+-----+-----+-----+-----+ |
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 function doesn't have the right arguments and/or return values.
So we end up inventing some silly name like foo2 or foo_helper. I have always found it painful to come up with a proper name, and see some disadvantages:
You have to think up a name, which then pollutes the namespace
Function is created which is called from nowhere else
The program flow in the source code is interrupted
Some languages allow you to embed recursion directly in-place. This might work via a label, a local gosub instruction, or some special keyword.
Anonymous recursion can also be accomplished using the Y combinator.
Task
If possible, demonstrate this by writing the recursive version of the fibonacci function (see Fibonacci sequence) which checks for a negative argument before doing the actual recursion.
| #Seed7 | Seed7 | $ include "seed7_05.s7i";
const func integer: fib (in integer: x) is func
result
var integer: fib is 0;
local
const func integer: fib1 (in integer: n) is func
result
var integer: fib1 is 0;
begin
if n < 2 then
fib1 := n;
else
fib1 := fib1(n-2) + fib1(n-1);
end if;
end func;
begin
if x < 0 then
raise RANGE_ERROR;
else
fib := fib1(x);
end if;
end func;
const proc: main is func
local
var integer: i is 0;
begin
for i range 0 to 4 do
writeln(fib(i));
end for;
end func; |
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
{\displaystyle =M}
as well as
s
u
m
(
p
r
o
p
D
i
v
s
(
M
)
)
=
N
{\displaystyle \mathrm {sum} (\mathrm {propDivs} (M))=N}
.
Example
1184 and 1210 are an amicable pair, with proper divisors:
1, 2, 4, 8, 16, 32, 37, 74, 148, 296, 592 and
1, 2, 5, 10, 11, 22, 55, 110, 121, 242, 605 respectively.
Task
Calculate and show here the Amicable pairs below 20,000; (there are eight).
Related tasks
Proper divisors
Abundant, deficient and perfect number classifications
Aliquot sequence classifications and its amicable classification.
| #REXX | REXX |
/*REXX*/
Call time 'R'
Do x=1 To 20000
pd=proper_divisors(x)
sumpd.x=sum(pd)
End
Say 'sum(pd) computed in' time('E') 'seconds'
Call time 'R'
Do x=1 To 20000
/* If x//1000=0 Then Say x time() */
Do y=x+1 To 20000
If y=sumpd.x &,
x=sumpd.y Then
Say x y 'found after' time('E') 'seconds'
End
End
Say time('E') 'seconds total search time'
Exit
proper_divisors: Procedure
Parse Arg n
Pd=''
If n=1 Then Return ''
If n//2=1 Then /* odd number */
delta=2
Else /* even number */
delta=1
Do d=1 To n%2 By delta
If n//d=0 Then
pd=pd d
End
Return space(pd)
sum: Procedure
Parse Arg list
sum=0
Do i=1 To words(list)
sum=sum+word(list,i)
End
Return sum |
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 variable number of expressions (or values if that's simpler in the language) and yields a correct one which will satisfy a constraint in some future computation, thereby avoiding failure.
Problems whose solution the Amb operator naturally expresses can be approached with other tools, such as explicit nested iterations over data sets, or with pattern matching. By contrast, the Amb operator appears integrated into the language. Invocations of Amb are not wrapped in any visible loops or other search patterns; they appear to be independent.
Essentially Amb(x, y, z) splits the computation into three possible futures: a future in which the value x is yielded, a future in which the value y is yielded and a future in which the value z is yielded. The future which leads to a successful subsequent computation is chosen. The other "parallel universes" somehow go away. Amb called with no arguments fails.
For simplicity, one of the domain values usable with Amb may denote failure, if that is convenient. For instance, it is convenient if a Boolean false denotes failure, so that Amb(false) fails, and thus constraints can be expressed using Boolean expressions like Amb(x * y == 8) which unless x and y add to four.
A pseudo-code program which satisfies this constraint might look like:
let x = Amb(1, 2, 3)
let y = Amb(7, 6, 4, 5)
Amb(x * y = 8)
print x, y
The output is 2 4 because Amb(1, 2, 3) correctly chooses the future in which x has value 2, Amb(7, 6, 4, 5) chooses 4 and consequently Amb(x * y = 8) produces a success.
Alternatively, failure could be represented using strictly Amb():
unless x * y = 8 do Amb()
Or else Amb could take the form of two operators or functions: one for producing values and one for enforcing constraints:
let x = Ambsel(1, 2, 3)
let y = Ambsel(4, 5, 6)
Ambassert(x * y = 8)
print x, y
where Ambassert behaves like Amb() if the Boolean expression is false, otherwise it allows the future computation to take place, without yielding any value.
The task is to somehow implement Amb, and demonstrate it with a program which chooses one word from each of the following four sets of character strings to generate a four-word sentence:
"the" "that" "a"
"frog" "elephant" "thing"
"walked" "treaded" "grows"
"slowly" "quickly"
The constraint to be satisfied is that the last character of each word (other than the last) is the same as the first character of its successor.
The only successful sentence is "that thing grows slowly"; other combinations do not satisfy the constraint and thus fail.
The goal of this task isn't to simply process the four lists of words with explicit, deterministic program flow such as nested iteration, to trivially demonstrate the correct output. The goal is to implement the Amb operator, or a facsimile thereof that is possible within the language limitations.
| #PureBasic | PureBasic | Procedure Words_Ok(String1.s, String2.s)
If Mid(String1,Len(String1),1)=Mid(String2,1,1)
ProcedureReturn #True
EndIf
ProcedureReturn #False
EndProcedure
Procedure.s Amb(Array A.s(1), Array B.s(1), Array C.s(1), Array D.s(1))
Protected a, b, c, d
For a=0 To ArraySize(A())
For b=0 To ArraySize(B())
For c=0 To ArraySize(C())
For d=0 To ArraySize(D())
If Words_Ok(A(a),B(b)) And Words_Ok(B(b),C(c)) And Words_Ok(C(c),D(d))
ProcedureReturn A(a)+" "+B(b)+" "+C(c)+" "+D(d)
EndIf
Next
Next
Next
Next
ProcedureReturn "" ; Empty string, e.g. fail
EndProcedure
If OpenConsole()
Define Text.s
Dim Set1.s(2)
Dim Set2.s(2)
Dim Set3.s(2)
Dim Set4.s(1)
Set1(0)="the": set1(1)="that": set1(2)="a"
Set2(0)="frog": set2(1)="elephant": set2(2)="thing"
Set3(0)="walked": set3(1)="treaded": set3(2)="grows"
Set4(0)="slowly": set4(1)="quickly"
text=Amb(set1(),set2(),Set3(),set4())
If Text<>""
PrintN("Correct sentence would be,"+#CRLF$+Text)
Else
PrintN("Failed to fine a correct sentence.")
EndIf
PrintN(#CRLF$+#CRLF$+"Press ENTER to exit."): Input()
CloseConsole()
EndIf |
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 accumulator (including the initial value passed when the accumulator was created).
Rules
The detailed rules are at http://paulgraham.com/accgensub.html and are reproduced here for simplicity (with additions in small italic text).
Before you submit an example, make sure the function
Takes a number n and returns a function (lets call it g), that takes a number i, and returns n incremented by the accumulation of i from every call of function g(i).
Although these exact function and parameter names need not be used
Works for any numeric type-- i.e. can take both ints and floats and returns functions that can take both ints and floats. (It is not enough simply to convert all input to floats. An accumulator that has only seen integers must return integers.) (i.e., if the language doesn't allow for numeric polymorphism, you have to use overloading or something like that)
Generates functions that return the sum of every number ever passed to them, not just the most recent. (This requires a piece of state to hold the accumulated value, which in turn means that pure functional languages can't be used for this task.)
Returns a real function, meaning something that you can use wherever you could use a function you had defined in the ordinary way in the text of your program. (Follow your language's conventions here.)
Doesn't store the accumulated value or the returned functions in a way that could cause them to be inadvertently modified by other code. (No global variables or other such things.)
E.g. if after the example, you added the following code (in a made-up language) where the factory function is called foo:
x = foo(1);
x(5);
foo(3);
print x(2.3);
It should print 8.3. (There is no need to print the form of the accumulator function returned by foo(3); it's not part of the task at all.)
Task
Create a function that implements the described rules.
It need not handle any special error cases not described above. The simplest way to implement the task as described is typically to use a closure, providing the language supports them.
Where it is not possible to hold exactly to the constraints above, describe the deviations.
| #Lua | Lua | function acc(init)
init = init or 0
return function(delta)
init = init + (delta or 0)
return init
end
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 accumulator (including the initial value passed when the accumulator was created).
Rules
The detailed rules are at http://paulgraham.com/accgensub.html and are reproduced here for simplicity (with additions in small italic text).
Before you submit an example, make sure the function
Takes a number n and returns a function (lets call it g), that takes a number i, and returns n incremented by the accumulation of i from every call of function g(i).
Although these exact function and parameter names need not be used
Works for any numeric type-- i.e. can take both ints and floats and returns functions that can take both ints and floats. (It is not enough simply to convert all input to floats. An accumulator that has only seen integers must return integers.) (i.e., if the language doesn't allow for numeric polymorphism, you have to use overloading or something like that)
Generates functions that return the sum of every number ever passed to them, not just the most recent. (This requires a piece of state to hold the accumulated value, which in turn means that pure functional languages can't be used for this task.)
Returns a real function, meaning something that you can use wherever you could use a function you had defined in the ordinary way in the text of your program. (Follow your language's conventions here.)
Doesn't store the accumulated value or the returned functions in a way that could cause them to be inadvertently modified by other code. (No global variables or other such things.)
E.g. if after the example, you added the following code (in a made-up language) where the factory function is called foo:
x = foo(1);
x(5);
foo(3);
print x(2.3);
It should print 8.3. (There is no need to print the form of the accumulator function returned by foo(3); it's not part of the task at all.)
Task
Create a function that implements the described rules.
It need not handle any special error cases not described above. The simplest way to implement the task as described is typically to use a closure, providing the language supports them.
Where it is not possible to hold exactly to the constraints above, describe the deviations.
| #M2000_Interpreter | M2000 Interpreter | \\ M2000 Interpreter
\\ accumulator factory
foo=lambda acc=0 (n as double=0) -> {
\\ interpreter place this: read n as double=0 as first line of lambda function
if n=0 then =acc : exit
acc+=n
\\ acc passed as a closuer to lambda (a copy of acc in the result lambda function)
=lambda acc -> {
' if stack of values is empty then return a copy of acc
if empty then =acc : exit
read x
\\ x has no type here, can be any numeric type (also can be an object too)
\\ accumulator is double, and is a closure (a copy of acc in foo)
acc+=x
\\ any variable in M2000 hold first type
\\ if x is an object then we get error, except if object use this operator
x=acc
\\ so we return x type
=x
}
}
x=foo(1&) ' 1& is long type (32bit)
call void x(5) ' 5 is double type (the default type for M2000)
call void foo(3#) ' void tell to interpreter to throw result, 3# is Currency type
print x(2.3@) ' print 8.3, 2.3@ is Decimal type
print foo()=4 ' print true
def ExpType$(z)=type$(z)
print ExpType$(foo())="Double"
print ExpType$(x(0&))="Long"
print ExpType$(x(0@))="Decimal"
print ExpType$(x())="Double"
print ExpType$(foo(20))="lambda" |
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
−
1
,
1
)
if
m
>
0
and
n
=
0
A
(
m
−
1
,
A
(
m
,
n
−
1
)
)
if
m
>
0
and
n
>
0.
{\displaystyle A(m,n)={\begin{cases}n+1&{\mbox{if }}m=0\\A(m-1,1)&{\mbox{if }}m>0{\mbox{ and }}n=0\\A(m-1,A(m,n-1))&{\mbox{if }}m>0{\mbox{ and }}n>0.\end{cases}}}
Its arguments are never negative and it always terminates.
Task
Write a function which returns the value of
A
(
m
,
n
)
{\displaystyle A(m,n)}
. Arbitrary precision is preferred (since the function grows so quickly), but not required.
See also
Conway chained arrow notation for the Ackermann function.
| #AWK | AWK | function ackermann(m, n)
{
if ( m == 0 ) {
return n+1
}
if ( n == 0 ) {
return ackermann(m-1, 1)
}
return ackermann(m-1, ackermann(m, n-1))
}
BEGIN {
for(n=0; n < 7; n++) {
for(m=0; m < 4; m++) {
print "A(" m "," n ") = " ackermann(m,n)
}
}
} |
http://rosettacode.org/wiki/Abundant,_deficient_and_perfect_number_classifications | Abundant, deficient and perfect number classifications | These define three classifications of positive integers based on their proper divisors.
Let P(n) be the sum of the proper divisors of n where the proper divisors are all positive divisors of n other than n itself.
if P(n) < n then n is classed as deficient (OEIS A005100).
if P(n) == n then n is classed as perfect (OEIS A000396).
if P(n) > n then n is classed as abundant (OEIS A005101).
Example
6 has proper divisors of 1, 2, and 3.
1 + 2 + 3 = 6, so 6 is classed as a perfect number.
Task
Calculate how many of the integers 1 to 20,000 (inclusive) are in each of the three classes.
Show the results here.
Related tasks
Aliquot sequence classifications. (The whole series from which this task is a subset.)
Proper divisors
Amicable pairs
| #D | D | void main() /*@safe*/ {
import std.stdio, std.algorithm, std.range;
static immutable properDivs = (in uint n) pure nothrow @safe /*@nogc*/ =>
iota(1, (n + 1) / 2 + 1).filter!(x => n % x == 0 && n != x);
enum Class { deficient, perfect, abundant }
static Class classify(in uint n) pure nothrow @safe /*@nogc*/ {
immutable p = properDivs(n).sum;
with (Class)
return (p < n) ? deficient : ((p == n) ? perfect : abundant);
}
enum rangeMax = 20_000;
//iota(1, 1 + rangeMax).map!classify.hashGroup.writeln;
iota(1, 1 + rangeMax).map!classify.array.sort().group.writeln;
} |
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, or center justified within its column.
Use the following text to test your programs:
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,$or$center$justified$within$its$column.
Note that:
The example input texts lines may, or may not, have trailing dollar characters.
All columns should share the same alignment.
Consecutive space characters produced adjacent to the end of lines are insignificant for the purposes of the task.
Output text will be viewed in a mono-spaced font on a plain text editor or basic terminal.
The minimum space between columns should be computed from the text and not hard-coded.
It is not a requirement to add separating characters between or around columns.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Erlang | Erlang |
-module (align_columns).
-export([align_left/0, align_right/0, align_center/0]).
-define (Lines,
["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,\$or\$center\$justified\$within\$its\$column."].
align_left()-> align_columns(left).
align_right()-> align_columns(right).
align_center()-> align_columns(centre).
align_columns(Alignment) ->
Words = [ string:tokens(Line, "\$") || Line <- ?Lines ],
Words_length = lists:foldl( fun max_length/2, [], Words),
Result = [prepare_line(Words_line, Words_length, Alignment)
|| Words_line <- Words],
[ io:fwrite("~s~n", [lists:flatten(Line)]) || Line <- Result],
ok.
max_length(Words_of_a_line, Acc_maxlength) ->
Line_lengths = [length(W) || W <- Words_of_a_line ],
Max_nb_of_length = lists:max([length(Acc_maxlength), length(Line_lengths)]),
Line_lengths_prepared = adjust_list (Line_lengths, Max_nb_of_length, 0),
Acc_maxlength_prepared = adjust_list(Acc_maxlength, Max_nb_of_length, 0),
Two_lengths =lists:zip(Line_lengths_prepared, Acc_maxlength_prepared),
[ lists:max([A, B]) || {A, B} <- Two_lengths].
adjust_list(L, Desired_length, Elem) ->
L++lists:duplicate(Desired_length - length(L), Elem).
prepare_line(Words_line, Words_length, Alignment) ->
All_words = adjust_list(Words_line, length(Words_length), ""),
Zipped = lists:zip (All_words, Words_length),
[ apply(string, Alignment, [Word, Length + 1, $\s])
|| {Word, Length} <- Zipped]. |
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 synchronization mechanism with the encapsulated task in order to prevent object's state corruption.
A typical instance of an active object is an animation widget. The widget state changes with the time, while as an object it has all properties of a normal widget.
The task
Implement an active integrator object. The object has an input and output. The input can be set using the method Input. The input is a function of time. The output can be queried using the method Output. The object integrates its input over the time and the result becomes the object's output. So if the input is K(t) and the output is S, the object state S is changed to S + (K(t1) + K(t0)) * (t1 - t0) / 2, i.e. it integrates K using the trapeze method. Initially K is constant 0 and S is 0.
In order to test the object:
set its input to sin (2π f t), where the frequency f=0.5Hz. The phase is irrelevant.
wait 2s
set the input to constant 0
wait 0.5s
Verify that now the object's output is approximately 0 (the sine has the period of 2s). The accuracy of the result will depend on the OS scheduler time slicing and the accuracy of the clock.
| #Tcl | Tcl | package require Tcl 8.6
oo::class create integrator {
variable e sum delay tBase t0 k0 aid
constructor {{interval 1}} {
set delay $interval
set tBase [clock microseconds]
set t0 0
set e { 0.0 }
set k0 0.0
set sum 0.0
set aid [after $delay [namespace code {my Step}]]
}
destructor {
after cancel $aid
}
method input expression {
set e $expression
}
method output {} {
return $sum
}
method Eval t {
expr $e
}
method Step {} {
set aid [after $delay [namespace code {my Step}]]
set t [expr {([clock microseconds] - $tBase) / 1e6}]
set k1 [my Eval $t]
set sum [expr {$sum + ($k1 + $k0) * ($t - $t0) / 2.}]
set t0 $t
set k0 $k1
}
}
set pi 3.14159265
proc pause {time} {
yield [after [expr {int($time * 1000)}] [info coroutine]]
}
proc task {script} {
coroutine task_ apply [list {} "$script;set ::done ok"]
vwait done
}
task {
integrator create i
i input {sin(2*$::pi * 0.5 * $t)}
pause 2
i input { 0.0 }
pause 0.5
puts [format %.15f [i output]]
} |
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 second term is K then all future terms are also K and so the sequence repeats from the first term with period 1 and K is called perfect.
If the third term would be repeating K then the sequence repeats with period 2 and K is called amicable.
If the Nth term would be repeating K for the first time, with N > 3 then the sequence repeats with period N - 1 and K is called sociable.
Perfect, amicable and sociable numbers eventually repeat the original number K; there are other repetitions...
Some K have a sequence that eventually forms a periodic repetition of period 1 but of a number other than K, for example 95 which forms the sequence 95, 25, 6, 6, 6, ... such K are called aspiring.
K that have a sequence that eventually forms a periodic repetition of period >= 2 but of a number other than K, for example 562 which forms the sequence 562, 284, 220, 284, 220, ... such K are called cyclic.
And finally:
Some K form aliquot sequences that are not known to be either terminating or periodic; these K are to be called non-terminating.
For the purposes of this task, K is to be classed as non-terminating if it has not been otherwise classed after generating 16 terms or if any term of the sequence is greater than 2**47 = 140,737,488,355,328.
Task
Create routine(s) to generate the aliquot sequence of a positive integer enough to classify it according to the classifications given above.
Use it to display the classification and sequences of the numbers one to ten inclusive.
Use it to show the classification and sequences of the following integers, in order:
11, 12, 28, 496, 220, 1184, 12496, 1264460, 790, 909, 562, 1064, 1488, and optionally 15355717786080.
Show all output on this page.
Related tasks
Abundant, deficient and perfect number classifications. (Classifications from only the first two members of the whole sequence).
Proper divisors
Amicable pairs
| #Scala | Scala | def createAliquotSeq(n: Long, step: Int, list: List[Long]): (String, List[Long]) = {
val sum = properDivisors(n).sum
if (sum == 0) ("terminate", list ::: List(sum))
else if (step >= 16 || sum > 140737488355328L) ("non-term", list)
else {
list.indexOf(sum) match {
case -1 => createAliquotSeq(sum, step + 1, list ::: List(sum))
case 0 => if (step == 0) ("perfect", list ::: List(sum))
else if (step == 1) ("amicable", list ::: List(sum))
else ("sociable-" + (step + 1), list ::: List(sum))
case index => if (step == index) ("aspiring", list ::: List(sum))
else ("cyclic-" + (step - index + 1), list ::: List(sum))
}
}
}
val numbers = List(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 28, 496, 220, 1184,
12496, 1264460, 790, 909, 562, 1064, 1488, 15355717786080L)
val result = numbers.map(i => createAliquotSeq(i, 0, List(i)))
result foreach { v => println(f"${v._2.head}%14d ${v._1}%10s [${v._2 mkString " "}]" ) } |
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 expansion of
(
x
−
1
)
p
−
(
x
p
−
1
)
{\displaystyle (x-1)^{p}-(x^{p}-1)}
are divisible by
p
{\displaystyle p}
.
Example
Using
p
=
3
{\displaystyle p=3}
:
(x-1)^3 - (x^3 - 1)
= (x^3 - 3x^2 + 3x - 1) - (x^3 - 1)
= -3x^2 + 3x
And all the coefficients are divisible by 3, so 3 is prime.
Note:
This task is not the AKS primality test. It is an inefficient exponential time algorithm discovered in the late 1600s and used as an introductory lemma in the AKS derivation.
Task
Create a function/subroutine/method that given
p
{\displaystyle p}
generates the coefficients of the expanded polynomial representation of
(
x
−
1
)
p
{\displaystyle (x-1)^{p}}
.
Use the function to show here the polynomial expansions of
(
x
−
1
)
p
{\displaystyle (x-1)^{p}}
for
p
{\displaystyle p}
in the range 0 to at least 7, inclusive.
Use the previous function in creating another function that when given
p
{\displaystyle p}
returns whether
p
{\displaystyle p}
is prime using the theorem.
Use your test to generate a list of all primes under 35.
As a stretch goal, generate all primes under 50 (needs integers larger than 31-bit).
References
Agrawal-Kayal-Saxena (AKS) primality test (Wikipedia)
Fool-Proof Test for Primes - Numberphile (Video). The accuracy of this video is disputed -- at best it is an oversimplification.
| #OCaml | OCaml | #require "gen"
#require "zarith"
open Z
let range ?(step=one) i j = if i = j then Gen.empty else Gen.unfold (fun k ->
if compare i j = compare k j then Some (k, (add step k)) else None) i
(* kth coefficient of (x - 1)^n *)
let coeff n k =
let numer = Gen.fold mul one
(range n (sub n k) ~step:minus_one) in
let denom = Gen.fold mul one
(range k zero ~step:minus_one) in
div numer denom |> mul @@
if
compare k n < 0 && is_even k
then
minus_one
else
one
(* coefficient series for (x - 1)^n, k=[0..n] *)
let coeff_series n =
Gen.map (coeff n) (range zero (succ n))
let middle g = Gen.drop 1 g |> Gen.peek |> Gen.filter_map
(function (_, None) -> None | (e, _) -> Some e)
let is_mod_p ~p n = rem n p = zero
let aks p =
coeff_series p |> middle |> Gen.for_all (is_mod_p ~p)
let _ =
print_endline "coefficient series n (k[0] .. k[n])";
Gen.iter
(fun n -> Format.printf "%d (%s)\n" (to_int n)
(Gen.map to_string (coeff_series n) |> Gen.to_list |> String.concat " "))
(range zero (of_int 10));
print_endline "";
print_endline ("primes < 50 per AKS: " ^
(Gen.filter aks (range (of_int 2) (of_int 50)) |>
Gen.map to_string |> Gen.to_list |> String.concat " ")) |
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
{\displaystyle k=2}
, are the semiprimes.
Task
Write a function/method/subroutine/... that generates k-almost primes and use it to create a table here of the first ten members of k-Almost primes for
1
<=
K
<=
5
{\displaystyle 1<=K<=5}
.
Related tasks
Semiprime
Category:Prime Numbers
| #Ring | Ring |
for ap = 1 to 5
see "k = " + ap + ":"
aList = []
for n = 1 to 200
num = 0
for nr = 1 to n
if n%nr=0 and isPrime(nr)=1
num = num + 1
pr = nr
while true
pr = pr * nr
if n%pr = 0
num = num + 1
else exit ok
end ok
next
if (ap = 1 and isPrime(n) = 1) or (ap > 1 and num = ap)
add(aList, n)
if len(aList)=10 exit ok ok
next
for m = 1 to len(aList)
see " " + aList[m]
next
see nl
next
func isPrime num
if (num <= 1) return 0 ok
if (num % 2 = 0 and num != 2) return 0 ok
for i = 3 to floor(num / 2) -1 step 2
if (num % i = 0) return 0 ok
next
return 1
|
http://rosettacode.org/wiki/Almost_prime | Almost prime | A k-Almost-prime is a natural number
n
{\displaystyle n}
that is the product of
k
{\displaystyle k}
(possibly identical) primes.
Example
1-almost-primes, where
k
=
1
{\displaystyle k=1}
, are the prime numbers themselves.
2-almost-primes, where
k
=
2
{\displaystyle k=2}
, are the semiprimes.
Task
Write a function/method/subroutine/... that generates k-almost primes and use it to create a table here of the first ten members of k-Almost primes for
1
<=
K
<=
5
{\displaystyle 1<=K<=5}
.
Related tasks
Semiprime
Category:Prime Numbers
| #Ruby | Ruby | require 'prime'
def almost_primes(k=2)
return to_enum(:almost_primes, k) unless block_given?
1.step {|n| yield n if n.prime_division.sum( &:last ) == k }
end
(1..5).each{|k| puts almost_primes(k).take(10).join(", ")} |
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
Ordered words
Palindrome detection
Semordnilap
Anagrams
Anagrams/Deranged anagrams
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Java | Java | import java.net.*;
import java.io.*;
import java.util.*;
public class WordsOfEqChars {
public static void main(String[] args) throws IOException {
URL url = new URL("http://wiki.puzzlers.org/pub/wordlists/unixdict.txt");
InputStreamReader isr = new InputStreamReader(url.openStream());
BufferedReader reader = new BufferedReader(isr);
Map<String, Collection<String>> anagrams = new HashMap<String, Collection<String>>();
String word;
int count = 0;
while ((word = reader.readLine()) != null) {
char[] chars = word.toCharArray();
Arrays.sort(chars);
String key = new String(chars);
if (!anagrams.containsKey(key))
anagrams.put(key, new ArrayList<String>());
anagrams.get(key).add(word);
count = Math.max(count, anagrams.get(key).size());
}
reader.close();
for (Collection<String> ana : anagrams.values())
if (ana.size() >= count)
System.out.println(ana);
}
} |
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 function doesn't have the right arguments and/or return values.
So we end up inventing some silly name like foo2 or foo_helper. I have always found it painful to come up with a proper name, and see some disadvantages:
You have to think up a name, which then pollutes the namespace
Function is created which is called from nowhere else
The program flow in the source code is interrupted
Some languages allow you to embed recursion directly in-place. This might work via a label, a local gosub instruction, or some special keyword.
Anonymous recursion can also be accomplished using the Y combinator.
Task
If possible, demonstrate this by writing the recursive version of the fibonacci function (see Fibonacci sequence) which checks for a negative argument before doing the actual recursion.
| #Sidef | Sidef | func fib(n) {
return NaN if (n < 0)
func (n) {
n < 2 ? n
: (__FUNC__(n-1) + __FUNC__(n-2))
}(n)
} |
http://rosettacode.org/wiki/Amicable_pairs | Amicable pairs | Two integers
N
{\displaystyle N}
and
M
{\displaystyle M}
are said to be amicable pairs if
N
≠
M
{\displaystyle N\neq M}
and the sum of the proper divisors of
N
{\displaystyle N}
(
s
u
m
(
p
r
o
p
D
i
v
s
(
N
)
)
{\displaystyle \mathrm {sum} (\mathrm {propDivs} (N))}
)
=
M
{\displaystyle =M}
as well as
s
u
m
(
p
r
o
p
D
i
v
s
(
M
)
)
=
N
{\displaystyle \mathrm {sum} (\mathrm {propDivs} (M))=N}
.
Example
1184 and 1210 are an amicable pair, with proper divisors:
1, 2, 4, 8, 16, 32, 37, 74, 148, 296, 592 and
1, 2, 5, 10, 11, 22, 55, 110, 121, 242, 605 respectively.
Task
Calculate and show here the Amicable pairs below 20,000; (there are eight).
Related tasks
Proper divisors
Abundant, deficient and perfect number classifications
Aliquot sequence classifications and its amicable classification.
| #Ring | Ring |
size = 18500
for n = 1 to size
m = amicable(n)
if m>n and amicable(m)=n
see "" + n + " and " + m + nl ok
next
see "OK" + nl
func amicable nr
sum = 1
for d = 2 to sqrt(nr)
if nr % d = 0
sum = sum + d
sum = sum + nr / d ok
next
return sum
|
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 variable number of expressions (or values if that's simpler in the language) and yields a correct one which will satisfy a constraint in some future computation, thereby avoiding failure.
Problems whose solution the Amb operator naturally expresses can be approached with other tools, such as explicit nested iterations over data sets, or with pattern matching. By contrast, the Amb operator appears integrated into the language. Invocations of Amb are not wrapped in any visible loops or other search patterns; they appear to be independent.
Essentially Amb(x, y, z) splits the computation into three possible futures: a future in which the value x is yielded, a future in which the value y is yielded and a future in which the value z is yielded. The future which leads to a successful subsequent computation is chosen. The other "parallel universes" somehow go away. Amb called with no arguments fails.
For simplicity, one of the domain values usable with Amb may denote failure, if that is convenient. For instance, it is convenient if a Boolean false denotes failure, so that Amb(false) fails, and thus constraints can be expressed using Boolean expressions like Amb(x * y == 8) which unless x and y add to four.
A pseudo-code program which satisfies this constraint might look like:
let x = Amb(1, 2, 3)
let y = Amb(7, 6, 4, 5)
Amb(x * y = 8)
print x, y
The output is 2 4 because Amb(1, 2, 3) correctly chooses the future in which x has value 2, Amb(7, 6, 4, 5) chooses 4 and consequently Amb(x * y = 8) produces a success.
Alternatively, failure could be represented using strictly Amb():
unless x * y = 8 do Amb()
Or else Amb could take the form of two operators or functions: one for producing values and one for enforcing constraints:
let x = Ambsel(1, 2, 3)
let y = Ambsel(4, 5, 6)
Ambassert(x * y = 8)
print x, y
where Ambassert behaves like Amb() if the Boolean expression is false, otherwise it allows the future computation to take place, without yielding any value.
The task is to somehow implement Amb, and demonstrate it with a program which chooses one word from each of the following four sets of character strings to generate a four-word sentence:
"the" "that" "a"
"frog" "elephant" "thing"
"walked" "treaded" "grows"
"slowly" "quickly"
The constraint to be satisfied is that the last character of each word (other than the last) is the same as the first character of its successor.
The only successful sentence is "that thing grows slowly"; other combinations do not satisfy the constraint and thus fail.
The goal of this task isn't to simply process the four lists of words with explicit, deterministic program flow such as nested iteration, to trivially demonstrate the correct output. The goal is to implement the Amb operator, or a facsimile thereof that is possible within the language limitations.
| #Python | Python | import itertools as _itertools
class Amb(object):
def __init__(self):
self._names2values = {} # set of values for each global name
self._func = None # Boolean constraint function
self._valueiterator = None # itertools.product of names values
self._funcargnames = None # Constraint parameter names
def __call__(self, arg=None):
if hasattr(arg, '__code__'):
##
## Called with a constraint function.
##
globls = arg.__globals__ if hasattr(arg, '__globals__') else arg.func_globals
# Names used in constraint
argv = arg.__code__.co_varnames[:arg.__code__.co_argcount]
for name in argv:
if name not in self._names2values:
assert name in globls, \
"Global name %s not found in function globals" % name
self._names2values[name] = globls[name]
# Gather the range of values of all names used in the constraint
valuesets = [self._names2values[name] for name in argv]
self._valueiterator = _itertools.product(*valuesets)
self._func = arg
self._funcargnames = argv
return self
elif arg is not None:
##
## Assume called with an iterable set of values
##
arg = frozenset(arg)
return arg
else:
##
## blank call tries to return next solution
##
return self._nextinsearch()
def _nextinsearch(self):
arg = self._func
globls = arg.__globals__
argv = self._funcargnames
found = False
for values in self._valueiterator:
if arg(*values):
# Set globals.
found = True
for n, v in zip(argv, values):
globls[n] = v
break
if not found: raise StopIteration
return values
def __iter__(self):
return self
def __next__(self):
return self()
next = __next__ # Python 2
if __name__ == '__main__':
if True:
amb = Amb()
print("\nSmall Pythagorean triples problem:")
x = amb(range(1,11))
y = amb(range(1,11))
z = amb(range(1,11))
for _dummy in amb( lambda x, y, z: x*x + y*y == z*z ):
print ('%s %s %s' % (x, y, z))
if True:
amb = Amb()
print("\nRosetta Code Amb problem:")
w1 = amb(["the", "that", "a"])
w2 = amb(["frog", "elephant", "thing"])
w3 = amb(["walked", "treaded", "grows"])
w4 = amb(["slowly", "quickly"])
for _dummy in amb( lambda w1, w2, w3, w4: \
w1[-1] == w2[0] and \
w2[-1] == w3[0] and \
w3[-1] == w4[0] ):
print ('%s %s %s %s' % (w1, w2, w3, w4))
if True:
amb = Amb()
print("\nAmb problem from "
"http://www.randomhacks.net/articles/2005/10/11/amb-operator:")
x = amb([1, 2, 3])
y = amb([4, 5, 6])
for _dummy in amb( lambda x, y: x * y != 8 ):
print ('%s %s' % (x, y)) |
http://rosettacode.org/wiki/Accumulator_factory | Accumulator factory | A problem posed by Paul Graham is that of creating a function that takes a single (numeric) argument and which returns another function that is an accumulator. The returned accumulator function in turn also takes a single numeric argument, and returns the sum of all the numeric values passed in so far to that accumulator (including the initial value passed when the accumulator was created).
Rules
The detailed rules are at http://paulgraham.com/accgensub.html and are reproduced here for simplicity (with additions in small italic text).
Before you submit an example, make sure the function
Takes a number n and returns a function (lets call it g), that takes a number i, and returns n incremented by the accumulation of i from every call of function g(i).
Although these exact function and parameter names need not be used
Works for any numeric type-- i.e. can take both ints and floats and returns functions that can take both ints and floats. (It is not enough simply to convert all input to floats. An accumulator that has only seen integers must return integers.) (i.e., if the language doesn't allow for numeric polymorphism, you have to use overloading or something like that)
Generates functions that return the sum of every number ever passed to them, not just the most recent. (This requires a piece of state to hold the accumulated value, which in turn means that pure functional languages can't be used for this task.)
Returns a real function, meaning something that you can use wherever you could use a function you had defined in the ordinary way in the text of your program. (Follow your language's conventions here.)
Doesn't store the accumulated value or the returned functions in a way that could cause them to be inadvertently modified by other code. (No global variables or other such things.)
E.g. if after the example, you added the following code (in a made-up language) where the factory function is called foo:
x = foo(1);
x(5);
foo(3);
print x(2.3);
It should print 8.3. (There is no need to print the form of the accumulator function returned by foo(3); it's not part of the task at all.)
Task
Create a function that implements the described rules.
It need not handle any special error cases not described above. The simplest way to implement the task as described is typically to use a closure, providing the language supports them.
Where it is not possible to hold exactly to the constraints above, describe the deviations.
| #Maple | Maple | AccumulatorFactory := proc( initial := 0 )
local total := initial;
proc( val := 1 ) total := total + val end
end proc: |
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 accumulator (including the initial value passed when the accumulator was created).
Rules
The detailed rules are at http://paulgraham.com/accgensub.html and are reproduced here for simplicity (with additions in small italic text).
Before you submit an example, make sure the function
Takes a number n and returns a function (lets call it g), that takes a number i, and returns n incremented by the accumulation of i from every call of function g(i).
Although these exact function and parameter names need not be used
Works for any numeric type-- i.e. can take both ints and floats and returns functions that can take both ints and floats. (It is not enough simply to convert all input to floats. An accumulator that has only seen integers must return integers.) (i.e., if the language doesn't allow for numeric polymorphism, you have to use overloading or something like that)
Generates functions that return the sum of every number ever passed to them, not just the most recent. (This requires a piece of state to hold the accumulated value, which in turn means that pure functional languages can't be used for this task.)
Returns a real function, meaning something that you can use wherever you could use a function you had defined in the ordinary way in the text of your program. (Follow your language's conventions here.)
Doesn't store the accumulated value or the returned functions in a way that could cause them to be inadvertently modified by other code. (No global variables or other such things.)
E.g. if after the example, you added the following code (in a made-up language) where the factory function is called foo:
x = foo(1);
x(5);
foo(3);
print x(2.3);
It should print 8.3. (There is no need to print the form of the accumulator function returned by foo(3); it's not part of the task at all.)
Task
Create a function that implements the described rules.
It need not handle any special error cases not described above. The simplest way to implement the task as described is typically to use a closure, providing the language supports them.
Where it is not possible to hold exactly to the constraints above, describe the deviations.
| #Mathematica_.2F_Wolfram_Language | Mathematica / Wolfram Language | accFactory[initial_] :=
Module[{total = initial},
Function[x, total += x]
]
x=accFactory[1];
x[5.0];
accFactory[3];
x[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
−
1
,
1
)
if
m
>
0
and
n
=
0
A
(
m
−
1
,
A
(
m
,
n
−
1
)
)
if
m
>
0
and
n
>
0.
{\displaystyle A(m,n)={\begin{cases}n+1&{\mbox{if }}m=0\\A(m-1,1)&{\mbox{if }}m>0{\mbox{ and }}n=0\\A(m-1,A(m,n-1))&{\mbox{if }}m>0{\mbox{ and }}n>0.\end{cases}}}
Its arguments are never negative and it always terminates.
Task
Write a function which returns the value of
A
(
m
,
n
)
{\displaystyle A(m,n)}
. Arbitrary precision is preferred (since the function grows so quickly), but not required.
See also
Conway chained arrow notation for the Ackermann function.
| #Babel | Babel | main:
{((0 0) (0 1) (0 2)
(0 3) (0 4) (1 0)
(1 1) (1 2) (1 3)
(1 4) (2 0) (2 1)
(2 2) (2 3) (3 0)
(3 1) (3 2) (4 0))
{ dup
"A(" << { %d " " . << } ... ") = " <<
reverse give
ack
%d cr << } ... }
ack!:
{ dup zero?
{ <-> dup zero?
{ <->
cp
1 -
<- <- 1 - ->
ack ->
ack }
{ <->
1 -
<- 1 ->
ack }
if }
{ zap 1 + }
if }
zero?!: { 0 = }
|
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) == n then n is classed as perfect (OEIS A000396).
if P(n) > n then n is classed as abundant (OEIS A005101).
Example
6 has proper divisors of 1, 2, and 3.
1 + 2 + 3 = 6, so 6 is classed as a perfect number.
Task
Calculate how many of the integers 1 to 20,000 (inclusive) are in each of the three classes.
Show the results here.
Related tasks
Aliquot sequence classifications. (The whole series from which this task is a subset.)
Proper divisors
Amicable pairs
| #Delphi | Delphi | /* Fill a given array such that for each N,
* P[n] is the sum of proper divisors of N */
proc nonrec propdivs([*] word p) void:
word i, j, max;
max := dim(p,1)-1;
for i from 0 upto max do p[i] := 0 od;
for i from 1 upto max/2 do
for j from i*2 by i upto max do
p[j] := p[j] + i
od
od
corp
proc nonrec main() void:
word MAX = 20000;
word def, per, ab, i;
/* Find all required proper divisor sums */
[MAX+1] word p;
propdivs(p);
def := 0;
per := 0;
ab := 0;
/* Check each number */
for i from 1 upto MAX do
if p[i]<i then def := def + 1
elif p[i]=i then per := per + 1
elif p[i]>i then ab := ab + 1
fi
od;
writeln("Deficient: ", def:5);
writeln("Perfect: ", per:5);
writeln("Abundant: ", ab:5)
corp |
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, or center justified within its column.
Use the following text to test your programs:
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,$or$center$justified$within$its$column.
Note that:
The example input texts lines may, or may not, have trailing dollar characters.
All columns should share the same alignment.
Consecutive space characters produced adjacent to the end of lines are insignificant for the purposes of the task.
Output text will be viewed in a mono-spaced font on a plain text editor or basic terminal.
The minimum space between columns should be computed from the text and not hard-coded.
It is not a requirement to add separating characters between or around columns.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Euphoria | Euphoria | constant data = {
"Given$a$text$file$of$many$lines,$where$fields$within$a$line$",
"are$delineated$by$a$single$'dollar'$character,$write$a$program",
"that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$",
"column$are$separated$by$at$least$one$space.",
"Further,$allow$for$each$word$in$a$column$to$be$either$left$",
"justified,$right$justified,$or$center$justified$within$its$column."
}
function split(sequence s, integer c)
sequence out
integer first, delim
out = {}
first = 1
while first<=length(s) do
delim = find_from(c,s,first)
if delim = 0 then
delim = length(s)+1
end if
out = append(out,s[first..delim-1])
first = delim + 1
end while
return out
end function
function align(sequence s, integer width, integer alignment)
integer n
n = width - length(s)
if n <= 0 then
return s
elsif alignment < 0 then
return s & repeat(' ', n)
elsif alignment > 0 then
return repeat(' ', n) & s
else
return repeat(' ', floor(n/2)) & s & repeat(' ', floor(n/2+0.5))
end if
end function
integer maxlen
sequence lines
maxlen = 0
lines = repeat(0,length(data))
for i = 1 to length(data) do
lines[i] = split(data[i],'$')
for j = 1 to length(lines[i]) do
if length(lines[i][j]) > maxlen then
maxlen = length(lines[i][j])
end if
end for
end for
for a = -1 to 1 do
for i = 1 to length(lines) do
for j = 1 to length(lines[i]) do
puts(1, align(lines[i][j],maxlen,a) & ' ')
end for
puts(1,'\n')
end for
puts(1,'\n')
end for |
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 synchronization mechanism with the encapsulated task in order to prevent object's state corruption.
A typical instance of an active object is an animation widget. The widget state changes with the time, while as an object it has all properties of a normal widget.
The task
Implement an active integrator object. The object has an input and output. The input can be set using the method Input. The input is a function of time. The output can be queried using the method Output. The object integrates its input over the time and the result becomes the object's output. So if the input is K(t) and the output is S, the object state S is changed to S + (K(t1) + K(t0)) * (t1 - t0) / 2, i.e. it integrates K using the trapeze method. Initially K is constant 0 and S is 0.
In order to test the object:
set its input to sin (2π f t), where the frequency f=0.5Hz. The phase is irrelevant.
wait 2s
set the input to constant 0
wait 0.5s
Verify that now the object's output is approximately 0 (the sine has the period of 2s). The accuracy of the result will depend on the OS scheduler time slicing and the accuracy of the clock.
| #Visual_Basic_.NET | Visual Basic .NET | Module Module1
Sub Main()
Using active As New Integrator
active.Operation = Function(t As Double) Math.Sin(2 * Math.PI * 0.5 * t)
Threading.Thread.Sleep(TimeSpan.FromSeconds(2))
Console.WriteLine(active.Value)
active.Operation = Function(t As Double) 0
Threading.Thread.Sleep(TimeSpan.FromSeconds(0.5))
Console.WriteLine(active.Value)
End Using
Console.ReadLine()
End Sub
End Module
Class Integrator
Implements IDisposable
Private m_Operation As Func(Of Double, Double)
Private m_Disposed As Boolean
Private m_SyncRoot As New Object
Private m_Value As Double
Public Sub New()
m_Operation = Function(void) 0.0
Dim t As New Threading.Thread(AddressOf MainLoop)
t.Start()
End Sub
Private Sub MainLoop()
Dim epoch = Now
Dim t0 = 0.0
Do
SyncLock m_SyncRoot
Dim t1 = (Now - epoch).TotalSeconds
m_Value = m_Value + (Operation(t1) + Operation(t0)) * (t1 - t0) / 2
t0 = t1
End SyncLock
Threading.Thread.Sleep(10)
Loop Until m_Disposed
End Sub
Public Property Operation() As Func(Of Double, Double)
Get
SyncLock m_SyncRoot
Return m_Operation
End SyncLock
End Get
Set(ByVal value As Func(Of Double, Double))
SyncLock m_SyncRoot
m_Operation = value
End SyncLock
End Set
End Property
Public ReadOnly Property Value() As Double
Get
SyncLock m_SyncRoot
Return m_Value
End SyncLock
End Get
End Property
Protected Overridable Sub Dispose(ByVal disposing As Boolean)
m_Disposed = True
End Sub
Public Sub Dispose() Implements IDisposable.Dispose
Dispose(True)
GC.SuppressFinalize(Me)
End Sub
End Class |
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 second term is K then all future terms are also K and so the sequence repeats from the first term with period 1 and K is called perfect.
If the third term would be repeating K then the sequence repeats with period 2 and K is called amicable.
If the Nth term would be repeating K for the first time, with N > 3 then the sequence repeats with period N - 1 and K is called sociable.
Perfect, amicable and sociable numbers eventually repeat the original number K; there are other repetitions...
Some K have a sequence that eventually forms a periodic repetition of period 1 but of a number other than K, for example 95 which forms the sequence 95, 25, 6, 6, 6, ... such K are called aspiring.
K that have a sequence that eventually forms a periodic repetition of period >= 2 but of a number other than K, for example 562 which forms the sequence 562, 284, 220, 284, 220, ... such K are called cyclic.
And finally:
Some K form aliquot sequences that are not known to be either terminating or periodic; these K are to be called non-terminating.
For the purposes of this task, K is to be classed as non-terminating if it has not been otherwise classed after generating 16 terms or if any term of the sequence is greater than 2**47 = 140,737,488,355,328.
Task
Create routine(s) to generate the aliquot sequence of a positive integer enough to classify it according to the classifications given above.
Use it to display the classification and sequences of the numbers one to ten inclusive.
Use it to show the classification and sequences of the following integers, in order:
11, 12, 28, 496, 220, 1184, 12496, 1264460, 790, 909, 562, 1064, 1488, and optionally 15355717786080.
Show all output on this page.
Related tasks
Abundant, deficient and perfect number classifications. (Classifications from only the first two members of the whole sequence).
Proper divisors
Amicable pairs
| #Swift | Swift | extension BinaryInteger {
@inlinable
public func factors(sorted: Bool = true) -> [Self] {
let maxN = Self(Double(self).squareRoot())
var res = Set<Self>()
for factor in stride(from: 1, through: maxN, by: 1) where self % factor == 0 {
res.insert(factor)
res.insert(self / factor)
}
return sorted ? res.sorted() : Array(res)
}
}
struct SeqClass: CustomStringConvertible {
var seq: [Int]
var desc: String
var description: String {
return "\(desc): \(seq)"
}
}
func classifySequence(k: Int, threshold: Int = 1 << 47) -> SeqClass {
var last = k
var seq = [k]
while true {
last = last.factors().dropLast().reduce(0, +)
seq.append(last)
let n = seq.count
if last == 0 {
return SeqClass(seq: seq, desc: "Terminating")
} else if n == 2 && last == k {
return SeqClass(seq: seq, desc: "Perfect")
} else if n == 3 && last == k {
return SeqClass(seq: seq, desc: "Amicable")
} else if n >= 4 && last == k {
return SeqClass(seq: seq, desc: "Sociable[\(n - 1)]")
} else if last == seq[n - 2] {
return SeqClass(seq: seq, desc: "Aspiring")
} else if seq.dropFirst().dropLast(2).contains(last) {
return SeqClass(seq: seq, desc: "Cyclic[\(n - 1 - seq.firstIndex(of: last)!)]")
} else if n == 16 || last > threshold {
return SeqClass(seq: seq, desc: "Non-terminating")
}
}
fatalError()
}
for i in 1...10 {
print("\(i): \(classifySequence(k: i))")
}
print()
for i in [11, 12, 28, 496, 220, 1184, 12496, 1264460, 790, 909, 562, 1064, 1488] {
print("\(i): \(classifySequence(k: i))")
}
print()
print("\(15355717786080): \(classifySequence(k: 15355717786080))") |
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 expansion of
(
x
−
1
)
p
−
(
x
p
−
1
)
{\displaystyle (x-1)^{p}-(x^{p}-1)}
are divisible by
p
{\displaystyle p}
.
Example
Using
p
=
3
{\displaystyle p=3}
:
(x-1)^3 - (x^3 - 1)
= (x^3 - 3x^2 + 3x - 1) - (x^3 - 1)
= -3x^2 + 3x
And all the coefficients are divisible by 3, so 3 is prime.
Note:
This task is not the AKS primality test. It is an inefficient exponential time algorithm discovered in the late 1600s and used as an introductory lemma in the AKS derivation.
Task
Create a function/subroutine/method that given
p
{\displaystyle p}
generates the coefficients of the expanded polynomial representation of
(
x
−
1
)
p
{\displaystyle (x-1)^{p}}
.
Use the function to show here the polynomial expansions of
(
x
−
1
)
p
{\displaystyle (x-1)^{p}}
for
p
{\displaystyle p}
in the range 0 to at least 7, inclusive.
Use the previous function in creating another function that when given
p
{\displaystyle p}
returns whether
p
{\displaystyle p}
is prime using the theorem.
Use your test to generate a list of all primes under 35.
As a stretch goal, generate all primes under 50 (needs integers larger than 31-bit).
References
Agrawal-Kayal-Saxena (AKS) primality test (Wikipedia)
Fool-Proof Test for Primes - Numberphile (Video). The accuracy of this video is disputed -- at best it is an oversimplification.
| #Oforth | Oforth | import: mapping
: nextCoef( prev -- [] )
| i |
Array new 0 over dup
prev size 1- loop: i [ prev at(i) prev at(i 1+) - over add ]
0 over add
;
: coefs( n -- [] )
[ 0, 1, 0 ] #nextCoef times(n) extract(2, n 2 + ) ;
: prime?( n -- b)
coefs( n ) extract(2, n) conform?( #[n mod 0 == ] ) ;
: aks
| i |
0 10 for: i [ System.Out "(x-1)^" << i << " = " << coefs( i ) << cr ]
50 seq filter( #prime? ) apply(#.) printcr
; |
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
{\displaystyle k=2}
, are the semiprimes.
Task
Write a function/method/subroutine/... that generates k-almost primes and use it to create a table here of the first ten members of k-Almost primes for
1
<=
K
<=
5
{\displaystyle 1<=K<=5}
.
Related tasks
Semiprime
Category:Prime Numbers
| #Rust | Rust | fn is_kprime(n: u32, k: u32) -> bool {
let mut primes = 0;
let mut f = 2;
let mut rem = n;
while primes < k && rem > 1{
while (rem % f) == 0 && rem > 1{
rem /= f;
primes += 1;
}
f += 1;
}
rem == 1 && primes == k
}
struct KPrimeGen {
k: u32,
n: u32,
}
impl Iterator for KPrimeGen {
type Item = u32;
fn next(&mut self) -> Option<u32> {
self.n += 1;
while !is_kprime(self.n, self.k) {
self.n += 1;
}
Some(self.n)
}
}
fn kprime_generator(k: u32) -> KPrimeGen {
KPrimeGen {k: k, n: 1}
}
fn main() {
for k in 1..6 {
println!("{}: {:?}", k, kprime_generator(k).take(10).collect::<Vec<_>>());
}
} |
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
{\displaystyle k=2}
, are the semiprimes.
Task
Write a function/method/subroutine/... that generates k-almost primes and use it to create a table here of the first ten members of k-Almost primes for
1
<=
K
<=
5
{\displaystyle 1<=K<=5}
.
Related tasks
Semiprime
Category:Prime Numbers
| #Scala | Scala | def isKPrime(n: Int, k: Int, d: Int = 2): Boolean = (n, k, d) match {
case (n, k, _) if n == 1 => k == 0
case (n, _, d) if n % d == 0 => isKPrime(n / d, k - 1, d)
case (_, _, _) => isKPrime(n, k, d + 1)
}
def kPrimeStream(k: Int): Stream[Int] = {
def loop(n: Int): Stream[Int] =
if (isKPrime(n, k)) n #:: loop(n+ 1)
else loop(n + 1)
loop(2)
}
for (k <- 1 to 5) {
println( s"$k: [${ kPrimeStream(k).take(10) mkString " " }]" )
} |
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
Ordered words
Palindrome detection
Semordnilap
Anagrams
Anagrams/Deranged anagrams
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #JavaScript | JavaScript | var fs = require('fs');
var words = fs.readFileSync('unixdict.txt', 'UTF-8').split('\n');
var i, item, max = 0,
anagrams = {};
for (i = 0; i < words.length; i += 1) {
var key = words[i].split('').sort().join('');
if (!anagrams.hasOwnProperty(key)) {//check if property exists on current obj only
anagrams[key] = [];
}
var count = anagrams[key].push(words[i]); //push returns new array length
max = Math.max(count, max);
}
//note, this returns all arrays that match the maximum length
for (item in anagrams) {
if (anagrams.hasOwnProperty(item)) {//check if property exists on current obj only
if (anagrams[item].length === max) {
console.log(anagrams[item].join(' '));
}
}
} |
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 function doesn't have the right arguments and/or return values.
So we end up inventing some silly name like foo2 or foo_helper. I have always found it painful to come up with a proper name, and see some disadvantages:
You have to think up a name, which then pollutes the namespace
Function is created which is called from nowhere else
The program flow in the source code is interrupted
Some languages allow you to embed recursion directly in-place. This might work via a label, a local gosub instruction, or some special keyword.
Anonymous recursion can also be accomplished using the Y combinator.
Task
If possible, demonstrate this by writing the recursive version of the fibonacci function (see Fibonacci sequence) which checks for a negative argument before doing the actual recursion.
| #Smalltalk | Smalltalk |
myMethodComputingFib:arg
|_|
^ (_ := [:n | n <= 1
ifTrue:[n]
ifFalse:[(_ value:(n - 1))+(_ value:(n - 2))]]
) value:arg. |
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
{\displaystyle =M}
as well as
s
u
m
(
p
r
o
p
D
i
v
s
(
M
)
)
=
N
{\displaystyle \mathrm {sum} (\mathrm {propDivs} (M))=N}
.
Example
1184 and 1210 are an amicable pair, with proper divisors:
1, 2, 4, 8, 16, 32, 37, 74, 148, 296, 592 and
1, 2, 5, 10, 11, 22, 55, 110, 121, 242, 605 respectively.
Task
Calculate and show here the Amicable pairs below 20,000; (there are eight).
Related tasks
Proper divisors
Abundant, deficient and perfect number classifications
Aliquot sequence classifications and its amicable classification.
| #Ruby | Ruby | h = {}
(1..20_000).each{|n| h[n] = n.proper_divisors.sum }
h.select{|k,v| h[v] == k && k < v}.each do |key,val| # k<v filters out doubles and perfects
puts "#{key} and #{val}"
end
|
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 variable number of expressions (or values if that's simpler in the language) and yields a correct one which will satisfy a constraint in some future computation, thereby avoiding failure.
Problems whose solution the Amb operator naturally expresses can be approached with other tools, such as explicit nested iterations over data sets, or with pattern matching. By contrast, the Amb operator appears integrated into the language. Invocations of Amb are not wrapped in any visible loops or other search patterns; they appear to be independent.
Essentially Amb(x, y, z) splits the computation into three possible futures: a future in which the value x is yielded, a future in which the value y is yielded and a future in which the value z is yielded. The future which leads to a successful subsequent computation is chosen. The other "parallel universes" somehow go away. Amb called with no arguments fails.
For simplicity, one of the domain values usable with Amb may denote failure, if that is convenient. For instance, it is convenient if a Boolean false denotes failure, so that Amb(false) fails, and thus constraints can be expressed using Boolean expressions like Amb(x * y == 8) which unless x and y add to four.
A pseudo-code program which satisfies this constraint might look like:
let x = Amb(1, 2, 3)
let y = Amb(7, 6, 4, 5)
Amb(x * y = 8)
print x, y
The output is 2 4 because Amb(1, 2, 3) correctly chooses the future in which x has value 2, Amb(7, 6, 4, 5) chooses 4 and consequently Amb(x * y = 8) produces a success.
Alternatively, failure could be represented using strictly Amb():
unless x * y = 8 do Amb()
Or else Amb could take the form of two operators or functions: one for producing values and one for enforcing constraints:
let x = Ambsel(1, 2, 3)
let y = Ambsel(4, 5, 6)
Ambassert(x * y = 8)
print x, y
where Ambassert behaves like Amb() if the Boolean expression is false, otherwise it allows the future computation to take place, without yielding any value.
The task is to somehow implement Amb, and demonstrate it with a program which chooses one word from each of the following four sets of character strings to generate a four-word sentence:
"the" "that" "a"
"frog" "elephant" "thing"
"walked" "treaded" "grows"
"slowly" "quickly"
The constraint to be satisfied is that the last character of each word (other than the last) is the same as the first character of its successor.
The only successful sentence is "that thing grows slowly"; other combinations do not satisfy the constraint and thus fail.
The goal of this task isn't to simply process the four lists of words with explicit, deterministic program flow such as nested iteration, to trivially demonstrate the correct output. The goal is to implement the Amb operator, or a facsimile thereof that is possible within the language limitations.
| #R | R | checkSentence <- function(sentence){
# Input: character vector
# Output: whether the sentence formed by the elements of the vector is valid
for (index in 1:(length(sentence)-1)){
first.word <- sentence[index]
second.word <- sentence[index+1]
last.letter <- substr(first.word, nchar(first.word), nchar(first.word))
first.letter <- substr(second.word, 1, 1)
if (last.letter != first.letter){ return(FALSE) }
}
return(TRUE)
}
amb <- function(sets){
# Input: list of character vectors containing all sets to consider
# Output: list of character vectors that are valid
all.paths <- apply(expand.grid(sets), 2, as.character)
all.paths.list <- split(all.paths, 1:nrow(all.paths))
winners <- all.paths.list[sapply(all.paths.list, checkSentence)]
return(winners)
} |
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 variable number of expressions (or values if that's simpler in the language) and yields a correct one which will satisfy a constraint in some future computation, thereby avoiding failure.
Problems whose solution the Amb operator naturally expresses can be approached with other tools, such as explicit nested iterations over data sets, or with pattern matching. By contrast, the Amb operator appears integrated into the language. Invocations of Amb are not wrapped in any visible loops or other search patterns; they appear to be independent.
Essentially Amb(x, y, z) splits the computation into three possible futures: a future in which the value x is yielded, a future in which the value y is yielded and a future in which the value z is yielded. The future which leads to a successful subsequent computation is chosen. The other "parallel universes" somehow go away. Amb called with no arguments fails.
For simplicity, one of the domain values usable with Amb may denote failure, if that is convenient. For instance, it is convenient if a Boolean false denotes failure, so that Amb(false) fails, and thus constraints can be expressed using Boolean expressions like Amb(x * y == 8) which unless x and y add to four.
A pseudo-code program which satisfies this constraint might look like:
let x = Amb(1, 2, 3)
let y = Amb(7, 6, 4, 5)
Amb(x * y = 8)
print x, y
The output is 2 4 because Amb(1, 2, 3) correctly chooses the future in which x has value 2, Amb(7, 6, 4, 5) chooses 4 and consequently Amb(x * y = 8) produces a success.
Alternatively, failure could be represented using strictly Amb():
unless x * y = 8 do Amb()
Or else Amb could take the form of two operators or functions: one for producing values and one for enforcing constraints:
let x = Ambsel(1, 2, 3)
let y = Ambsel(4, 5, 6)
Ambassert(x * y = 8)
print x, y
where Ambassert behaves like Amb() if the Boolean expression is false, otherwise it allows the future computation to take place, without yielding any value.
The task is to somehow implement Amb, and demonstrate it with a program which chooses one word from each of the following four sets of character strings to generate a four-word sentence:
"the" "that" "a"
"frog" "elephant" "thing"
"walked" "treaded" "grows"
"slowly" "quickly"
The constraint to be satisfied is that the last character of each word (other than the last) is the same as the first character of its successor.
The only successful sentence is "that thing grows slowly"; other combinations do not satisfy the constraint and thus fail.
The goal of this task isn't to simply process the four lists of words with explicit, deterministic program flow such as nested iteration, to trivially demonstrate the correct output. The goal is to implement the Amb operator, or a facsimile thereof that is possible within the language limitations.
| #Racket | Racket |
#lang racket
;; A quick `amb' implementation (same as in the Twelve Statements task)
(define failures null)
(define (fail)
(if (pair? failures) ((first failures)) (error "no more choices!")))
(define (amb/thunks choices)
(let/cc k (set! failures (cons k failures)))
(if (pair? choices)
(let ([choice (first choices)]) (set! choices (rest choices)) (choice))
(begin (set! failures (rest failures)) (fail))))
(define-syntax-rule (amb E ...) (amb/thunks (list (lambda () E) ...)))
(define (assert condition) (unless condition (fail)))
;; Problem solution
(define (joins? left right)
(regexp-match? #px"(.)\0\\1" (~a left "\0" right)))
(let ([result (list (amb "the" "that" "a")
(amb "frog" "elephant" "thing")
(amb "walked" "treaded" "grows")
(amb "slowly" "quickly"))])
(for ([x result] [y (cdr result)]) (assert (joins? x y)))
result)
;; -> '("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 accumulator (including the initial value passed when the accumulator was created).
Rules
The detailed rules are at http://paulgraham.com/accgensub.html and are reproduced here for simplicity (with additions in small italic text).
Before you submit an example, make sure the function
Takes a number n and returns a function (lets call it g), that takes a number i, and returns n incremented by the accumulation of i from every call of function g(i).
Although these exact function and parameter names need not be used
Works for any numeric type-- i.e. can take both ints and floats and returns functions that can take both ints and floats. (It is not enough simply to convert all input to floats. An accumulator that has only seen integers must return integers.) (i.e., if the language doesn't allow for numeric polymorphism, you have to use overloading or something like that)
Generates functions that return the sum of every number ever passed to them, not just the most recent. (This requires a piece of state to hold the accumulated value, which in turn means that pure functional languages can't be used for this task.)
Returns a real function, meaning something that you can use wherever you could use a function you had defined in the ordinary way in the text of your program. (Follow your language's conventions here.)
Doesn't store the accumulated value or the returned functions in a way that could cause them to be inadvertently modified by other code. (No global variables or other such things.)
E.g. if after the example, you added the following code (in a made-up language) where the factory function is called foo:
x = foo(1);
x(5);
foo(3);
print x(2.3);
It should print 8.3. (There is no need to print the form of the accumulator function returned by foo(3); it's not part of the task at all.)
Task
Create a function that implements the described rules.
It need not handle any special error cases not described above. The simplest way to implement the task as described is typically to use a closure, providing the language supports them.
Where it is not possible to hold exactly to the constraints above, describe the deviations.
| #Mercury | Mercury | :- module accum.
:- interface.
:- typeclass addable(T) where [
func T + T = T
].
:- impure func gen(T) = (impure (func(T)) = T) <= addable(T).
:- implementation.
:- import_module bt_array, univ, int.
:- mutable(states, bt_array(univ), make_empty_array(0), ground, [untrailed]).
gen(N) = F :-
some [!S] (
semipure get_states(!:S),
size(!.S, Size),
resize(!.S, 0, Size + 1, univ(N), !:S),
impure set_states(!.S)
),
F = (impure (func(Add)) = M :-
some [!SF] (
semipure get_states(!:SF),
!.SF ^ elem(Size) = U,
det_univ_to_type(U, M0),
M = M0 + Add,
!SF ^ elem(Size) := univ(M),
impure set_states(!.SF)
)). |
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 accumulator (including the initial value passed when the accumulator was created).
Rules
The detailed rules are at http://paulgraham.com/accgensub.html and are reproduced here for simplicity (with additions in small italic text).
Before you submit an example, make sure the function
Takes a number n and returns a function (lets call it g), that takes a number i, and returns n incremented by the accumulation of i from every call of function g(i).
Although these exact function and parameter names need not be used
Works for any numeric type-- i.e. can take both ints and floats and returns functions that can take both ints and floats. (It is not enough simply to convert all input to floats. An accumulator that has only seen integers must return integers.) (i.e., if the language doesn't allow for numeric polymorphism, you have to use overloading or something like that)
Generates functions that return the sum of every number ever passed to them, not just the most recent. (This requires a piece of state to hold the accumulated value, which in turn means that pure functional languages can't be used for this task.)
Returns a real function, meaning something that you can use wherever you could use a function you had defined in the ordinary way in the text of your program. (Follow your language's conventions here.)
Doesn't store the accumulated value or the returned functions in a way that could cause them to be inadvertently modified by other code. (No global variables or other such things.)
E.g. if after the example, you added the following code (in a made-up language) where the factory function is called foo:
x = foo(1);
x(5);
foo(3);
print x(2.3);
It should print 8.3. (There is no need to print the form of the accumulator function returned by foo(3); it's not part of the task at all.)
Task
Create a function that implements the described rules.
It need not handle any special error cases not described above. The simplest way to implement the task as described is typically to use a closure, providing the language supports them.
Where it is not possible to hold exactly to the constraints above, describe the deviations.
| #Nemerle | Nemerle | def Foo(n) {
mutable value : object = n;
fun (i : object) {
match(i) {
|x is int => match(value) {
|y is int => value = x + y;
|y is double => value = x + y;
}
|x is double => match(value) {
|y is int => value = x + (y :> double);
|y is double => value = x + y;
}
}
value
}
}
def x = Foo(1);
def y = Foo(2.2);
x(5);
System.Console.WriteLine(x(2.3));
System.Console.WriteLine(y(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
−
1
,
1
)
if
m
>
0
and
n
=
0
A
(
m
−
1
,
A
(
m
,
n
−
1
)
)
if
m
>
0
and
n
>
0.
{\displaystyle A(m,n)={\begin{cases}n+1&{\mbox{if }}m=0\\A(m-1,1)&{\mbox{if }}m>0{\mbox{ and }}n=0\\A(m-1,A(m,n-1))&{\mbox{if }}m>0{\mbox{ and }}n>0.\end{cases}}}
Its arguments are never negative and it always terminates.
Task
Write a function which returns the value of
A
(
m
,
n
)
{\displaystyle A(m,n)}
. Arbitrary precision is preferred (since the function grows so quickly), but not required.
See also
Conway chained arrow notation for the Ackermann function.
| #BASIC | BASIC | 100 DIM R%(2900),M(2900),N(2900)
110 FOR M = 0 TO 3
120 FOR N = 0 TO 4
130 GOSUB 200"ACKERMANN
140 PRINT "ACK("M","N") = "ACK
150 NEXT N, M
160 END
200 M(SP) = M
210 N(SP) = N
REM A(M - 1, A(M, N - 1))
220 IF M > 0 AND N > 0 THEN N = N - 1 : R%(SP) = 0 : SP = SP + 1 : GOTO 200
REM A(M - 1, 1)
230 IF M > 0 THEN M = M - 1 : N = 1 : R%(SP) = 1 : SP = SP + 1 : GOTO 200
REM N + 1
240 ACK = N + 1
REM RETURN
250 M = M(SP) : N = N(SP) : IF SP = 0 THEN RETURN
260 FOR SP = SP - 1 TO 0 STEP -1 : IF R%(SP) THEN M = M(SP) : N = N(SP) : NEXT SP : SP = 0 : RETURN
270 M = M - 1 : N = ACK : R%(SP) = 1 : SP = SP + 1 : GOTO 200 |
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) == n then n is classed as perfect (OEIS A000396).
if P(n) > n then n is classed as abundant (OEIS A005101).
Example
6 has proper divisors of 1, 2, and 3.
1 + 2 + 3 = 6, so 6 is classed as a perfect number.
Task
Calculate how many of the integers 1 to 20,000 (inclusive) are in each of the three classes.
Show the results here.
Related tasks
Aliquot sequence classifications. (The whole series from which this task is a subset.)
Proper divisors
Amicable pairs
| #Draco | Draco | /* Fill a given array such that for each N,
* P[n] is the sum of proper divisors of N */
proc nonrec propdivs([*] word p) void:
word i, j, max;
max := dim(p,1)-1;
for i from 0 upto max do p[i] := 0 od;
for i from 1 upto max/2 do
for j from i*2 by i upto max do
p[j] := p[j] + i
od
od
corp
proc nonrec main() void:
word MAX = 20000;
word def, per, ab, i;
/* Find all required proper divisor sums */
[MAX+1] word p;
propdivs(p);
def := 0;
per := 0;
ab := 0;
/* Check each number */
for i from 1 upto MAX do
if p[i]<i then def := def + 1
elif p[i]=i then per := per + 1
elif p[i]>i then ab := ab + 1
fi
od;
writeln("Deficient: ", def:5);
writeln("Perfect: ", per:5);
writeln("Abundant: ", ab:5)
corp |
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, or center justified within its column.
Use the following text to test your programs:
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,$or$center$justified$within$its$column.
Note that:
The example input texts lines may, or may not, have trailing dollar characters.
All columns should share the same alignment.
Consecutive space characters produced adjacent to the end of lines are insignificant for the purposes of the task.
Output text will be viewed in a mono-spaced font on a plain text editor or basic terminal.
The minimum space between columns should be computed from the text and not hard-coded.
It is not a requirement to add separating characters between or around columns.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #F.23 | F# | open System
open System.IO
let tableFromPath path =
let lines =
[ for line in File.ReadAllLines(path) -> (line.TrimEnd('$').Split('$')) ]
let width = List.fold (fun max (line : string[]) -> if max < line.Length then line.Length else max) 0 lines
List.map (fun (a : string[]) -> (List.init width (fun i -> if i < a.Length then a.[i] else ""))) lines
let rec trans m =
match m with
| []::_ -> []
| _ -> (List.map List.head m) :: trans (List.map List.tail m)
let colWidth table =
List.map (fun col -> List.max (List.map String.length col)) (trans table)
let left = (fun (s : string) n -> s.PadRight(n))
let right = (fun (s : string) n -> s.PadLeft(n))
let center = (fun (s : string) n -> s.PadLeft((n + s.Length) / 2).PadRight(n))
[<EntryPoint>]
let main argv =
let table = tableFromPath argv.[0]
let width = Array.ofList (colWidth table)
let format table align =
List.map (fun (row : string list) -> List.mapi (fun i s -> sprintf "%s" (align s width.[i])) row) table
|> List.iter (fun row -> printfn "%s" (String.Join(" ", Array.ofList row)))
for align in [ left; right; center ] do
format table align
printfn "%s" (new String('-', (Array.sum width) + width.Length - 1))
0 |
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 synchronization mechanism with the encapsulated task in order to prevent object's state corruption.
A typical instance of an active object is an animation widget. The widget state changes with the time, while as an object it has all properties of a normal widget.
The task
Implement an active integrator object. The object has an input and output. The input can be set using the method Input. The input is a function of time. The output can be queried using the method Output. The object integrates its input over the time and the result becomes the object's output. So if the input is K(t) and the output is S, the object state S is changed to S + (K(t1) + K(t0)) * (t1 - t0) / 2, i.e. it integrates K using the trapeze method. Initially K is constant 0 and S is 0.
In order to test the object:
set its input to sin (2π f t), where the frequency f=0.5Hz. The phase is irrelevant.
wait 2s
set the input to constant 0
wait 0.5s
Verify that now the object's output is approximately 0 (the sine has the period of 2s). The accuracy of the result will depend on the OS scheduler time slicing and the accuracy of the clock.
| #Wren | Wren | import "scheduler" for Scheduler
import "timer" for Timer
var Interval = 0
class Integrator {
construct new() {
_sum = 0
}
input(k) {
_k = k
_v0 = k.call(0)
_t = 0
_running = true
integrate_()
}
output { _sum }
stop() {
_running = false
}
integrate_() {
while (_running) {
Timer.sleep(1)
update_()
}
}
update_() {
_t = _t + Interval
var v1 = _k.call(_t)
var trap = Interval * (_v0 + v1) / 2
_sum = _sum + trap
_v0 = v1
}
}
var integrator = Integrator.new()
Scheduler.add {
Interval = 2 / 1550 // machine specific value
integrator.input(Fn.new { |t| (Num.pi * t).sin })
}
Timer.sleep(2000)
Scheduler.add {
Interval = 0.5 / 775 // machine specific value
integrator.input(Fn.new { |t| 0 })
}
Timer.sleep(500)
integrator.stop()
System.print(integrator.output) |
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 second term is K then all future terms are also K and so the sequence repeats from the first term with period 1 and K is called perfect.
If the third term would be repeating K then the sequence repeats with period 2 and K is called amicable.
If the Nth term would be repeating K for the first time, with N > 3 then the sequence repeats with period N - 1 and K is called sociable.
Perfect, amicable and sociable numbers eventually repeat the original number K; there are other repetitions...
Some K have a sequence that eventually forms a periodic repetition of period 1 but of a number other than K, for example 95 which forms the sequence 95, 25, 6, 6, 6, ... such K are called aspiring.
K that have a sequence that eventually forms a periodic repetition of period >= 2 but of a number other than K, for example 562 which forms the sequence 562, 284, 220, 284, 220, ... such K are called cyclic.
And finally:
Some K form aliquot sequences that are not known to be either terminating or periodic; these K are to be called non-terminating.
For the purposes of this task, K is to be classed as non-terminating if it has not been otherwise classed after generating 16 terms or if any term of the sequence is greater than 2**47 = 140,737,488,355,328.
Task
Create routine(s) to generate the aliquot sequence of a positive integer enough to classify it according to the classifications given above.
Use it to display the classification and sequences of the numbers one to ten inclusive.
Use it to show the classification and sequences of the following integers, in order:
11, 12, 28, 496, 220, 1184, 12496, 1264460, 790, 909, 562, 1064, 1488, and optionally 15355717786080.
Show all output on this page.
Related tasks
Abundant, deficient and perfect number classifications. (Classifications from only the first two members of the whole sequence).
Proper divisors
Amicable pairs
| #Tcl | Tcl | proc ProperDivisors {n} {
if {$n == 1} {return 0}
set divs 1
set sum 1
for {set i 2} {$i*$i <= $n} {incr i} {
if {! ($n % $i)} {
lappend divs $i
incr sum $i
if {$i*$i<$n} {
lappend divs [set d [expr {$n / $i}]]
incr sum $d
}
}
}
list $sum $divs
}
proc al_iter {n} {
yield [info coroutine]
while {$n} {
yield $n
lassign [ProperDivisors $n] n
}
yield 0
return -code break
}
proc al_classify {n} {
coroutine iter al_iter $n
set items {}
try {
set type "non-terminating"
while {[llength $items] < 16} {
set i [iter]
if {$i == 0} {
set type "terminating"
}
set ix [lsearch -exact $items $i]
set items [linsert $items 0 $i]
switch $ix {
-1 { continue }
0 { throw RESULT "perfect" }
1 { throw RESULT "amicable" }
default { throw RESULT "sociable" }
}
}
} trap {RESULT} {type} {
rename iter {}
set map {
perfect aspiring
amicable cyclic
sociable cyclic
}
if {$ix != [llength $items]-2} {
set type [dict get $map $type]
}
}
list $type [lreverse $items]
}
for {set i 1} {$i <= 10} {incr i} {
puts [format "%8d -> %-16s : %s" $i {*}[al_classify $i]]
}
foreach i {11 12 28 496 220 1184 12496 1264460 790 909 562 1064 1488 } {
puts [format "%8d -> %-16s : %s" $i {*}[al_classify $i]]
}
;# stretch goal .. let's time it:
set i 15355717786080
puts [time {
puts [format "%8d -> %-16s : %s" $i {*}[al_classify $i]]
}] |
http://rosettacode.org/wiki/AKS_test_for_primes | AKS test for primes | The AKS algorithm for testing whether a number is prime is a polynomial-time algorithm based on an elementary theorem about Pascal triangles.
The theorem on which the test is based can be stated as follows:
a number
p
{\displaystyle p}
is prime if and only if all the coefficients of the polynomial expansion of
(
x
−
1
)
p
−
(
x
p
−
1
)
{\displaystyle (x-1)^{p}-(x^{p}-1)}
are divisible by
p
{\displaystyle p}
.
Example
Using
p
=
3
{\displaystyle p=3}
:
(x-1)^3 - (x^3 - 1)
= (x^3 - 3x^2 + 3x - 1) - (x^3 - 1)
= -3x^2 + 3x
And all the coefficients are divisible by 3, so 3 is prime.
Note:
This task is not the AKS primality test. It is an inefficient exponential time algorithm discovered in the late 1600s and used as an introductory lemma in the AKS derivation.
Task
Create a function/subroutine/method that given
p
{\displaystyle p}
generates the coefficients of the expanded polynomial representation of
(
x
−
1
)
p
{\displaystyle (x-1)^{p}}
.
Use the function to show here the polynomial expansions of
(
x
−
1
)
p
{\displaystyle (x-1)^{p}}
for
p
{\displaystyle p}
in the range 0 to at least 7, inclusive.
Use the previous function in creating another function that when given
p
{\displaystyle p}
returns whether
p
{\displaystyle p}
is prime using the theorem.
Use your test to generate a list of all primes under 35.
As a stretch goal, generate all primes under 50 (needs integers larger than 31-bit).
References
Agrawal-Kayal-Saxena (AKS) primality test (Wikipedia)
Fool-Proof Test for Primes - Numberphile (Video). The accuracy of this video is disputed -- at best it is an oversimplification.
| #PARI.2FGP | PARI/GP | getPoly(n)=('x-1)^n;
vector(8,n,getPoly(n-1))
AKS_slow(n)=my(P=getPoly(n));for(i=1,n-1,if(polcoeff(P,i)%n,return(0))); 1;
AKS(n)=my(X=('x-1)*Mod(1,n));X^n=='x^n-1;
select(AKS, [1..50]) |
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
{\displaystyle k=2}
, are the semiprimes.
Task
Write a function/method/subroutine/... that generates k-almost primes and use it to create a table here of the first ten members of k-Almost primes for
1
<=
K
<=
5
{\displaystyle 1<=K<=5}
.
Related tasks
Semiprime
Category:Prime Numbers
| #Seed7 | Seed7 | $ include "seed7_05.s7i";
const func boolean: kprime (in var integer: number, in integer: k) is func
result
var boolean: kprime is FALSE;
local
var integer: p is 2;
var integer: f is 0;
begin
while f < k and p * p <= number do
while number rem p = 0 do
number := number div p;
incr(f);
end while;
incr(p);
end while;
kprime := f + ord(number > 1) = k;
end func;
const proc: main is func
local
var integer: k is 0;
var integer: number is 0;
var integer: count is 0;
begin
for k range 1 to 5 do
write("k = " <& k <& ":");
count := 0;
for number range 2 to integer.last until count >= 10 do
if kprime(number, k) then
write(" " <& number);
incr(count);
end if;
end for;
writeln;
end for;
end func; |
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
{\displaystyle k=2}
, are the semiprimes.
Task
Write a function/method/subroutine/... that generates k-almost primes and use it to create a table here of the first ten members of k-Almost primes for
1
<=
K
<=
5
{\displaystyle 1<=K<=5}
.
Related tasks
Semiprime
Category:Prime Numbers
| #SequenceL | SequenceL | import <Utilities/Conversion.sl>;
import <Utilities/Sequence.sl>;
main(args(2)) :=
let
result := firstNKPrimes(1 ... 5, 10);
output[i] := "k = " ++ intToString(i) ++ ": " ++ delimit(intToString(result[i]), ' ');
in
delimit(output, '\n');
firstNKPrimes(k, N) := firstNKPrimesHelper(k, N, 2, []);
firstNKPrimesHelper(k, N, current, result(1)) :=
let
newResult := result when not isKPrime(k, current) else result ++ [current];
in
result when size(result) = N
else
firstNKPrimesHelper(k, N, current + 1, newResult);
isKPrime(k, n) := size(primeFactorization(n)) = k; |
http://rosettacode.org/wiki/Anagrams | Anagrams | When two or more words are composed of the same characters, but in a different order, they are called anagrams.
Task[edit]
Using the word list at http://wiki.puzzlers.org/pub/wordlists/unixdict.txt,
find the sets of words that share the same characters that contain the most words in them.
Related tasks
Word plays
Ordered words
Palindrome detection
Semordnilap
Anagrams
Anagrams/Deranged anagrams
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #jq | jq | def anagrams:
(reduce .[] as $word (
{table: {}, max: 0}; # state
($word | explode | sort | implode) as $hash
| .table[$hash] += [ $word ]
| .max = ([ .max, ( .table[$hash] | length) ] | max ) ))
| .max as $max
| .table | .[] | select(length == $max) ;
# The task:
split("\n") | anagrams
|
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 function doesn't have the right arguments and/or return values.
So we end up inventing some silly name like foo2 or foo_helper. I have always found it painful to come up with a proper name, and see some disadvantages:
You have to think up a name, which then pollutes the namespace
Function is created which is called from nowhere else
The program flow in the source code is interrupted
Some languages allow you to embed recursion directly in-place. This might work via a label, a local gosub instruction, or some special keyword.
Anonymous recursion can also be accomplished using the Y combinator.
Task
If possible, demonstrate this by writing the recursive version of the fibonacci function (see Fibonacci sequence) which checks for a negative argument before doing the actual recursion.
| #Sparkling | Sparkling | function(n, f) {
return f(n, f);
}(10, function(n, f) {
return n < 2 ? 1 : f(n - 1, f) + f(n - 2, 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
{\displaystyle =M}
as well as
s
u
m
(
p
r
o
p
D
i
v
s
(
M
)
)
=
N
{\displaystyle \mathrm {sum} (\mathrm {propDivs} (M))=N}
.
Example
1184 and 1210 are an amicable pair, with proper divisors:
1, 2, 4, 8, 16, 32, 37, 74, 148, 296, 592 and
1, 2, 5, 10, 11, 22, 55, 110, 121, 242, 605 respectively.
Task
Calculate and show here the Amicable pairs below 20,000; (there are eight).
Related tasks
Proper divisors
Abundant, deficient and perfect number classifications
Aliquot sequence classifications and its amicable classification.
| #Run_BASIC | Run BASIC | size = 18500
for n = 1 to size
m = amicable(n)
if m > n and amicable(m) = n then print n ; " and " ; m
next
function amicable(nr)
amicable = 1
for d = 2 to sqr(nr)
if nr mod d = 0 then amicable = amicable + d + nr / d
next
end function |
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 variable number of expressions (or values if that's simpler in the language) and yields a correct one which will satisfy a constraint in some future computation, thereby avoiding failure.
Problems whose solution the Amb operator naturally expresses can be approached with other tools, such as explicit nested iterations over data sets, or with pattern matching. By contrast, the Amb operator appears integrated into the language. Invocations of Amb are not wrapped in any visible loops or other search patterns; they appear to be independent.
Essentially Amb(x, y, z) splits the computation into three possible futures: a future in which the value x is yielded, a future in which the value y is yielded and a future in which the value z is yielded. The future which leads to a successful subsequent computation is chosen. The other "parallel universes" somehow go away. Amb called with no arguments fails.
For simplicity, one of the domain values usable with Amb may denote failure, if that is convenient. For instance, it is convenient if a Boolean false denotes failure, so that Amb(false) fails, and thus constraints can be expressed using Boolean expressions like Amb(x * y == 8) which unless x and y add to four.
A pseudo-code program which satisfies this constraint might look like:
let x = Amb(1, 2, 3)
let y = Amb(7, 6, 4, 5)
Amb(x * y = 8)
print x, y
The output is 2 4 because Amb(1, 2, 3) correctly chooses the future in which x has value 2, Amb(7, 6, 4, 5) chooses 4 and consequently Amb(x * y = 8) produces a success.
Alternatively, failure could be represented using strictly Amb():
unless x * y = 8 do Amb()
Or else Amb could take the form of two operators or functions: one for producing values and one for enforcing constraints:
let x = Ambsel(1, 2, 3)
let y = Ambsel(4, 5, 6)
Ambassert(x * y = 8)
print x, y
where Ambassert behaves like Amb() if the Boolean expression is false, otherwise it allows the future computation to take place, without yielding any value.
The task is to somehow implement Amb, and demonstrate it with a program which chooses one word from each of the following four sets of character strings to generate a four-word sentence:
"the" "that" "a"
"frog" "elephant" "thing"
"walked" "treaded" "grows"
"slowly" "quickly"
The constraint to be satisfied is that the last character of each word (other than the last) is the same as the first character of its successor.
The only successful sentence is "that thing grows slowly"; other combinations do not satisfy the constraint and thus fail.
The goal of this task isn't to simply process the four lists of words with explicit, deterministic program flow such as nested iteration, to trivially demonstrate the correct output. The goal is to implement the Amb operator, or a facsimile thereof that is possible within the language limitations.
| #Raku | Raku |
#| an array of four words, that have more possible values.
#| Normally we would want `any' to signify we want any of the values, but well negate later and thus we need `all'
my @a =
(all «the that a»),
(all «frog elephant thing»),
(all «walked treaded grows»),
(all «slowly quickly»);
sub test (Str $l, Str $r) {
$l.ends-with($r.substr(0,1))
}
(sub ($w1, $w2, $w3, $w4){
# return if the values are false
return unless [and] test($w1, $w2), test($w2, $w3),test($w3, $w4);
# say the results. If there is one more Container layer around them this doesn't work, this is why we need the arguments here.
say "$w1 $w2 $w3 $w4"
})(|@a); # supply the array as argumetns
|
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 accumulator (including the initial value passed when the accumulator was created).
Rules
The detailed rules are at http://paulgraham.com/accgensub.html and are reproduced here for simplicity (with additions in small italic text).
Before you submit an example, make sure the function
Takes a number n and returns a function (lets call it g), that takes a number i, and returns n incremented by the accumulation of i from every call of function g(i).
Although these exact function and parameter names need not be used
Works for any numeric type-- i.e. can take both ints and floats and returns functions that can take both ints and floats. (It is not enough simply to convert all input to floats. An accumulator that has only seen integers must return integers.) (i.e., if the language doesn't allow for numeric polymorphism, you have to use overloading or something like that)
Generates functions that return the sum of every number ever passed to them, not just the most recent. (This requires a piece of state to hold the accumulated value, which in turn means that pure functional languages can't be used for this task.)
Returns a real function, meaning something that you can use wherever you could use a function you had defined in the ordinary way in the text of your program. (Follow your language's conventions here.)
Doesn't store the accumulated value or the returned functions in a way that could cause them to be inadvertently modified by other code. (No global variables or other such things.)
E.g. if after the example, you added the following code (in a made-up language) where the factory function is called foo:
x = foo(1);
x(5);
foo(3);
print x(2.3);
It should print 8.3. (There is no need to print the form of the accumulator function returned by foo(3); it's not part of the task at all.)
Task
Create a function that implements the described rules.
It need not handle any special error cases not described above. The simplest way to implement the task as described is typically to use a closure, providing the language supports them.
Where it is not possible to hold exactly to the constraints above, describe the deviations.
| #NewLisp | NewLisp | (define (sum (x 0)) (inc 0 x))
|
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 accumulator (including the initial value passed when the accumulator was created).
Rules
The detailed rules are at http://paulgraham.com/accgensub.html and are reproduced here for simplicity (with additions in small italic text).
Before you submit an example, make sure the function
Takes a number n and returns a function (lets call it g), that takes a number i, and returns n incremented by the accumulation of i from every call of function g(i).
Although these exact function and parameter names need not be used
Works for any numeric type-- i.e. can take both ints and floats and returns functions that can take both ints and floats. (It is not enough simply to convert all input to floats. An accumulator that has only seen integers must return integers.) (i.e., if the language doesn't allow for numeric polymorphism, you have to use overloading or something like that)
Generates functions that return the sum of every number ever passed to them, not just the most recent. (This requires a piece of state to hold the accumulated value, which in turn means that pure functional languages can't be used for this task.)
Returns a real function, meaning something that you can use wherever you could use a function you had defined in the ordinary way in the text of your program. (Follow your language's conventions here.)
Doesn't store the accumulated value or the returned functions in a way that could cause them to be inadvertently modified by other code. (No global variables or other such things.)
E.g. if after the example, you added the following code (in a made-up language) where the factory function is called foo:
x = foo(1);
x(5);
foo(3);
print x(2.3);
It should print 8.3. (There is no need to print the form of the accumulator function returned by foo(3); it's not part of the task at all.)
Task
Create a function that implements the described rules.
It need not handle any special error cases not described above. The simplest way to implement the task as described is typically to use a closure, providing the language supports them.
Where it is not possible to hold exactly to the constraints above, describe the deviations.
| #NGS | NGS | {
F Acc(start:Int) {
sum = start
F acc(i:Int) {
sum = sum + i
sum
}
}
acc = Acc(10)
echo(acc(5))
echo(acc(2))
} |
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
−
1
,
1
)
if
m
>
0
and
n
=
0
A
(
m
−
1
,
A
(
m
,
n
−
1
)
)
if
m
>
0
and
n
>
0.
{\displaystyle A(m,n)={\begin{cases}n+1&{\mbox{if }}m=0\\A(m-1,1)&{\mbox{if }}m>0{\mbox{ and }}n=0\\A(m-1,A(m,n-1))&{\mbox{if }}m>0{\mbox{ and }}n>0.\end{cases}}}
Its arguments are never negative and it always terminates.
Task
Write a function which returns the value of
A
(
m
,
n
)
{\displaystyle A(m,n)}
. Arbitrary precision is preferred (since the function grows so quickly), but not required.
See also
Conway chained arrow notation for the Ackermann function.
| #Batch_File | Batch File | ::Ackermann.cmd
@echo off
set depth=0
:ack
if %1==0 goto m0
if %2==0 goto n0
:else
set /a n=%2-1
set /a depth+=1
call :ack %1 %n%
set t=%errorlevel%
set /a depth-=1
set /a m=%1-1
set /a depth+=1
call :ack %m% %t%
set t=%errorlevel%
set /a depth-=1
if %depth%==0 ( exit %t% ) else ( exit /b %t% )
:m0
set/a n=%2+1
if %depth%==0 ( exit %n% ) else ( exit /b %n% )
:n0
set /a m=%1-1
set /a depth+=1
call :ack %m% 1
set t=%errorlevel%
set /a depth-=1
if %depth%==0 ( exit %t% ) else ( exit /b %t% ) |
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) == n then n is classed as perfect (OEIS A000396).
if P(n) > n then n is classed as abundant (OEIS A005101).
Example
6 has proper divisors of 1, 2, and 3.
1 + 2 + 3 = 6, so 6 is classed as a perfect number.
Task
Calculate how many of the integers 1 to 20,000 (inclusive) are in each of the three classes.
Show the results here.
Related tasks
Aliquot sequence classifications. (The whole series from which this task is a subset.)
Proper divisors
Amicable pairs
| #Dyalect | Dyalect | func sieve(bound) {
var (a, d, p) = (0, 0, 0)
var sum = Array.Empty(bound + 1, 0)
for divisor in 1..(bound / 2) {
var i = divisor + divisor
while i <= bound {
sum[i] += divisor
i += divisor
}
}
for i in 1..bound {
if sum[i] < i {
d += 1
} else if sum[i] > i {
a += 1
} else {
p += 1
}
}
(abundant: a, deficient: d, perfect: p)
}
func Iterator.Where(fn) {
for x in this {
if fn(x) {
yield x
}
}
}
func Iterator.Sum() {
var sum = 0
for x in this {
sum += x
}
sum
}
func division(bound) {
var (a, d, p) = (0, 0, 0)
for i in 1..20000 {
var sum = ( 1 .. ((i + 1) / 2) )
.Where(div => div != i && i % div == 0)
.Sum()
if sum < i {
d += 1
} else if sum > i {
a += 1
} else {
p += 1
}
}
(abundant: a, deficient: d, perfect: p)
}
func out(res) {
print("Abundant: \(res.abundant), Deficient: \(res.deficient), Perfect: \(res.perfect)");
}
out( sieve(20000) )
out( division(20000) ) |
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, or center justified within its column.
Use the following text to test your programs:
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,$or$center$justified$within$its$column.
Note that:
The example input texts lines may, or may not, have trailing dollar characters.
All columns should share the same alignment.
Consecutive space characters produced adjacent to the end of lines are insignificant for the purposes of the task.
Output text will be viewed in a mono-spaced font on a plain text editor or basic terminal.
The minimum space between columns should be computed from the text and not hard-coded.
It is not a requirement to add separating characters between or around columns.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Factor | Factor | USING: fry io kernel math math.functions math.order sequences
splitting strings ;
IN: rosetta.column-aligner
CONSTANT: example-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$
justified,$right$justified,$or$center$justified$within$its$column."
: split-and-pad ( text -- lines )
"\n" split [ "$" split harvest ] map
dup [ length ] [ max ] map-reduce
'[ _ "" pad-tail ] map ;
: column-widths ( columns -- widths )
[ [ length ] [ max ] map-reduce ] map ;
SINGLETONS: +left+ +middle+ +right+ ;
GENERIC: align-string ( str n alignment -- str' )
M: +left+ align-string drop CHAR: space pad-tail ;
M: +right+ align-string drop CHAR: space pad-head ;
M: +middle+ align-string
drop
over length - 2 /
[ floor CHAR: space <string> ]
[ ceiling CHAR: space <string> ] bi surround ;
: align-columns ( columns alignment -- columns' )
[ dup column-widths ] dip '[
[ _ align-string ] curry map
] 2map ;
: print-aligned ( text alignment -- )
[ split-and-pad flip ] dip align-columns flip
[ [ write " " write ] each nl ] each ; |
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 synchronization mechanism with the encapsulated task in order to prevent object's state corruption.
A typical instance of an active object is an animation widget. The widget state changes with the time, while as an object it has all properties of a normal widget.
The task
Implement an active integrator object. The object has an input and output. The input can be set using the method Input. The input is a function of time. The output can be queried using the method Output. The object integrates its input over the time and the result becomes the object's output. So if the input is K(t) and the output is S, the object state S is changed to S + (K(t1) + K(t0)) * (t1 - t0) / 2, i.e. it integrates K using the trapeze method. Initially K is constant 0 and S is 0.
In order to test the object:
set its input to sin (2π f t), where the frequency f=0.5Hz. The phase is irrelevant.
wait 2s
set the input to constant 0
wait 0.5s
Verify that now the object's output is approximately 0 (the sine has the period of 2s). The accuracy of the result will depend on the OS scheduler time slicing and the accuracy of the clock.
| #zkl | zkl | class Integrator{
// continuously integrate a function `K`, at each `interval` seconds'
fcn init(f,interval=1e-4){
var _interval=interval, K=Ref(f), S=Ref(0.0), run=True;
self.launch(); // start me as a thread
}
fcn liftoff{ // entry point for the thread
start:=Time.Clock.timef; // floating point seconds since Epoch
t0,k0,s:=0,K.value(0),S.value;
while(run){
Atomic.sleep(_interval);
t1,k1:=Time.Clock.timef - start, K.value(t1);
s+=(k1 + k0)*(t1 - t0)/2.0; S.set(s);
t0,k0=t1,k1;
}
}
fcn sample { S.value }
fcn setF(f) { K.set(f) }
} |
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 second term is K then all future terms are also K and so the sequence repeats from the first term with period 1 and K is called perfect.
If the third term would be repeating K then the sequence repeats with period 2 and K is called amicable.
If the Nth term would be repeating K for the first time, with N > 3 then the sequence repeats with period N - 1 and K is called sociable.
Perfect, amicable and sociable numbers eventually repeat the original number K; there are other repetitions...
Some K have a sequence that eventually forms a periodic repetition of period 1 but of a number other than K, for example 95 which forms the sequence 95, 25, 6, 6, 6, ... such K are called aspiring.
K that have a sequence that eventually forms a periodic repetition of period >= 2 but of a number other than K, for example 562 which forms the sequence 562, 284, 220, 284, 220, ... such K are called cyclic.
And finally:
Some K form aliquot sequences that are not known to be either terminating or periodic; these K are to be called non-terminating.
For the purposes of this task, K is to be classed as non-terminating if it has not been otherwise classed after generating 16 terms or if any term of the sequence is greater than 2**47 = 140,737,488,355,328.
Task
Create routine(s) to generate the aliquot sequence of a positive integer enough to classify it according to the classifications given above.
Use it to display the classification and sequences of the numbers one to ten inclusive.
Use it to show the classification and sequences of the following integers, in order:
11, 12, 28, 496, 220, 1184, 12496, 1264460, 790, 909, 562, 1064, 1488, and optionally 15355717786080.
Show all output on this page.
Related tasks
Abundant, deficient and perfect number classifications. (Classifications from only the first two members of the whole sequence).
Proper divisors
Amicable pairs
| #VBA | VBA | Option Explicit
Private Type Aliquot
Sequence() As Double
Classification As String
End Type
Sub Main()
Dim result As Aliquot, i As Long, j As Double, temp As String
'display the classification and sequences of the numbers one to ten inclusive
For j = 1 To 10
result = Aliq(j)
temp = vbNullString
For i = 0 To UBound(result.Sequence)
temp = temp & result.Sequence(i) & ", "
Next i
Debug.Print "Aliquot seq of " & j & " : " & result.Classification & " " & Left(temp, Len(temp) - 2)
Next j
'show the classification and sequences of the following integers, in order:
Dim a
'15 355 717 786 080 : impossible in VBA ==> out of memory
a = Array(11, 12, 28, 496, 220, 1184, 12496, 1264460, 790, 909, 562, 1064, 1488)
For j = LBound(a) To UBound(a)
result = Aliq(CDbl(a(j)))
temp = vbNullString
For i = 0 To UBound(result.Sequence)
temp = temp & result.Sequence(i) & ", "
Next i
Debug.Print "Aliquot seq of " & a(j) & " : " & result.Classification & " " & Left(temp, Len(temp) - 2)
Next
End Sub
Private Function Aliq(Nb As Double) As Aliquot
Dim s() As Double, i As Long, temp, j As Long, cpt As Long
temp = Array("non-terminating", "Terminate", "Perfect", "Amicable", "Sociable", "Aspiring", "Cyclic")
ReDim s(0)
s(0) = Nb
For i = 1 To 15
cpt = cpt + 1
ReDim Preserve s(cpt)
s(i) = SumPDiv(s(i - 1))
If s(i) > 140737488355328# Then Exit For
If s(i) = 0 Then j = 1
If s(1) = s(0) Then j = 2
If s(i) = s(0) And i > 1 And i <> 2 Then j = 4
If s(i) = s(i - 1) And i > 1 Then j = 5
If i >= 2 Then
If s(2) = s(0) Then j = 3
If s(i) = s(i - 2) And i <> 2 Then j = 6
End If
If j > 0 Then Exit For
Next
Aliq.Classification = temp(j)
Aliq.Sequence = s
End Function
Private Function SumPDiv(n As Double) As Double
'returns the sum of the Proper divisors of n
Dim j As Long, t As Long
If n > 1 Then
For j = 1 To n \ 2
If n Mod j = 0 Then t = t + j
Next
End If
SumPDiv = t
End Function
|
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 expansion of
(
x
−
1
)
p
−
(
x
p
−
1
)
{\displaystyle (x-1)^{p}-(x^{p}-1)}
are divisible by
p
{\displaystyle p}
.
Example
Using
p
=
3
{\displaystyle p=3}
:
(x-1)^3 - (x^3 - 1)
= (x^3 - 3x^2 + 3x - 1) - (x^3 - 1)
= -3x^2 + 3x
And all the coefficients are divisible by 3, so 3 is prime.
Note:
This task is not the AKS primality test. It is an inefficient exponential time algorithm discovered in the late 1600s and used as an introductory lemma in the AKS derivation.
Task
Create a function/subroutine/method that given
p
{\displaystyle p}
generates the coefficients of the expanded polynomial representation of
(
x
−
1
)
p
{\displaystyle (x-1)^{p}}
.
Use the function to show here the polynomial expansions of
(
x
−
1
)
p
{\displaystyle (x-1)^{p}}
for
p
{\displaystyle p}
in the range 0 to at least 7, inclusive.
Use the previous function in creating another function that when given
p
{\displaystyle p}
returns whether
p
{\displaystyle p}
is prime using the theorem.
Use your test to generate a list of all primes under 35.
As a stretch goal, generate all primes under 50 (needs integers larger than 31-bit).
References
Agrawal-Kayal-Saxena (AKS) primality test (Wikipedia)
Fool-Proof Test for Primes - Numberphile (Video). The accuracy of this video is disputed -- at best it is an oversimplification.
| #Pascal | Pascal |
const
pasTriMax = 61;
type
TPasTri = array[0 .. pasTriMax] of UInt64;
var
pasTri: TPasTri;
procedure PascalTriangle(n: LongWord);
// Calculate the n'th line 0.. middle
var
j, k: LongWord;
begin
pasTri[0] := 1;
j := 1;
while j <= n do
begin
Inc(j);
k := j div 2;
pasTri[k] := pasTri[k - 1];
for k := k downto 1 do
Inc(pasTri[k], pasTri[k - 1]);
end;
end;
function IsPrime(n: LongWord): Boolean;
var
i: Integer;
begin
if n > pasTriMax then
begin
WriteLn(n, ' is out of range');
Halt;
end;
PascalTriangle(n);
Result := true;
i := n div 2;
while Result and (i > 1) do
begin
Result := Result and (pasTri[i] mod n = 0);
Dec(i);
end;
end;
procedure ExpandPoly(n: LongWord);
const
Vz: array[Boolean] of Char = ('+', '-');
var
j: LongWord;
bVz: Boolean;
begin
if n > pasTriMax then
begin
WriteLn(n,' is out of range');
Halt;
end;
case n of
0: WriteLn('(x-1)^0 = 1');
1: WriteLn('(x-1)^1 = x-1');
else
PascalTriangle(n);
Write('(x-1)^', n, ' = ');
Write('x^', n);
bVz := true;
for j := n - 1 downto n div 2 + 1 do
begin
Write(vz[bVz], pasTri[n - j], '*x^', j);
bVz := not bVz;
end;
for j := n div 2 downto 2 do
begin
Write(vz[bVz], pasTri[j], '*x^', j);
bVz := not bVz;
end;
Write(vz[bVz], pasTri[1], '*x');
bVz := not bVz;
WriteLn(vz[bVz], pasTri[0]);
end;
end;
var
n: LongWord;
begin
for n := 0 to 9 do
ExpandPoly(n);
for n := 2 to pasTriMax do
if IsPrime(n) then
Write(n:3);
WriteLn;
end. |
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
{\displaystyle k=2}
, are the semiprimes.
Task
Write a function/method/subroutine/... that generates k-almost primes and use it to create a table here of the first ten members of k-Almost primes for
1
<=
K
<=
5
{\displaystyle 1<=K<=5}
.
Related tasks
Semiprime
Category:Prime Numbers
| #Sidef | Sidef | func is_k_almost_prime(n, k) {
for (var (p, f) = (2, 0); (f < k) && (p*p <= n); ++p) {
(n /= p; ++f) while (p `divides` n)
}
n > 1 ? (f.inc == k) : (f == k)
}
{ |k|
var x = 10
say gather {
{ |i|
if (is_k_almost_prime(i, k)) {
take(i)
--x == 0 && break
}
} << 1..Inf
}
} << 1..5 |
http://rosettacode.org/wiki/Anagrams | Anagrams | When two or more words are composed of the same characters, but in a different order, they are called anagrams.
Task[edit]
Using the word list at http://wiki.puzzlers.org/pub/wordlists/unixdict.txt,
find the sets of words that share the same characters that contain the most words in them.
Related tasks
Word plays
Ordered words
Palindrome detection
Semordnilap
Anagrams
Anagrams/Deranged anagrams
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Jsish | Jsish | /* Anagrams, in Jsish */
var datafile = 'unixdict.txt';
if (console.args[0] == '-more' && Interp.conf('maxArrayList') > 500000)
datafile = '/usr/share/dict/words';
var words = File.read(datafile).split('\n');
puts(words.length, 'words');
var i, item, max = 0, anagrams = {};
for (i = 0; i < words.length; i += 1) {
var key = words[i].split('').sort().join('');
if (!anagrams.hasOwnProperty(key)) {
anagrams[key] = [];
}
var count = anagrams[key].push(words[i]);
max = Math.max(count, max);
}
// display all arrays that match the maximum length
for (item in anagrams) {
if (anagrams.hasOwnProperty(item)) {
if (anagrams[item].length === max) {
puts(anagrams[item].join(' '));
}
}
}
/*
=!EXPECTSTART!=
25108 words
abel able bale bela elba
caret carte cater crate trace
angel angle galen glean lange
alger glare lager large regal
elan lane lean lena neal
evil levi live veil vile
=!EXPECTEND!=
*/ |
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 function doesn't have the right arguments and/or return values.
So we end up inventing some silly name like foo2 or foo_helper. I have always found it painful to come up with a proper name, and see some disadvantages:
You have to think up a name, which then pollutes the namespace
Function is created which is called from nowhere else
The program flow in the source code is interrupted
Some languages allow you to embed recursion directly in-place. This might work via a label, a local gosub instruction, or some special keyword.
Anonymous recursion can also be accomplished using the Y combinator.
Task
If possible, demonstrate this by writing the recursive version of the fibonacci function (see Fibonacci sequence) which checks for a negative argument before doing the actual recursion.
| #Standard_ML | Standard ML | fun fix f x = f (fix f) x
fun fib n =
if n < 0 then raise Fail "Negative"
else
fix (fn fib =>
(fn 0 => 0
| 1 => 1
| n => fib (n-1) + fib (n-2))) n |
http://rosettacode.org/wiki/Amicable_pairs | Amicable pairs | Two integers
N
{\displaystyle N}
and
M
{\displaystyle M}
are said to be amicable pairs if
N
≠
M
{\displaystyle N\neq M}
and the sum of the proper divisors of
N
{\displaystyle N}
(
s
u
m
(
p
r
o
p
D
i
v
s
(
N
)
)
{\displaystyle \mathrm {sum} (\mathrm {propDivs} (N))}
)
=
M
{\displaystyle =M}
as well as
s
u
m
(
p
r
o
p
D
i
v
s
(
M
)
)
=
N
{\displaystyle \mathrm {sum} (\mathrm {propDivs} (M))=N}
.
Example
1184 and 1210 are an amicable pair, with proper divisors:
1, 2, 4, 8, 16, 32, 37, 74, 148, 296, 592 and
1, 2, 5, 10, 11, 22, 55, 110, 121, 242, 605 respectively.
Task
Calculate and show here the Amicable pairs below 20,000; (there are eight).
Related tasks
Proper divisors
Abundant, deficient and perfect number classifications
Aliquot sequence classifications and its amicable classification.
| #Rust | Rust | fn sum_of_divisors(val: u32) -> u32 {
(1..val/2+1).filter(|n| val % n == 0)
.fold(0, |sum, n| sum + n)
}
fn main() {
let iter = (1..20_000).map(|i| (i, sum_of_divisors(i)))
.filter(|&(i, div_sum)| i > div_sum);
for (i, sum1) in iter {
if sum_of_divisors(sum1) == i {
println!("{} {}", i, sum1);
}
}
} |
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 variable number of expressions (or values if that's simpler in the language) and yields a correct one which will satisfy a constraint in some future computation, thereby avoiding failure.
Problems whose solution the Amb operator naturally expresses can be approached with other tools, such as explicit nested iterations over data sets, or with pattern matching. By contrast, the Amb operator appears integrated into the language. Invocations of Amb are not wrapped in any visible loops or other search patterns; they appear to be independent.
Essentially Amb(x, y, z) splits the computation into three possible futures: a future in which the value x is yielded, a future in which the value y is yielded and a future in which the value z is yielded. The future which leads to a successful subsequent computation is chosen. The other "parallel universes" somehow go away. Amb called with no arguments fails.
For simplicity, one of the domain values usable with Amb may denote failure, if that is convenient. For instance, it is convenient if a Boolean false denotes failure, so that Amb(false) fails, and thus constraints can be expressed using Boolean expressions like Amb(x * y == 8) which unless x and y add to four.
A pseudo-code program which satisfies this constraint might look like:
let x = Amb(1, 2, 3)
let y = Amb(7, 6, 4, 5)
Amb(x * y = 8)
print x, y
The output is 2 4 because Amb(1, 2, 3) correctly chooses the future in which x has value 2, Amb(7, 6, 4, 5) chooses 4 and consequently Amb(x * y = 8) produces a success.
Alternatively, failure could be represented using strictly Amb():
unless x * y = 8 do Amb()
Or else Amb could take the form of two operators or functions: one for producing values and one for enforcing constraints:
let x = Ambsel(1, 2, 3)
let y = Ambsel(4, 5, 6)
Ambassert(x * y = 8)
print x, y
where Ambassert behaves like Amb() if the Boolean expression is false, otherwise it allows the future computation to take place, without yielding any value.
The task is to somehow implement Amb, and demonstrate it with a program which chooses one word from each of the following four sets of character strings to generate a four-word sentence:
"the" "that" "a"
"frog" "elephant" "thing"
"walked" "treaded" "grows"
"slowly" "quickly"
The constraint to be satisfied is that the last character of each word (other than the last) is the same as the first character of its successor.
The only successful sentence is "that thing grows slowly"; other combinations do not satisfy the constraint and thus fail.
The goal of this task isn't to simply process the four lists of words with explicit, deterministic program flow such as nested iteration, to trivially demonstrate the correct output. The goal is to implement the Amb operator, or a facsimile thereof that is possible within the language limitations.
| #Red | Red | Red ["Amb operator"]
findblock: function [
blk [block!]
][
foreach w blk [
if all [word? w block? get w] [return w]
if block? w [findblock w]
]
]
amb: function [
cond [block!]
][
either b: findblock cond [
foreach a get b [
cond2: replace/all/deep copy/deep cond b a
if amb cond2 [set b a return true]]
][do cond]
]
; examples
x: [1 2 3 4]
y: [4 5 6]
z: [5 2]
print amb [x * y * z = 8]
print [x y z]
a: ["the" "that" "a"]
b: ["frog" "elephant" "thing"]
c: ["walked" "treaded" "grows"]
d: ["slowly" "quickly"]
print amb [
all [
equal? last a first b
equal? last b first c
equal? last c first d
]
]
print [a b c d]
|
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 accumulator (including the initial value passed when the accumulator was created).
Rules
The detailed rules are at http://paulgraham.com/accgensub.html and are reproduced here for simplicity (with additions in small italic text).
Before you submit an example, make sure the function
Takes a number n and returns a function (lets call it g), that takes a number i, and returns n incremented by the accumulation of i from every call of function g(i).
Although these exact function and parameter names need not be used
Works for any numeric type-- i.e. can take both ints and floats and returns functions that can take both ints and floats. (It is not enough simply to convert all input to floats. An accumulator that has only seen integers must return integers.) (i.e., if the language doesn't allow for numeric polymorphism, you have to use overloading or something like that)
Generates functions that return the sum of every number ever passed to them, not just the most recent. (This requires a piece of state to hold the accumulated value, which in turn means that pure functional languages can't be used for this task.)
Returns a real function, meaning something that you can use wherever you could use a function you had defined in the ordinary way in the text of your program. (Follow your language's conventions here.)
Doesn't store the accumulated value or the returned functions in a way that could cause them to be inadvertently modified by other code. (No global variables or other such things.)
E.g. if after the example, you added the following code (in a made-up language) where the factory function is called foo:
x = foo(1);
x(5);
foo(3);
print x(2.3);
It should print 8.3. (There is no need to print the form of the accumulator function returned by foo(3); it's not part of the task at all.)
Task
Create a function that implements the described rules.
It need not handle any special error cases not described above. The simplest way to implement the task as described is typically to use a closure, providing the language supports them.
Where it is not possible to hold exactly to the constraints above, describe the deviations.
| #Nim | Nim |
proc accumulator[T: SomeNumber](x: T): auto =
var sum = float(x)
result = proc (n: float): float =
sum += n
result = sum
let acc = accumulator(1)
echo acc(5) # 6
discard accumulator(3) # Create another accumulator.
echo acc(2.3) # 8.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 accumulator (including the initial value passed when the accumulator was created).
Rules
The detailed rules are at http://paulgraham.com/accgensub.html and are reproduced here for simplicity (with additions in small italic text).
Before you submit an example, make sure the function
Takes a number n and returns a function (lets call it g), that takes a number i, and returns n incremented by the accumulation of i from every call of function g(i).
Although these exact function and parameter names need not be used
Works for any numeric type-- i.e. can take both ints and floats and returns functions that can take both ints and floats. (It is not enough simply to convert all input to floats. An accumulator that has only seen integers must return integers.) (i.e., if the language doesn't allow for numeric polymorphism, you have to use overloading or something like that)
Generates functions that return the sum of every number ever passed to them, not just the most recent. (This requires a piece of state to hold the accumulated value, which in turn means that pure functional languages can't be used for this task.)
Returns a real function, meaning something that you can use wherever you could use a function you had defined in the ordinary way in the text of your program. (Follow your language's conventions here.)
Doesn't store the accumulated value or the returned functions in a way that could cause them to be inadvertently modified by other code. (No global variables or other such things.)
E.g. if after the example, you added the following code (in a made-up language) where the factory function is called foo:
x = foo(1);
x(5);
foo(3);
print x(2.3);
It should print 8.3. (There is no need to print the form of the accumulator function returned by foo(3); it's not part of the task at all.)
Task
Create a function that implements the described rules.
It need not handle any special error cases not described above. The simplest way to implement the task as described is typically to use a closure, providing the language supports them.
Where it is not possible to hold exactly to the constraints above, describe the deviations.
| #Nit | Nit | # The `accumulator factory` task.
#
# Nit has no first-class function.
# A class is used to store the state.
module accumulator_factory
class Accumulator
# The accumulated sum
# Numeric is used, so Int and Float are accepted
private var sum: Numeric
fun call(n: Numeric): Numeric
do
# `add` is the safe `+` method on Numeric
sum = sum.add(n)
return sum
end
end
var x = new Accumulator(1)
x.call(5)
var y = new Accumulator(3)
print x.call(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
−
1
,
1
)
if
m
>
0
and
n
=
0
A
(
m
−
1
,
A
(
m
,
n
−
1
)
)
if
m
>
0
and
n
>
0.
{\displaystyle A(m,n)={\begin{cases}n+1&{\mbox{if }}m=0\\A(m-1,1)&{\mbox{if }}m>0{\mbox{ and }}n=0\\A(m-1,A(m,n-1))&{\mbox{if }}m>0{\mbox{ and }}n>0.\end{cases}}}
Its arguments are never negative and it always terminates.
Task
Write a function which returns the value of
A
(
m
,
n
)
{\displaystyle A(m,n)}
. Arbitrary precision is preferred (since the function grows so quickly), but not required.
See also
Conway chained arrow notation for the Ackermann function.
| #bc | bc | define ack(m, n) {
if ( m == 0 ) return (n+1);
if ( n == 0 ) return (ack(m-1, 1));
return (ack(m-1, ack(m, n-1)));
}
for (n=0; n<7; n++) {
for (m=0; m<4; m++) {
print "A(", m, ",", n, ") = ", ack(m,n), "\n";
}
}
quit |
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) == n then n is classed as perfect (OEIS A000396).
if P(n) > n then n is classed as abundant (OEIS A005101).
Example
6 has proper divisors of 1, 2, and 3.
1 + 2 + 3 = 6, so 6 is classed as a perfect number.
Task
Calculate how many of the integers 1 to 20,000 (inclusive) are in each of the three classes.
Show the results here.
Related tasks
Aliquot sequence classifications. (The whole series from which this task is a subset.)
Proper divisors
Amicable pairs
| #EchoLisp | EchoLisp |
(lib 'math) ;; sum-divisors function
(define-syntax-rule (++ a) (set! a (1+ a)))
(define (abondance (N 20000))
(define-values (delta abondant deficient perfect) '(0 0 0 0))
(for ((n (in-range 1 (1+ N))))
(set! delta (- (sum-divisors n) n))
(cond
((< delta 0) (++ deficient))
((> delta 0) (++ abondant))
(else (writeln 'perfect→ n) (++ perfect))))
(printf "In range 1.. %d" N)
(for-each (lambda(x) (writeln x (eval x))) '(abondant deficient perfect)))
(abondance)
perfect→ 6
perfect→ 28
perfect→ 496
perfect→ 8128
In range 1.. 20000
abondant 4953
deficient 15043
perfect 4
|
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, or center justified within its column.
Use the following text to test your programs:
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,$or$center$justified$within$its$column.
Note that:
The example input texts lines may, or may not, have trailing dollar characters.
All columns should share the same alignment.
Consecutive space characters produced adjacent to the end of lines are insignificant for the purposes of the task.
Output text will be viewed in a mono-spaced font on a plain text editor or basic terminal.
The minimum space between columns should be computed from the text and not hard-coded.
It is not a requirement to add separating characters between or around columns.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #FBSL | FBSL | #APPTYPE CONSOLE
DIM s = "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,$or$center$justified$within$its$column."
DIM lines[] = SPLIT(s, CRLF), tokens[], l, t, length, margin, justify = "center"
FOREACH l IN lines
tokens = SPLIT(l, "$")
FOREACH t IN tokens
IF STRLEN(t) > length THEN length = INCR(STRLEN)
NEXT
NEXT
FOREACH l IN lines
tokens = SPLIT(l, "$")
FOREACH t IN tokens
SELECT CASE justify
CASE "left"
PRINT t, SPACE(length - STRLEN(t));
CASE "center"
margin = (length - STRLEN(t)) \ 2
PRINT SPACE(margin), t, SPACE(length - STRLEN - margin);
CASE "right"
PRINT SPACE(length - STRLEN(t)), t;
END SELECT
NEXT
PRINT
NEXT
PAUSE |
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 second term is K then all future terms are also K and so the sequence repeats from the first term with period 1 and K is called perfect.
If the third term would be repeating K then the sequence repeats with period 2 and K is called amicable.
If the Nth term would be repeating K for the first time, with N > 3 then the sequence repeats with period N - 1 and K is called sociable.
Perfect, amicable and sociable numbers eventually repeat the original number K; there are other repetitions...
Some K have a sequence that eventually forms a periodic repetition of period 1 but of a number other than K, for example 95 which forms the sequence 95, 25, 6, 6, 6, ... such K are called aspiring.
K that have a sequence that eventually forms a periodic repetition of period >= 2 but of a number other than K, for example 562 which forms the sequence 562, 284, 220, 284, 220, ... such K are called cyclic.
And finally:
Some K form aliquot sequences that are not known to be either terminating or periodic; these K are to be called non-terminating.
For the purposes of this task, K is to be classed as non-terminating if it has not been otherwise classed after generating 16 terms or if any term of the sequence is greater than 2**47 = 140,737,488,355,328.
Task
Create routine(s) to generate the aliquot sequence of a positive integer enough to classify it according to the classifications given above.
Use it to display the classification and sequences of the numbers one to ten inclusive.
Use it to show the classification and sequences of the following integers, in order:
11, 12, 28, 496, 220, 1184, 12496, 1264460, 790, 909, 562, 1064, 1488, and optionally 15355717786080.
Show all output on this page.
Related tasks
Abundant, deficient and perfect number classifications. (Classifications from only the first two members of the whole sequence).
Proper divisors
Amicable pairs
| #Vlang | Vlang | import math
const threshold = u64(1) << 47
fn index_of(s []u64, search u64) int {
for i, e in s {
if e == search {
return i
}
}
return -1
}
fn contains(s []u64, search u64) bool {
return index_of(s, search) > -1
}
fn max_of(i1 int, i2 int) int {
if i1 > i2 {
return i1
}
return i2
}
fn sum_proper_divisors(n u64) u64 {
if n < 2 {
return 0
}
sqrt := u64(math.sqrt(f64(n)))
mut sum := u64(1)
for i := u64(2); i <= sqrt; i++ {
if n % i != 0 {
continue
}
sum += i + n / i
}
if sqrt * sqrt == n {
sum -= sqrt
}
return sum
}
fn classify_sequence(k u64) ([]u64, string) {
if k == 0 {
panic("Argument must be positive.")
}
mut last := k
mut seq := []u64{}
seq << k
for {
last = sum_proper_divisors(last)
seq << last
n := seq.len
mut aliquot := ""
match true {
last == 0 {
aliquot = "Terminating"
}
n == 2 && last == k {
aliquot = "Perfect"
}
n == 3 && last == k {
aliquot = "Amicable"
}
n >= 4 && last == k {
aliquot = "Sociable[${n-1}]"
}
last == seq[n - 2] {
aliquot = "Aspiring"
}
contains(seq[1 .. max_of(1, n - 2)], last) {
aliquot = "Cyclic[${n - 1 - index_of(seq, last)}]"
}
n == 16 || last > threshold {
aliquot = "Non-Terminating"
}
else {}
}
if aliquot != "" {
return seq, aliquot
}
}
return seq, ''
}
fn main() {
println("Aliquot classifications - periods for Sociable/Cyclic in square brackets:\n")
for k := u64(1); k <= 10; k++ {
seq, aliquot := classify_sequence(k)
println("${k:2}: ${aliquot:-15} $seq")
}
println('')
s := [
u64(11), 12, 28, 496, 220, 1184, 12496, 1264460, 790, 909, 562, 1064, 1488,
]
for k in s {
seq, aliquot := classify_sequence(k)
println("${k:7}: ${aliquot:-15} $seq")
}
println('')
k := u64(15355717786080)
seq, aliquot := classify_sequence(k)
println("$k: ${aliquot:-15} $seq")
} |
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 expansion of
(
x
−
1
)
p
−
(
x
p
−
1
)
{\displaystyle (x-1)^{p}-(x^{p}-1)}
are divisible by
p
{\displaystyle p}
.
Example
Using
p
=
3
{\displaystyle p=3}
:
(x-1)^3 - (x^3 - 1)
= (x^3 - 3x^2 + 3x - 1) - (x^3 - 1)
= -3x^2 + 3x
And all the coefficients are divisible by 3, so 3 is prime.
Note:
This task is not the AKS primality test. It is an inefficient exponential time algorithm discovered in the late 1600s and used as an introductory lemma in the AKS derivation.
Task
Create a function/subroutine/method that given
p
{\displaystyle p}
generates the coefficients of the expanded polynomial representation of
(
x
−
1
)
p
{\displaystyle (x-1)^{p}}
.
Use the function to show here the polynomial expansions of
(
x
−
1
)
p
{\displaystyle (x-1)^{p}}
for
p
{\displaystyle p}
in the range 0 to at least 7, inclusive.
Use the previous function in creating another function that when given
p
{\displaystyle p}
returns whether
p
{\displaystyle p}
is prime using the theorem.
Use your test to generate a list of all primes under 35.
As a stretch goal, generate all primes under 50 (needs integers larger than 31-bit).
References
Agrawal-Kayal-Saxena (AKS) primality test (Wikipedia)
Fool-Proof Test for Primes - Numberphile (Video). The accuracy of this video is disputed -- at best it is an oversimplification.
| #Perl | Perl | use strict;
use warnings;
# Select one of these lines. Math::BigInt is in core, but quite slow.
use Math::BigInt; sub binomial { Math::BigInt->new(shift)->bnok(shift) }
# use Math::Pari "binomial";
# use ntheory "binomial";
sub binprime {
my $p = shift;
return 0 unless $p >= 2;
# binomial is symmetric, so only test half the terms
for (1 .. ($p>>1)) { return 0 if binomial($p,$_) % $p }
1;
}
sub coef { # For prettier printing
my($n,$e) = @_;
return $n unless $e;
$n = "" if $n==1;
$e==1 ? "${n}x" : "${n}x^$e";
}
sub binpoly {
my $p = shift;
join(" ", coef(1,$p),
map { join("",("+","-")[($p-$_)&1]," ",coef(binomial($p,$_),$_)) }
reverse 0..$p-1 );
}
print "expansions of (x-1)^p:\n";
print binpoly($_),"\n" for 0..9;
print "Primes to 80: [", join(",", grep { binprime($_) } 2..80), "]\n"; |
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
{\displaystyle k=2}
, are the semiprimes.
Task
Write a function/method/subroutine/... that generates k-almost primes and use it to create a table here of the first ten members of k-Almost primes for
1
<=
K
<=
5
{\displaystyle 1<=K<=5}
.
Related tasks
Semiprime
Category:Prime Numbers
| #Swift | Swift | struct KPrimeGen: Sequence, IteratorProtocol {
let k: Int
private(set) var n: Int
private func isKPrime() -> Bool {
var primes = 0
var f = 2
var rem = n
while primes < k && rem > 1 {
while rem % f == 0 && rem > 1 {
rem /= f
primes += 1
}
f += 1
}
return rem == 1 && primes == k
}
mutating func next() -> Int? {
n += 1
while !isKPrime() {
n += 1
}
return n
}
}
for k in 1..<6 {
print("\(k): \(Array(KPrimeGen(k: k, n: 1).lazy.prefix(10)))")
} |
http://rosettacode.org/wiki/Almost_prime | Almost prime | A k-Almost-prime is a natural number
n
{\displaystyle n}
that is the product of
k
{\displaystyle k}
(possibly identical) primes.
Example
1-almost-primes, where
k
=
1
{\displaystyle k=1}
, are the prime numbers themselves.
2-almost-primes, where
k
=
2
{\displaystyle k=2}
, are the semiprimes.
Task
Write a function/method/subroutine/... that generates k-almost primes and use it to create a table here of the first ten members of k-Almost primes for
1
<=
K
<=
5
{\displaystyle 1<=K<=5}
.
Related tasks
Semiprime
Category:Prime Numbers
| #Tcl | Tcl | package require Tcl 8.6
package require math::numtheory
proc firstNprimes n {
for {set result {};set i 2} {[llength $result] < $n} {incr i} {
if {[::math::numtheory::isprime $i]} {
lappend result $i
}
}
return $result
}
proc firstN_KalmostPrimes {n k} {
set p [firstNprimes $n]
set i [lrepeat $k 0]
set c {}
while true {
dict set c [::tcl::mathop::* {*}[lmap j $i {lindex $p $j}]] ""
for {set x 0} {$x < $k} {incr x} {
lset i $x [set xx [expr {([lindex $i $x] + 1) % $n}]]
if {$xx} break
}
if {$x == $k} break
}
return [lrange [lsort -integer [dict keys $c]] 0 [expr {$n - 1}]]
}
for {set K 1} {$K <= 5} {incr K} {
puts "$K => [firstN_KalmostPrimes 10 $K]"
} |
http://rosettacode.org/wiki/Anagrams | Anagrams | When two or more words are composed of the same characters, but in a different order, they are called anagrams.
Task[edit]
Using the word list at http://wiki.puzzlers.org/pub/wordlists/unixdict.txt,
find the sets of words that share the same characters that contain the most words in them.
Related tasks
Word plays
Ordered words
Palindrome detection
Semordnilap
Anagrams
Anagrams/Deranged anagrams
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Julia | Julia | url = "http://wiki.puzzlers.org/pub/wordlists/unixdict.txt"
wordlist = open(readlines, download(url))
wsort(word::AbstractString) = join(sort(collect(word)))
function anagram(wordlist::Vector{<:AbstractString})
dict = Dict{String, Set{String}}()
for word in wordlist
sorted = wsort(word)
push!(get!(dict, sorted, Set{String}()), word)
end
wcnt = maximum(length, values(dict))
return collect(Iterators.filter((y) -> length(y) == wcnt, values(dict)))
end
println.(anagram(wordlist)) |
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 function doesn't have the right arguments and/or return values.
So we end up inventing some silly name like foo2 or foo_helper. I have always found it painful to come up with a proper name, and see some disadvantages:
You have to think up a name, which then pollutes the namespace
Function is created which is called from nowhere else
The program flow in the source code is interrupted
Some languages allow you to embed recursion directly in-place. This might work via a label, a local gosub instruction, or some special keyword.
Anonymous recursion can also be accomplished using the Y combinator.
Task
If possible, demonstrate this by writing the recursive version of the fibonacci function (see Fibonacci sequence) which checks for a negative argument before doing the actual recursion.
| #SuperCollider | SuperCollider |
(
f = { |n|
if(n >= 0) {
if(n < 2) { n } { thisFunction.(n-1) + thisFunction.(n-2) }
}
};
(0..20).collect(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
{\displaystyle =M}
as well as
s
u
m
(
p
r
o
p
D
i
v
s
(
M
)
)
=
N
{\displaystyle \mathrm {sum} (\mathrm {propDivs} (M))=N}
.
Example
1184 and 1210 are an amicable pair, with proper divisors:
1, 2, 4, 8, 16, 32, 37, 74, 148, 296, 592 and
1, 2, 5, 10, 11, 22, 55, 110, 121, 242, 605 respectively.
Task
Calculate and show here the Amicable pairs below 20,000; (there are eight).
Related tasks
Proper divisors
Abundant, deficient and perfect number classifications
Aliquot sequence classifications and its amicable classification.
| #Scala | Scala | def properDivisors(n: Int) = (1 to n/2).filter(i => n % i == 0)
val divisorsSum = (1 to 20000).map(i => i -> properDivisors(i).sum).toMap
val result = divisorsSum.filter(v => v._1 < v._2 && divisorsSum.get(v._2) == Some(v._1))
println( result mkString ", " ) |
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 variable number of expressions (or values if that's simpler in the language) and yields a correct one which will satisfy a constraint in some future computation, thereby avoiding failure.
Problems whose solution the Amb operator naturally expresses can be approached with other tools, such as explicit nested iterations over data sets, or with pattern matching. By contrast, the Amb operator appears integrated into the language. Invocations of Amb are not wrapped in any visible loops or other search patterns; they appear to be independent.
Essentially Amb(x, y, z) splits the computation into three possible futures: a future in which the value x is yielded, a future in which the value y is yielded and a future in which the value z is yielded. The future which leads to a successful subsequent computation is chosen. The other "parallel universes" somehow go away. Amb called with no arguments fails.
For simplicity, one of the domain values usable with Amb may denote failure, if that is convenient. For instance, it is convenient if a Boolean false denotes failure, so that Amb(false) fails, and thus constraints can be expressed using Boolean expressions like Amb(x * y == 8) which unless x and y add to four.
A pseudo-code program which satisfies this constraint might look like:
let x = Amb(1, 2, 3)
let y = Amb(7, 6, 4, 5)
Amb(x * y = 8)
print x, y
The output is 2 4 because Amb(1, 2, 3) correctly chooses the future in which x has value 2, Amb(7, 6, 4, 5) chooses 4 and consequently Amb(x * y = 8) produces a success.
Alternatively, failure could be represented using strictly Amb():
unless x * y = 8 do Amb()
Or else Amb could take the form of two operators or functions: one for producing values and one for enforcing constraints:
let x = Ambsel(1, 2, 3)
let y = Ambsel(4, 5, 6)
Ambassert(x * y = 8)
print x, y
where Ambassert behaves like Amb() if the Boolean expression is false, otherwise it allows the future computation to take place, without yielding any value.
The task is to somehow implement Amb, and demonstrate it with a program which chooses one word from each of the following four sets of character strings to generate a four-word sentence:
"the" "that" "a"
"frog" "elephant" "thing"
"walked" "treaded" "grows"
"slowly" "quickly"
The constraint to be satisfied is that the last character of each word (other than the last) is the same as the first character of its successor.
The only successful sentence is "that thing grows slowly"; other combinations do not satisfy the constraint and thus fail.
The goal of this task isn't to simply process the four lists of words with explicit, deterministic program flow such as nested iteration, to trivially demonstrate the correct output. The goal is to implement the Amb operator, or a facsimile thereof that is possible within the language limitations.
| #REXX | REXX | /*REXX program demonstrates the Amd operator, choosing a word from each set. */
@.1 = "the that a"
@.2 = "frog elephant thing"
@.3 = "walked treaded grows"
@.4 = "slowly quickly"
@.0 = 4 /*define the number of sets being ised.*/
call Amb 1 /*find all word combinations that works*/
exit /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
Amb: procedure expose @.; parse arg # x; arg . u /*ARG uppercases U value. */
if #>@.0 then do; y= word(u, 1) /*Y: is a uppercased U. */
do n=2 to words(u); ?= word(u, n)
if left(?, 1) \== right(y, 1) then return; y= ?
end /*n*/
say strip(x) /*¬show superfluous blanks.*/
end
do j=1 for words(@.#); call Amb #+1 x word(@.#, j) /*gen all combos recursively*/
end /*j*/; return |
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 accumulator (including the initial value passed when the accumulator was created).
Rules
The detailed rules are at http://paulgraham.com/accgensub.html and are reproduced here for simplicity (with additions in small italic text).
Before you submit an example, make sure the function
Takes a number n and returns a function (lets call it g), that takes a number i, and returns n incremented by the accumulation of i from every call of function g(i).
Although these exact function and parameter names need not be used
Works for any numeric type-- i.e. can take both ints and floats and returns functions that can take both ints and floats. (It is not enough simply to convert all input to floats. An accumulator that has only seen integers must return integers.) (i.e., if the language doesn't allow for numeric polymorphism, you have to use overloading or something like that)
Generates functions that return the sum of every number ever passed to them, not just the most recent. (This requires a piece of state to hold the accumulated value, which in turn means that pure functional languages can't be used for this task.)
Returns a real function, meaning something that you can use wherever you could use a function you had defined in the ordinary way in the text of your program. (Follow your language's conventions here.)
Doesn't store the accumulated value or the returned functions in a way that could cause them to be inadvertently modified by other code. (No global variables or other such things.)
E.g. if after the example, you added the following code (in a made-up language) where the factory function is called foo:
x = foo(1);
x(5);
foo(3);
print x(2.3);
It should print 8.3. (There is no need to print the form of the accumulator function returned by foo(3); it's not part of the task at all.)
Task
Create a function that implements the described rules.
It need not handle any special error cases not described above. The simplest way to implement the task as described is typically to use a closure, providing the language supports them.
Where it is not possible to hold exactly to the constraints above, describe the deviations.
| #Objeck | Objeck | bundle Default {
class Accumulator {
@sum : Float;
New(sum : Float) {
@sum := sum;
}
method : public : Call(n : Float) ~ Float {
@sum += n;
return @sum;
}
function : Main(args : String[]) ~ Nil {
x := Accumulator->New(1.0);
x->Call(5.0 );
x->Call(2.3)->PrintLine();
}
}
} |
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 accumulator (including the initial value passed when the accumulator was created).
Rules
The detailed rules are at http://paulgraham.com/accgensub.html and are reproduced here for simplicity (with additions in small italic text).
Before you submit an example, make sure the function
Takes a number n and returns a function (lets call it g), that takes a number i, and returns n incremented by the accumulation of i from every call of function g(i).
Although these exact function and parameter names need not be used
Works for any numeric type-- i.e. can take both ints and floats and returns functions that can take both ints and floats. (It is not enough simply to convert all input to floats. An accumulator that has only seen integers must return integers.) (i.e., if the language doesn't allow for numeric polymorphism, you have to use overloading or something like that)
Generates functions that return the sum of every number ever passed to them, not just the most recent. (This requires a piece of state to hold the accumulated value, which in turn means that pure functional languages can't be used for this task.)
Returns a real function, meaning something that you can use wherever you could use a function you had defined in the ordinary way in the text of your program. (Follow your language's conventions here.)
Doesn't store the accumulated value or the returned functions in a way that could cause them to be inadvertently modified by other code. (No global variables or other such things.)
E.g. if after the example, you added the following code (in a made-up language) where the factory function is called foo:
x = foo(1);
x(5);
foo(3);
print x(2.3);
It should print 8.3. (There is no need to print the form of the accumulator function returned by foo(3); it's not part of the task at all.)
Task
Create a function that implements the described rules.
It need not handle any special error cases not described above. The simplest way to implement the task as described is typically to use a closure, providing the language supports them.
Where it is not possible to hold exactly to the constraints above, describe the deviations.
| #Objective-C | Objective-C | #import <Foundation/Foundation.h>
typedef double (^Accumulator)(double);
Accumulator accumulator_factory(double initial) {
__block double sum = initial;
Accumulator acc = ^(double n){
return sum += n;
};
return acc;
}
int main (int argc, const char * argv[]) {
@autoreleasepool {
Accumulator x = accumulator_factory(1);
x(5);
accumulator_factory(3);
NSLog(@"%f", x(2.3));
}
return 0;
} |
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
−
1
,
1
)
if
m
>
0
and
n
=
0
A
(
m
−
1
,
A
(
m
,
n
−
1
)
)
if
m
>
0
and
n
>
0.
{\displaystyle A(m,n)={\begin{cases}n+1&{\mbox{if }}m=0\\A(m-1,1)&{\mbox{if }}m>0{\mbox{ and }}n=0\\A(m-1,A(m,n-1))&{\mbox{if }}m>0{\mbox{ and }}n>0.\end{cases}}}
Its arguments are never negative and it always terminates.
Task
Write a function which returns the value of
A
(
m
,
n
)
{\displaystyle A(m,n)}
. Arbitrary precision is preferred (since the function grows so quickly), but not required.
See also
Conway chained arrow notation for the Ackermann function.
| #BCPL | BCPL | GET "libhdr"
LET ack(m, n) = m=0 -> n+1,
n=0 -> ack(m-1, 1),
ack(m-1, ack(m, n-1))
LET start() = VALOF
{ FOR i = 0 TO 6 FOR m = 0 TO 3 DO
writef("ack(%n, %n) = %n*n", m, n, ack(m,n))
RESULTIS 0
} |
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) == n then n is classed as perfect (OEIS A000396).
if P(n) > n then n is classed as abundant (OEIS A005101).
Example
6 has proper divisors of 1, 2, and 3.
1 + 2 + 3 = 6, so 6 is classed as a perfect number.
Task
Calculate how many of the integers 1 to 20,000 (inclusive) are in each of the three classes.
Show the results here.
Related tasks
Aliquot sequence classifications. (The whole series from which this task is a subset.)
Proper divisors
Amicable pairs
| #Ela | Ela | open monad io number list
divisors n = filter ((0 ==) << (n `mod`)) [1 .. (n `div` 2)]
classOf n = compare (sum $ divisors n) n
do
let classes = map classOf [1 .. 20000]
let printRes w c = putStrLn $ w ++ (show << length $ filter (== c) classes)
printRes "deficient: " LT
printRes "perfect: " EQ
printRes "abundant: " GT |
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, or center justified within its column.
Use the following text to test your programs:
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,$or$center$justified$within$its$column.
Note that:
The example input texts lines may, or may not, have trailing dollar characters.
All columns should share the same alignment.
Consecutive space characters produced adjacent to the end of lines are insignificant for the purposes of the task.
Output text will be viewed in a mono-spaced font on a plain text editor or basic terminal.
The minimum space between columns should be computed from the text and not hard-coded.
It is not a requirement to add separating characters between or around columns.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Forth | Forth | \ align columns
: split ( addr len char -- addr len1 addr len-len1 )
>r 2dup r> scan 2swap 2 pick - ;
variable column
: for-each-line ( file len xt -- )
>r begin #lf split r@ execute 1 /string dup 0<= until 2drop rdrop ;
: for-each-field ( line len xt -- )
0 column !
>r begin '$ split r@ execute 1 column +! 1 /string dup 0<= until 2drop rdrop ;
0 value num-columns
: count-columns ( line len -- )
['] 2drop for-each-field
num-columns column @ max to num-columns ;
: find-num-columns ( file len -- )
0 to num-columns
['] count-columns for-each-line ;
0 value column-widths
: column-width ( field len -- )
column-widths column @ + c@
max
column-widths column @ + c!
drop ;
: measure-widths ( line len -- )
['] column-width for-each-field ;
: find-column-widths ( file len -- )
num-columns allocate throw to column-widths
column-widths num-columns erase
['] measure-widths for-each-line ;
\ type aligned, same naming convention as standard numeric U.R, .R
: type.l ( addr len width -- )
over - >r type r> spaces ;
: type.c ( addr len width -- )
over - dup 2/ spaces >r type r> 1+ 2/ spaces ;
: type.r ( addr len width -- )
over - spaces type ;
defer type.aligned
: print-field ( field len -- )
column-widths column @ + c@ type.aligned space ;
: print-line ( line len -- ) cr ['] print-field for-each-field ;
: print-fields ( file len -- ) ['] print-line for-each-line ;
\ read file
s" columns.txt" slurp-file ( file len )
\ scan once to determine num-columns
2dup find-num-columns
\ scan again to determine column-widths
2dup find-column-widths
\ print columns, once for each alignment type
' type.l is type.aligned 2dup print-fields cr
' type.c is type.aligned 2dup print-fields cr
' type.r is type.aligned 2dup print-fields cr
\ cleanup
nip free throw
column-widths free throw |
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 second term is K then all future terms are also K and so the sequence repeats from the first term with period 1 and K is called perfect.
If the third term would be repeating K then the sequence repeats with period 2 and K is called amicable.
If the Nth term would be repeating K for the first time, with N > 3 then the sequence repeats with period N - 1 and K is called sociable.
Perfect, amicable and sociable numbers eventually repeat the original number K; there are other repetitions...
Some K have a sequence that eventually forms a periodic repetition of period 1 but of a number other than K, for example 95 which forms the sequence 95, 25, 6, 6, 6, ... such K are called aspiring.
K that have a sequence that eventually forms a periodic repetition of period >= 2 but of a number other than K, for example 562 which forms the sequence 562, 284, 220, 284, 220, ... such K are called cyclic.
And finally:
Some K form aliquot sequences that are not known to be either terminating or periodic; these K are to be called non-terminating.
For the purposes of this task, K is to be classed as non-terminating if it has not been otherwise classed after generating 16 terms or if any term of the sequence is greater than 2**47 = 140,737,488,355,328.
Task
Create routine(s) to generate the aliquot sequence of a positive integer enough to classify it according to the classifications given above.
Use it to display the classification and sequences of the numbers one to ten inclusive.
Use it to show the classification and sequences of the following integers, in order:
11, 12, 28, 496, 220, 1184, 12496, 1264460, 790, 909, 562, 1064, 1488, and optionally 15355717786080.
Show all output on this page.
Related tasks
Abundant, deficient and perfect number classifications. (Classifications from only the first two members of the whole sequence).
Proper divisors
Amicable pairs
| #Wren | Wren | import "/fmt" for Conv, Fmt
import "/math" for Int, Nums
import "/seq" for Lst
class Classification {
construct new(seq, aliquot) {
_seq = seq
_aliquot = aliquot
}
seq { _seq}
aliquot { _aliquot }
}
var THRESHOLD = 2.pow(47)
var classifySequence = Fn.new { |k|
if (k <= 0) Fiber.abort("K must be positive")
var last = k
var seq = [k]
while (true) {
last = Nums.sum(Int.properDivisors(last))
seq.add(last)
var n = seq.count
var aliquot =
(last == 0) ? "Terminating" :
(n == 2 && last == k) ? "Perfect" :
(n == 3 && last == k) ? "Amicable" :
(n >= 4 && last == k) ? "Sociable[%(n-1)]" :
(last == seq[n-2]) ? "Aspiring" :
(n > 3 && seq[1..n-3].contains(last)) ? "Cyclic[%(n-1-Lst.indexOf(seq, last))]" :
(n == 16 || last > THRESHOLD) ? "Non-terminating" : ""
if (aliquot != "") return Classification.new(seq, aliquot)
}
}
System.print("Aliquot classifications - periods for Sociable/Cyclic in square brackets:\n")
for (k in 1..10) {
var c = classifySequence.call(k)
System.print("%(Fmt.d(2, k)): %(Fmt.s(-15, c.aliquot)) %(c.seq)")
}
System.print()
var a = [11, 12, 28, 496, 220, 1184, 12496, 1264460, 790, 909, 562, 1064, 1488]
for (k in a) {
var c = classifySequence.call(k)
System.print("%(Fmt.d(7, k)): %(Fmt.s(-15, c.aliquot)) %(c.seq)")
}
System.print()
var k = 15355717786080
var c = classifySequence.call(k)
var seq = c.seq.map { |i| Conv.dec(i) }.toList // ensure 15 digit integer is printed in full
System.print("%(k): %(Fmt.s(-15, c.aliquot)) %(seq)") |
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 expansion of
(
x
−
1
)
p
−
(
x
p
−
1
)
{\displaystyle (x-1)^{p}-(x^{p}-1)}
are divisible by
p
{\displaystyle p}
.
Example
Using
p
=
3
{\displaystyle p=3}
:
(x-1)^3 - (x^3 - 1)
= (x^3 - 3x^2 + 3x - 1) - (x^3 - 1)
= -3x^2 + 3x
And all the coefficients are divisible by 3, so 3 is prime.
Note:
This task is not the AKS primality test. It is an inefficient exponential time algorithm discovered in the late 1600s and used as an introductory lemma in the AKS derivation.
Task
Create a function/subroutine/method that given
p
{\displaystyle p}
generates the coefficients of the expanded polynomial representation of
(
x
−
1
)
p
{\displaystyle (x-1)^{p}}
.
Use the function to show here the polynomial expansions of
(
x
−
1
)
p
{\displaystyle (x-1)^{p}}
for
p
{\displaystyle p}
in the range 0 to at least 7, inclusive.
Use the previous function in creating another function that when given
p
{\displaystyle p}
returns whether
p
{\displaystyle p}
is prime using the theorem.
Use your test to generate a list of all primes under 35.
As a stretch goal, generate all primes under 50 (needs integers larger than 31-bit).
References
Agrawal-Kayal-Saxena (AKS) primality test (Wikipedia)
Fool-Proof Test for Primes - Numberphile (Video). The accuracy of this video is disputed -- at best it is an oversimplification.
| #Phix | Phix | -- demo/rosetta/AKSprimes.exw
-- Does not work for primes above 53, which is actually beyond the original task anyway.
-- Translated from the C version, just about everything is (working) out-by-1, what fun.
sequence c = repeat(0,100)
procedure coef(integer n)
-- out-by-1, ie coef(1)==^0, coef(2)==^1, coef(3)==^2 etc.
c[n] = 1
for i=n-1 to 2 by -1 do
c[i] = c[i]+c[i-1]
end for
end procedure
function is_aks_prime(integer n)
coef(n+1); -- (I said it was out-by-1)
for i=2 to n-1 do -- (technically "to n" is more correct)
if remainder(c[i],n)!=0 then
return 0
end if
end for
return 1
end function
procedure show(integer n)
-- (As per coef, this is (working) out-by-1)
object ci
for i=n to 1 by -1 do
ci = c[i]
if ci=1 then
if remainder(n-i,2)=0 then
if i=1 then
if n=1 then
ci = "1"
else
ci = "+1"
end if
else
ci = ""
end if
else
ci = "-1"
end if
else
if remainder(n-i,2)=0 then
ci = sprintf("+%d",ci)
else
ci = sprintf("-%d",ci)
end if
end if
if i=1 then -- ie ^0
printf(1,"%s",{ci})
elsif i=2 then -- ie ^1
printf(1,"%sx",{ci})
else
printf(1,"%sx^%d",{ci,i-1})
end if
end for
end procedure
procedure main()
for n=1 to 10 do -- (0 to 9 really)
coef(n);
printf(1,"(x-1)^%d = ", n-1);
show(n);
puts(1,'\n');
end for
puts(1,"\nprimes (<=53):");
-- coef(2); -- (needed to reset c, if we want to avoid saying 1 is prime...)
c[2] = 1 -- (this manages "", which is all that call did anyway...)
for n = 2 to 53 do
if is_aks_prime(n) then
printf(1," %d", n);
end if
end for
puts(1,'\n');
if getc(0) then end if
end procedure
main()
|
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
{\displaystyle k=2}
, are the semiprimes.
Task
Write a function/method/subroutine/... that generates k-almost primes and use it to create a table here of the first ten members of k-Almost primes for
1
<=
K
<=
5
{\displaystyle 1<=K<=5}
.
Related tasks
Semiprime
Category:Prime Numbers
| #Tiny_BASIC | Tiny BASIC |
REM Almost prime
LET K=1
10 IF K>5 THEN END
PRINT "k = ",K,":"
LET I=2
LET C=0
20 IF C>=10 THEN GOTO 40
LET N=I
GOSUB 500
IF P=0 THEN GOTO 30
PRINT I
LET C=C+1
30 LET I=I+1
GOTO 20
40 LET K=K+1
GOTO 10
REM Check if N is a K prime (result: P)
500 LET F=0
LET J=2
510 IF (N/J)*J<>N THEN GOTO 520
IF F=K THEN GOTO 530
LET F=F+1
LET N=N/J
GOTO 510
520 LET J=J+1
IF J<=N THEN GOTO 510
LET P=0
IF F=K THEN LET P=-1
RETURN
530 LET P=0
RETURN
|
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
{\displaystyle k=2}
, are the semiprimes.
Task
Write a function/method/subroutine/... that generates k-almost primes and use it to create a table here of the first ten members of k-Almost primes for
1
<=
K
<=
5
{\displaystyle 1<=K<=5}
.
Related tasks
Semiprime
Category:Prime Numbers
| #TypeScript | TypeScript | // Almost prime
function isKPrime(n: number, k: number): bool {
var f = 0;
for (var i = 2; i <= n; i++)
while (n % i == 0) {
if (f == k)
return false;
++f;
n = Math.floor(n / i);
}
return f == k;
}
for (var k = 1; k <= 5; k++) {
process.stdout.write(`k = ${k}:`);
var i = 2, c = 0;
while (c < 10) {
if (isKPrime(i, k)) {
process.stdout.write(" " + i.toString().padStart(3, ' '));
++c;
}
++i;
}
console.log();
}
|
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
Ordered words
Palindrome detection
Semordnilap
Anagrams
Anagrams/Deranged anagrams
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #K | K | {x@&a=|/a:#:'x}{x g@&1<#:'g:={x@<x}'x}0::`unixdict.txt |
http://rosettacode.org/wiki/Anonymous_recursion | Anonymous recursion | While implementing a recursive function, it often happens that we must resort to a separate helper function to handle the actual recursion.
This is usually the case when directly calling the current function would waste too many resources (stack space, execution time), causing unwanted side-effects, and/or the function doesn't have the right arguments and/or return values.
So we end up inventing some silly name like foo2 or foo_helper. I have always found it painful to come up with a proper name, and see some disadvantages:
You have to think up a name, which then pollutes the namespace
Function is created which is called from nowhere else
The program flow in the source code is interrupted
Some languages allow you to embed recursion directly in-place. This might work via a label, a local gosub instruction, or some special keyword.
Anonymous recursion can also be accomplished using the Y combinator.
Task
If possible, demonstrate this by writing the recursive version of the fibonacci function (see Fibonacci sequence) which checks for a negative argument before doing the actual recursion.
| #Swift | Swift | let fib: Int -> Int = {
func f(n: Int) -> Int {
assert(n >= 0, "fib: no negative numbers")
return n < 2 ? 1 : f(n-1) + f(n-2)
}
return f
}()
print(fib(8)) |
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
{\displaystyle =M}
as well as
s
u
m
(
p
r
o
p
D
i
v
s
(
M
)
)
=
N
{\displaystyle \mathrm {sum} (\mathrm {propDivs} (M))=N}
.
Example
1184 and 1210 are an amicable pair, with proper divisors:
1, 2, 4, 8, 16, 32, 37, 74, 148, 296, 592 and
1, 2, 5, 10, 11, 22, 55, 110, 121, 242, 605 respectively.
Task
Calculate and show here the Amicable pairs below 20,000; (there are eight).
Related tasks
Proper divisors
Abundant, deficient and perfect number classifications
Aliquot sequence classifications and its amicable classification.
| #Scheme | Scheme |
(import (scheme base)
(scheme inexact)
(scheme write)
(only (srfi 1) fold))
;; return a list of the proper-divisors of n
(define (proper-divisors n)
(let ((root (sqrt n)))
(let loop ((divisors (list 1))
(i 2))
(if (> i root)
divisors
(loop (if (zero? (modulo n i))
(if (= (square i) n)
(cons i divisors)
(append (list i (quotient n i)) divisors))
divisors)
(+ 1 i))))))
(define (sum-proper-divisors n)
(if (< n 2)
0
(fold + 0 (proper-divisors n))))
(define *max-n* 20000)
;; hold sums of proper divisors in a cache, to avoid recalculating
(define *cache* (make-vector (+ 1 *max-n*)))
(for-each (lambda (i) (vector-set! *cache* i (sum-proper-divisors i)))
(iota *max-n* 1))
(define (amicable-pair? i j)
(and (not (= i j))
(= i (vector-ref *cache* j))
(= j (vector-ref *cache* i))))
;; double loop to *max-n*, displaying all amicable pairs
(let loop-i ((i 1))
(when (<= i *max-n*)
(let loop-j ((j i))
(when (<= j *max-n*)
(when (amicable-pair? i j)
(display (string-append "Amicable pair: "
(number->string i)
" "
(number->string j)))
(newline))
(loop-j (+ 1 j))))
(loop-i (+ 1 i))))
|
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 variable number of expressions (or values if that's simpler in the language) and yields a correct one which will satisfy a constraint in some future computation, thereby avoiding failure.
Problems whose solution the Amb operator naturally expresses can be approached with other tools, such as explicit nested iterations over data sets, or with pattern matching. By contrast, the Amb operator appears integrated into the language. Invocations of Amb are not wrapped in any visible loops or other search patterns; they appear to be independent.
Essentially Amb(x, y, z) splits the computation into three possible futures: a future in which the value x is yielded, a future in which the value y is yielded and a future in which the value z is yielded. The future which leads to a successful subsequent computation is chosen. The other "parallel universes" somehow go away. Amb called with no arguments fails.
For simplicity, one of the domain values usable with Amb may denote failure, if that is convenient. For instance, it is convenient if a Boolean false denotes failure, so that Amb(false) fails, and thus constraints can be expressed using Boolean expressions like Amb(x * y == 8) which unless x and y add to four.
A pseudo-code program which satisfies this constraint might look like:
let x = Amb(1, 2, 3)
let y = Amb(7, 6, 4, 5)
Amb(x * y = 8)
print x, y
The output is 2 4 because Amb(1, 2, 3) correctly chooses the future in which x has value 2, Amb(7, 6, 4, 5) chooses 4 and consequently Amb(x * y = 8) produces a success.
Alternatively, failure could be represented using strictly Amb():
unless x * y = 8 do Amb()
Or else Amb could take the form of two operators or functions: one for producing values and one for enforcing constraints:
let x = Ambsel(1, 2, 3)
let y = Ambsel(4, 5, 6)
Ambassert(x * y = 8)
print x, y
where Ambassert behaves like Amb() if the Boolean expression is false, otherwise it allows the future computation to take place, without yielding any value.
The task is to somehow implement Amb, and demonstrate it with a program which chooses one word from each of the following four sets of character strings to generate a four-word sentence:
"the" "that" "a"
"frog" "elephant" "thing"
"walked" "treaded" "grows"
"slowly" "quickly"
The constraint to be satisfied is that the last character of each word (other than the last) is the same as the first character of its successor.
The only successful sentence is "that thing grows slowly"; other combinations do not satisfy the constraint and thus fail.
The goal of this task isn't to simply process the four lists of words with explicit, deterministic program flow such as nested iteration, to trivially demonstrate the correct output. The goal is to implement the Amb operator, or a facsimile thereof that is possible within the language limitations.
| #Ring | Ring |
# Project : Amb
set1 = ["the","that","a"]
set2 = ["frog","elephant","thing"]
set3 = ["walked","treaded","grows"]
set4 = ["slowly","quickly"]
text = amb(set1,set2,set3,set4)
if text != ""
see "Correct sentence would be: " + nl + text + nl
else
see "Failed to fine a correct sentence."
ok
func wordsok(string1, string2)
if substr(string1,len(string1),1) = substr(string2,1,1)
return true
ok
return false
func amb(a,b,c,d)
for a2 = 1 to len(a)
for b2 =1 to len(b)
for c2 = 1 to len(c)
for d2 = 1 to len(d)
if wordsok(a[a2],b[b2]) and wordsok(b[b2],c[c2]) and wordsok(c[c2],d[d2])
return a[a2]+" "+b[b2]+" "+c[c2]+" "+d[d2]
ok
next
next
next
next
return ""
|
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 variable number of expressions (or values if that's simpler in the language) and yields a correct one which will satisfy a constraint in some future computation, thereby avoiding failure.
Problems whose solution the Amb operator naturally expresses can be approached with other tools, such as explicit nested iterations over data sets, or with pattern matching. By contrast, the Amb operator appears integrated into the language. Invocations of Amb are not wrapped in any visible loops or other search patterns; they appear to be independent.
Essentially Amb(x, y, z) splits the computation into three possible futures: a future in which the value x is yielded, a future in which the value y is yielded and a future in which the value z is yielded. The future which leads to a successful subsequent computation is chosen. The other "parallel universes" somehow go away. Amb called with no arguments fails.
For simplicity, one of the domain values usable with Amb may denote failure, if that is convenient. For instance, it is convenient if a Boolean false denotes failure, so that Amb(false) fails, and thus constraints can be expressed using Boolean expressions like Amb(x * y == 8) which unless x and y add to four.
A pseudo-code program which satisfies this constraint might look like:
let x = Amb(1, 2, 3)
let y = Amb(7, 6, 4, 5)
Amb(x * y = 8)
print x, y
The output is 2 4 because Amb(1, 2, 3) correctly chooses the future in which x has value 2, Amb(7, 6, 4, 5) chooses 4 and consequently Amb(x * y = 8) produces a success.
Alternatively, failure could be represented using strictly Amb():
unless x * y = 8 do Amb()
Or else Amb could take the form of two operators or functions: one for producing values and one for enforcing constraints:
let x = Ambsel(1, 2, 3)
let y = Ambsel(4, 5, 6)
Ambassert(x * y = 8)
print x, y
where Ambassert behaves like Amb() if the Boolean expression is false, otherwise it allows the future computation to take place, without yielding any value.
The task is to somehow implement Amb, and demonstrate it with a program which chooses one word from each of the following four sets of character strings to generate a four-word sentence:
"the" "that" "a"
"frog" "elephant" "thing"
"walked" "treaded" "grows"
"slowly" "quickly"
The constraint to be satisfied is that the last character of each word (other than the last) is the same as the first character of its successor.
The only successful sentence is "that thing grows slowly"; other combinations do not satisfy the constraint and thus fail.
The goal of this task isn't to simply process the four lists of words with explicit, deterministic program flow such as nested iteration, to trivially demonstrate the correct output. The goal is to implement the Amb operator, or a facsimile thereof that is possible within the language limitations.
| #Ruby | Ruby | require "continuation"
class Amb
class ExhaustedError < RuntimeError; end
def initialize
@fail = proc { fail ExhaustedError, "amb tree exhausted" }
end
def choose(*choices)
prev_fail = @fail
callcc { |sk|
choices.each { |choice|
callcc { |fk|
@fail = proc {
@fail = prev_fail
fk.call(:fail)
}
if choice.respond_to? :call
sk.call(choice.call)
else
sk.call(choice)
end
}
}
@fail.call
}
end
def failure
choose
end
def assert(cond)
failure unless cond
end
end
A = Amb.new
w1 = A.choose("the", "that", "a")
w2 = A.choose("frog", "elephant", "thing")
w3 = A.choose("walked", "treaded", "grows")
w4 = A.choose("slowly", "quickly")
A.choose() unless w1[-1] == w2[0]
A.choose() unless w2[-1] == w3[0]
A.choose() unless w3[-1] == w4[0]
puts w1, w2, w3, w4 |
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 accumulator (including the initial value passed when the accumulator was created).
Rules
The detailed rules are at http://paulgraham.com/accgensub.html and are reproduced here for simplicity (with additions in small italic text).
Before you submit an example, make sure the function
Takes a number n and returns a function (lets call it g), that takes a number i, and returns n incremented by the accumulation of i from every call of function g(i).
Although these exact function and parameter names need not be used
Works for any numeric type-- i.e. can take both ints and floats and returns functions that can take both ints and floats. (It is not enough simply to convert all input to floats. An accumulator that has only seen integers must return integers.) (i.e., if the language doesn't allow for numeric polymorphism, you have to use overloading or something like that)
Generates functions that return the sum of every number ever passed to them, not just the most recent. (This requires a piece of state to hold the accumulated value, which in turn means that pure functional languages can't be used for this task.)
Returns a real function, meaning something that you can use wherever you could use a function you had defined in the ordinary way in the text of your program. (Follow your language's conventions here.)
Doesn't store the accumulated value or the returned functions in a way that could cause them to be inadvertently modified by other code. (No global variables or other such things.)
E.g. if after the example, you added the following code (in a made-up language) where the factory function is called foo:
x = foo(1);
x(5);
foo(3);
print x(2.3);
It should print 8.3. (There is no need to print the form of the accumulator function returned by foo(3); it's not part of the task at all.)
Task
Create a function that implements the described rules.
It need not handle any special error cases not described above. The simplest way to implement the task as described is typically to use a closure, providing the language supports them.
Where it is not possible to hold exactly to the constraints above, describe the deviations.
| #OCaml | OCaml | let accumulator sum0 =
let sum = ref sum0 in
fun n ->
sum := !sum +. n;
!sum;;
let _ =
let x = accumulator 1.0 in
ignore (x 5.0);
let _ = accumulator 3.0 in
Printf.printf "%g\n" (x 2.3)
;; |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.