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/Search_a_list_of_records
|
Search a list of records
|
Many programming languages provide convenient ways to look for a known value in a simple list of strings or numbers.
But what if the elements of the list are themselves compound records/objects/data-structures, and the search condition is more complex than a simple equality test?
Task[edit]
Write a function/method/etc. that can find the first element in a given list matching a given condition.
It should be as generic and reusable as possible.
(Of course if your programming language already provides such a feature, you can use that instead of recreating it.)
Then to demonstrate its functionality, create the data structure specified under #Data set, and perform on it the searches specified under #Test cases.
Data set
The data structure to be used contains the names and populations (in millions) of the 10 largest metropolitan areas in Africa, and looks as follows when represented in JSON:
[
{ "name": "Lagos", "population": 21.0 },
{ "name": "Cairo", "population": 15.2 },
{ "name": "Kinshasa-Brazzaville", "population": 11.3 },
{ "name": "Greater Johannesburg", "population": 7.55 },
{ "name": "Mogadishu", "population": 5.85 },
{ "name": "Khartoum-Omdurman", "population": 4.98 },
{ "name": "Dar Es Salaam", "population": 4.7 },
{ "name": "Alexandria", "population": 4.58 },
{ "name": "Abidjan", "population": 4.4 },
{ "name": "Casablanca", "population": 3.98 }
]
However, you shouldn't parse it from JSON, but rather represent it natively in your programming language.
The top-level data structure should be an ordered collection (i.e. a list, array, vector, or similar).
Each element in this list should be an associative collection that maps from keys to values (i.e. a struct, object, hash map, dictionary, or similar).
Each of them has two entries: One string value with key "name", and one numeric value with key "population".
You may rely on the list being sorted by population count, as long as you explain this to readers.
If any of that is impossible or unreasonable in your programming language, then feel free to deviate, as long as you explain your reasons in a comment above your solution.
Test cases
Search
Expected result
Find the (zero-based) index of the first city in the list whose name is "Dar Es Salaam"
6
Find the name of the first city in this list whose population is less than 5 million
Khartoum-Omdurman
Find the population of the first city in this list whose name starts with the letter "A"
4.58
Guidance
If your programming language supports higher-order programming, then the most elegant way to implement the requested functionality in a generic and reusable way, might be to write a function (maybe called "find_index" or similar), that takes two arguments:
The list to search through.
A function/lambda/closure (the so-called "predicate"), which will be applied in turn to each element in the list, and whose boolean return value defines whether that element matches the search requirement.
If this is not the approach which would be most natural or idiomatic in your language, explain why, and show what is.
Related tasks
Search a list
|
#jq
|
jq
|
def first(s): [s][0];
|
http://rosettacode.org/wiki/Safe_addition
|
Safe addition
|
Implementation of interval arithmetic and more generally fuzzy number arithmetic require operations that yield safe upper and lower bounds of the exact result.
For example, for an addition, it is the operations +↑ and +↓ defined as: a +↓ b ≤ a + b ≤ a +↑ b.
Additionally it is desired that the width of the interval (a +↑ b) - (a +↓ b) would be about the machine epsilon after removing the exponent part.
Differently to the standard floating-point arithmetic, safe interval arithmetic is accurate (but still imprecise).
I.E.: the result of each defined operation contains (though does not identify) the exact mathematical outcome.
Usually a FPU's have machine +,-,*,/ operations accurate within the machine precision.
To illustrate it, let us consider a machine with decimal floating-point arithmetic that has the precision is 3 decimal points.
If the result of the machine addition is 1.23, then the exact mathematical result is within the interval ]1.22, 1.24[.
When the machine rounds towards zero, then the exact result is within [1.23,1.24[. This is the basis for an implementation of safe addition.
Task;
Show how +↓ and +↑ can be implemented in your language using the standard floating-point type.
Define an interval type based on the standard floating-point one, and implement an interval-valued addition of two floating-point numbers considering them exact, in short an operation that yields the interval [a +↓ b, a +↑ b].
|
#Wren
|
Wren
|
/* safe_addition.wren */
class Interval {
construct new(lower, upper) {
if (lower.type != Num || upper.type != Num) {
Fiber.abort("Arguments must be numbers.")
}
_lower = lower
_upper = upper
}
lower { _lower }
upper { _upper }
static stepAway(x) { new(nextAfter_(x, -1/0), nextAfter_(x, 1/0)) }
static safeAdd(x, y) { stepAway(x + y) }
foreign static nextAfter_(x, y) // the code for this is written in C
toString { "[%(_lower), %(_upper)]" }
}
var a = 1.2
var b = 0.03
System.print("(%(a) + %(b)) is in the range %(Interval.safeAdd(a,b))")
|
http://rosettacode.org/wiki/Ruth-Aaron_numbers
|
Ruth-Aaron numbers
|
A Ruth–Aaron pair consists of two consecutive integers (e.g., 714 and 715) for which the sums of the prime divisors of each integer are equal. So called because 714 is Babe Ruth's lifetime home run record; Hank Aaron's 715th home run broke this record and 714 and 715 have the same prime divisor sum.
A Ruth–Aaron triple consists of three consecutive integers with the same properties.
There is a second variant of Ruth–Aaron numbers, one which uses prime factors rather than prime divisors. The difference; divisors are unique, factors may be repeated. The 714, 715 pair appears in both, so the name still fits.
It is common to refer to each Ruth–Aaron group by the first number in it.
Task
Find and show, here on this page, the first 30 Ruth-Aaron numbers (factors).
Find and show, here on this page, the first 30 Ruth-Aaron numbers (divisors).
Stretch
Find and show the first Ruth-Aaron triple (factors).
Find and show the first Ruth-Aaron triple (divisors).
See also
Wikipedia: Ruth–Aaron pair
OEIS:A006145 - Ruth-Aaron numbers (1): sum of prime divisors of n = sum of prime divisors of n+1
OEIS:A039752 - Ruth-Aaron numbers (2): sum of prime divisors of n = sum of prime divisors of n+1 (both taken with multiplicity)
|
#Phix
|
Phix
|
with javascript_semantics
procedure ruth_aaron(bool d, integer n=30, l=2, i=1)
string fd = iff(d?"divisors":"factors"),
ns = iff(n=1?"":sprintf(" %d",n)),
ss = iff(n=1?"":"s"),
nt = iff(l=2?"number":"triple")
printf(1,"First%s Ruth-Aaron %s%s (%s):\n",{ns,nt,ss,fd})
integer prev = -1, k = i, c = 0
while n do
sequence f = prime_factors(k,true,-1)
if d then f = unique(f) end if
integer s = sum(f)
if s and s=prev then
c += 1
if c=l-1 then
printf(1,"%d ",k-c)
n -= 1
end if
else
c = 0
end if
prev = s
k += 1
end while
printf(1,"\n\n")
end procedure
atom t0 = time()
ruth_aaron(false) -- https://oeis.org/A039752
ruth_aaron(true) -- https://oeis.org/A006145
ruth_aaron(false, 1, 3) -- (2.1s)
-- give this one a little leg-up :-) ...
ruth_aaron(true, 1, 3, 89460000) -- (0.1s)
--ruth_aaron(true, 1, 3) -- (24 minutes 30s)
|
http://rosettacode.org/wiki/Search_a_list
|
Search a list
|
Task[edit]
Find the index of a string (needle) in an indexable, ordered collection of strings (haystack).
Raise an exception if the needle is missing.
If there is more than one occurrence then return the smallest index to the needle.
Extra credit
Return the largest index to a needle that has multiple occurrences in the haystack.
See also
Search a list of records
|
#AWK
|
AWK
|
#! /usr/bin/awk -f
BEGIN {
# create the array, using the word as index...
words="Zig Zag Wally Ronald Bush Krusty Charlie Bush Bozo";
split(words, haystack_byorder, " ");
j=0;
for(idx in haystack_byorder) {
haystack[haystack_byorder[idx]] = j;
j++;
}
# now check for needle (we know it is there, so no "else")...
if ( "Bush" in haystack ) {
print "Bush is at " haystack["Bush"];
}
# check for unexisting needle
if ( "Washington" in haystack ) {
print "impossible";
} else {
print "Washington is not here";
}
}
|
http://rosettacode.org/wiki/Runtime_evaluation
|
Runtime evaluation
|
Task
Demonstrate a language's ability for programs to execute code written in the language provided at runtime.
Show what kind of program fragments are permitted (e.g. expressions vs. statements), and how to get values in and out (e.g. environments, arguments, return values), if applicable what lexical/static environment the program is evaluated in, and what facilities for restricting (e.g. sandboxes, resource limits) or customizing (e.g. debugging facilities) the execution.
You may not invoke a separate evaluator program, or invoke a compiler and then its output, unless the interface of that program, and the syntax and means of executing it, are considered part of your language/library/platform.
For a more constrained task giving a specific program fragment to evaluate, see Eval in environment.
|
#Elena
|
Elena
|
import extensions'scripting;
public program()
{
lscript.interpret("system'console.writeLine(""Hello World"")");
}
|
http://rosettacode.org/wiki/Runtime_evaluation
|
Runtime evaluation
|
Task
Demonstrate a language's ability for programs to execute code written in the language provided at runtime.
Show what kind of program fragments are permitted (e.g. expressions vs. statements), and how to get values in and out (e.g. environments, arguments, return values), if applicable what lexical/static environment the program is evaluated in, and what facilities for restricting (e.g. sandboxes, resource limits) or customizing (e.g. debugging facilities) the execution.
You may not invoke a separate evaluator program, or invoke a compiler and then its output, unless the interface of that program, and the syntax and means of executing it, are considered part of your language/library/platform.
For a more constrained task giving a specific program fragment to evaluate, see Eval in environment.
|
#Elixir
|
Elixir
|
iex(1)> Code.eval_string("x + 4 * Enum.sum([1,2,3,4])", [x: 17])
{57, [x: 17]}
iex(2)> Code.eval_string("c = a + b", [a: 1, b: 2])
{3, [a: 1, b: 2, c: 3]}
iex(3)> Code.eval_string("a = a + b", [a: 1, b: 2])
{3, [a: 3, b: 2]}
|
http://rosettacode.org/wiki/Runtime_evaluation
|
Runtime evaluation
|
Task
Demonstrate a language's ability for programs to execute code written in the language provided at runtime.
Show what kind of program fragments are permitted (e.g. expressions vs. statements), and how to get values in and out (e.g. environments, arguments, return values), if applicable what lexical/static environment the program is evaluated in, and what facilities for restricting (e.g. sandboxes, resource limits) or customizing (e.g. debugging facilities) the execution.
You may not invoke a separate evaluator program, or invoke a compiler and then its output, unless the interface of that program, and the syntax and means of executing it, are considered part of your language/library/platform.
For a more constrained task giving a specific program fragment to evaluate, see Eval in environment.
|
#Erlang
|
Erlang
|
1> {ok, Tokens, _} = erl_scan:string("X + 4 * lists:sum([1,2,3,4]).").
...
2> {ok, [Form]} = erl_parse:parse_exprs(Tokens).
...
3> Bindings = erl_eval:add_binding('X', 17, erl_eval:new_bindings()).
[{'X',17}]
4> {value, Value, _} = erl_eval:expr(Form, Bindings).
{value,57,[{'X',17}]}
5> Value.
57
|
http://rosettacode.org/wiki/Safe_primes_and_unsafe_primes
|
Safe primes and unsafe primes
|
Definitions
A safe prime is a prime p and where (p-1)/2 is also prime.
The corresponding prime (p-1)/2 is known as a Sophie Germain prime.
An unsafe prime is a prime p and where (p-1)/2 isn't a prime.
An unsafe prime is a prime that isn't a safe prime.
Task
Find and display (on one line) the first 35 safe primes.
Find and display the count of the safe primes below 1,000,000.
Find and display the count of the safe primes below 10,000,000.
Find and display (on one line) the first 40 unsafe primes.
Find and display the count of the unsafe primes below 1,000,000.
Find and display the count of the unsafe primes below 10,000,000.
(Optional) display the counts and "below numbers" with commas.
Show all output here.
Related Task
strong and weak primes.
Also see
The OEIS article: safe primes.
The OEIS article: unsafe primes.
|
#jq
|
jq
|
def is_prime:
. as $n
| if ($n < 2) then false
elif ($n % 2 == 0) then $n == 2
elif ($n % 3 == 0) then $n == 3
elif ($n % 5 == 0) then $n == 5
elif ($n % 7 == 0) then $n == 7
elif ($n % 11 == 0) then $n == 11
elif ($n % 13 == 0) then $n == 13
elif ($n % 17 == 0) then $n == 17
elif ($n % 19 == 0) then $n == 19
elif ($n % 23 == 0) then $n == 23
elif ($n % 29 == 0) then $n == 29
elif ($n % 31 == 0) then $n == 31
else 37
| until( (. * .) > $n or ($n % . == 0); . + 2)
| . * . > $n
end;
def task:
# a helper function for keeping count:
def record($p; counter6; counter7):
if $p < 10000000
then counter7 += 1
| if $p < 1000000
then counter6 += 1
else .
end
else .
end;
# a helper function for recording up to $max values
def recordValues($max; $p; a; done):
if done then .
elif a|length < $max
then a += [$p] | done = ($max == (a|length))
else .
end;
10000000 as $n
| reduce (2, range(3;$n;2)) as $p ({};
if $p|is_prime
then if (($p - 1) / 2) | is_prime
then recordValues(35; $p; .safeprimes; .safedone)
| record($p; .nsafeprimes6; .nsafeprimes7)
else recordValues(40; $p; .unsafeprimes; .unsafedone)
| record($p; .nunsafeprimes6; .nunsafeprimes7)
end
else .
end )
| "The first 35 safe primes are: ", .safeprimes[0:35],
"\nThere are \(.nsafeprimes6) safe primes less than 1 million.",
"\nThere are \(.nsafeprimes7) safe primes less than 10 million.",
"",
"\nThe first 40 unsafe primes are:", .unsafeprimes[0:40],
"\nThere are \(.nunsafeprimes6) unsafe primes less than 1 million.",
"\nThere are \(.nunsafeprimes7) unsafe primes less than 10 million."
;
task
|
http://rosettacode.org/wiki/Safe_primes_and_unsafe_primes
|
Safe primes and unsafe primes
|
Definitions
A safe prime is a prime p and where (p-1)/2 is also prime.
The corresponding prime (p-1)/2 is known as a Sophie Germain prime.
An unsafe prime is a prime p and where (p-1)/2 isn't a prime.
An unsafe prime is a prime that isn't a safe prime.
Task
Find and display (on one line) the first 35 safe primes.
Find and display the count of the safe primes below 1,000,000.
Find and display the count of the safe primes below 10,000,000.
Find and display (on one line) the first 40 unsafe primes.
Find and display the count of the unsafe primes below 1,000,000.
Find and display the count of the unsafe primes below 10,000,000.
(Optional) display the counts and "below numbers" with commas.
Show all output here.
Related Task
strong and weak primes.
Also see
The OEIS article: safe primes.
The OEIS article: unsafe primes.
|
#Julia
|
Julia
|
using Primes, Formatting
function parseprimelist()
primelist = primes(2, 10000000)
safeprimes = Vector{Int64}()
unsafeprimes = Vector{Int64}()
for p in primelist
if isprime(div(p - 1, 2))
push!(safeprimes, p)
else
push!(unsafeprimes, p)
end
end
println("The first 35 unsafe primes are: ", safeprimes[1:35])
println("There are ", format(sum(map(x -> x < 1000000, safeprimes)), commas=true), " safe primes less than 1 million.")
println("There are ", format(length(safeprimes), commas=true), " safe primes less than 10 million.")
println("The first 40 unsafe primes are: ", unsafeprimes[1:40])
println("There are ", format(sum(map(x -> x < 1000000, unsafeprimes)), commas=true), " unsafe primes less than 1 million.")
println("There are ", format(length(unsafeprimes), commas=true), " unsafe primes less than 10 million.")
end
parseprimelist()
|
http://rosettacode.org/wiki/Same_fringe
|
Same fringe
|
Write a routine that will compare the leaves ("fringe") of two binary trees to determine whether they are the same list of leaves when visited left-to-right. The structure or balance of the trees does not matter; only the number, order, and value of the leaves is important.
Any solution is allowed here, but many computer scientists will consider it inelegant to collect either fringe in its entirety before starting to collect the other one. In fact, this problem is usually proposed in various forums as a way to show off various forms of concurrency (tree-rotation algorithms have also been used to get around the need to collect one tree first). Thinking of it a slightly different way, an elegant solution is one that can perform the minimum amount of work to falsify the equivalence of the fringes when they differ somewhere in the middle, short-circuiting the unnecessary additional traversals and comparisons.
Any representation of a binary tree is allowed, as long as the nodes are orderable, and only downward links are used (for example, you may not use parent or sibling pointers to avoid recursion).
|
#Racket
|
Racket
|
#lang racket
(module same-fringe lazy
(provide same-fringe?)
(define (same-fringe? t1 t2)
(! (equal? (flatten t1) (flatten t2))))
(define (flatten tree)
(if (list? tree)
(apply append (map flatten tree))
(list tree))))
(require 'same-fringe)
(module+ test
(require rackunit)
(check-true (same-fringe? '((1 2 3) ((4 5 6) (7 8)))
'(((1 2 3) (4 5 6)) (7 8))))
(check-false (same-fringe? '((1 2 3) ((4 5 6) (7 8)))
'(((1 2 3) (4 6)) (8)))))
|
http://rosettacode.org/wiki/Same_fringe
|
Same fringe
|
Write a routine that will compare the leaves ("fringe") of two binary trees to determine whether they are the same list of leaves when visited left-to-right. The structure or balance of the trees does not matter; only the number, order, and value of the leaves is important.
Any solution is allowed here, but many computer scientists will consider it inelegant to collect either fringe in its entirety before starting to collect the other one. In fact, this problem is usually proposed in various forums as a way to show off various forms of concurrency (tree-rotation algorithms have also been used to get around the need to collect one tree first). Thinking of it a slightly different way, an elegant solution is one that can perform the minimum amount of work to falsify the equivalence of the fringes when they differ somewhere in the middle, short-circuiting the unnecessary additional traversals and comparisons.
Any representation of a binary tree is allowed, as long as the nodes are orderable, and only downward links are used (for example, you may not use parent or sibling pointers to avoid recursion).
|
#Raku
|
Raku
|
sub fringe ($tree) {
multi sub fringey (Pair $node) { fringey $_ for $node.kv; }
multi sub fringey ( Any $leaf) { take $leaf; }
gather fringey $tree;
}
sub samefringe ($a, $b) { fringe($a) eqv fringe($b) }
# Testing:
my $a = 1 => 2 => 3 => 4 => 5 => 6 => 7 => 8;
my $b = 1 => (( 2 => 3 ) => (4 => (5 => ((6 => 7) => 8))));
my $c = (((1 => 2) => 3) => 4) => 5 => 6 => 7 => 8;
my $x = 1 => 2 => 3 => 4 => 5 => 6 => 7 => 8 => 9;
my $y = 0 => 2 => 3 => 4 => 5 => 6 => 7 => 8;
my $z = 1 => 2 => (4 => 3) => 5 => 6 => 7 => 8;
say so samefringe $a, $a;
say so samefringe $a, $b;
say so samefringe $a, $c;
say not samefringe $a, $x;
say not samefringe $a, $y;
say not samefringe $a, $z;
|
http://rosettacode.org/wiki/Sieve_of_Eratosthenes
|
Sieve of Eratosthenes
|
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task.
The Sieve of Eratosthenes is a simple algorithm that finds the prime numbers up to a given integer.
Task
Implement the Sieve of Eratosthenes algorithm, with the only allowed optimization that the outer loop can stop at the square root of the limit, and the inner loop may start at the square of the prime just found.
That means especially that you shouldn't optimize by using pre-computed wheels, i.e. don't assume you need only to cross out odd numbers (wheel based on 2), numbers equal to 1 or 5 modulo 6 (wheel based on 2 and 3), or similar wheels based on low primes.
If there's an easy way to add such a wheel based optimization, implement it as an alternative version.
Note
It is important that the sieve algorithm be the actual algorithm used to find prime numbers for the task.
Related tasks
Emirp primes
count in factors
prime decomposition
factors of an integer
extensible prime generator
primality by trial division
factors of a Mersenne number
trial factoring of a Mersenne number
partition an integer X into N primes
sequence of primes by Trial Division
|
#Nial
|
Nial
|
primes is sublist [ each (2 = sum eachright (0 = mod) [pass,count]), pass ] rest count
|
http://rosettacode.org/wiki/Sailors,_coconuts_and_a_monkey_problem
|
Sailors, coconuts and a monkey problem
|
Five sailors are shipwrecked on an island and collect a large pile of coconuts during the day.
That night the first sailor wakes up and decides to take his first share early so tries to divide the pile of coconuts equally into five piles but finds that there is one coconut left over, so he tosses it to a monkey and then hides "his" one of the five equally sized piles of coconuts and pushes the other four piles together to form a single visible pile of coconuts again and goes to bed.
To cut a long story short, each of the sailors in turn gets up once during the night and performs the same actions of dividing the coconut pile into five, finding that one coconut is left over and giving that single remainder coconut to the monkey.
In the morning (after the surreptitious and separate action of each of the five sailors during the night), the remaining coconuts are divided into five equal piles for each of the sailors, whereupon it is found that the pile of coconuts divides equally amongst the sailors with no remainder. (Nothing for the monkey in the morning.)
The task
Calculate the minimum possible size of the initial pile of coconuts collected during the first day.
Use a method that assumes an answer is possible, and then applies the constraints of the tale to see if it is correct. (I.e. no applying some formula that generates the correct answer without integer divisions and remainders and tests on remainders; but constraint solvers are allowed.)
Calculate the size of the initial pile of coconuts if six sailors were marooned and went through a similar process (but split into six piles instead of five of course).
Show your answers here.
Extra credit (optional)
Give some indication of the number of coconuts each sailor hides during the night.
Note
Of course the tale is told in a world where the collection of any amount of coconuts in a day and multiple divisions of the pile, etc can occur in time fitting the story line, so as not to affect the mathematics.
The tale is also told in a version where the monkey also gets a coconut in the morning. This is not that tale!
C.f
Monkeys and Coconuts - Numberphile (Video) Analytical solution.
A002021: Pile of coconuts problem The On-Line Encyclopedia of Integer Sequences. (Although some of its references may use the alternate form of the tale).
|
#REXX
|
REXX
|
/*REXX program solves a riddle of 5 sailors, a pile of coconuts, and a monkey. */
parse arg L H .; if L=='' then L= 5 /*L not specified? Then use default.*/
if H=='' then H= 6 /*H " " " " default.*/
/*{Tars is an old name for sailors.} */
do n=L to H /*traipse through a number of sailors. */
do $=0 while \valid(n, $) /*perform while not valid coconuts. */
end /*$*/
say 'sailors='n " coconuts="$ /*display number of sailors & coconuts.*/
end /*n*/
exit 0 /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
valid: procedure; parse arg n,nuts /*obtain the number sailors & coconuts.*/
do k=n by -1 for n /*step through the possibilities. */
if nuts//n \== 1 then return 0 /*Not one coconut left? No solution. */
nuts=nuts - (1 + nuts % n) /*subtract number of coconuts from pile*/
end /*k*/
return (nuts \== 0) & \(nuts//n \== 0) /*see if number coconuts>0 & remainder.*/
|
http://rosettacode.org/wiki/Sailors,_coconuts_and_a_monkey_problem
|
Sailors, coconuts and a monkey problem
|
Five sailors are shipwrecked on an island and collect a large pile of coconuts during the day.
That night the first sailor wakes up and decides to take his first share early so tries to divide the pile of coconuts equally into five piles but finds that there is one coconut left over, so he tosses it to a monkey and then hides "his" one of the five equally sized piles of coconuts and pushes the other four piles together to form a single visible pile of coconuts again and goes to bed.
To cut a long story short, each of the sailors in turn gets up once during the night and performs the same actions of dividing the coconut pile into five, finding that one coconut is left over and giving that single remainder coconut to the monkey.
In the morning (after the surreptitious and separate action of each of the five sailors during the night), the remaining coconuts are divided into five equal piles for each of the sailors, whereupon it is found that the pile of coconuts divides equally amongst the sailors with no remainder. (Nothing for the monkey in the morning.)
The task
Calculate the minimum possible size of the initial pile of coconuts collected during the first day.
Use a method that assumes an answer is possible, and then applies the constraints of the tale to see if it is correct. (I.e. no applying some formula that generates the correct answer without integer divisions and remainders and tests on remainders; but constraint solvers are allowed.)
Calculate the size of the initial pile of coconuts if six sailors were marooned and went through a similar process (but split into six piles instead of five of course).
Show your answers here.
Extra credit (optional)
Give some indication of the number of coconuts each sailor hides during the night.
Note
Of course the tale is told in a world where the collection of any amount of coconuts in a day and multiple divisions of the pile, etc can occur in time fitting the story line, so as not to affect the mathematics.
The tale is also told in a version where the monkey also gets a coconut in the morning. This is not that tale!
C.f
Monkeys and Coconuts - Numberphile (Video) Analytical solution.
A002021: Pile of coconuts problem The On-Line Encyclopedia of Integer Sequences. (Although some of its references may use the alternate form of the tale).
|
#Ring
|
Ring
|
# Project : Sailors, coconuts and a monkey problem
scm(5)
scm(6)
func scm(sailors)
sm1 = sailors-1
if sm1 = 0
m = sailors
else
for n=sailors to 1000000000 step sailors
m = n
for j=1 to sailors
if m % sm1 != 0
m = 0
exit
ok
m = sailors*m/sm1+1
next
if m != 0
exit
ok
next
ok
see "Solution with " + sailors + " sailors: " + m + nl
for i=1 to sailors
m = m - 1
m = m / sailors
see "Sailor " + i + " takes " + m + " giving 1 to the monkey and leaving " + m*sm1 + nl
m = m * sm1
next
see "In the morning each sailor gets " + m/sailors + " nuts" + nl + nl
|
http://rosettacode.org/wiki/Search_a_list_of_records
|
Search a list of records
|
Many programming languages provide convenient ways to look for a known value in a simple list of strings or numbers.
But what if the elements of the list are themselves compound records/objects/data-structures, and the search condition is more complex than a simple equality test?
Task[edit]
Write a function/method/etc. that can find the first element in a given list matching a given condition.
It should be as generic and reusable as possible.
(Of course if your programming language already provides such a feature, you can use that instead of recreating it.)
Then to demonstrate its functionality, create the data structure specified under #Data set, and perform on it the searches specified under #Test cases.
Data set
The data structure to be used contains the names and populations (in millions) of the 10 largest metropolitan areas in Africa, and looks as follows when represented in JSON:
[
{ "name": "Lagos", "population": 21.0 },
{ "name": "Cairo", "population": 15.2 },
{ "name": "Kinshasa-Brazzaville", "population": 11.3 },
{ "name": "Greater Johannesburg", "population": 7.55 },
{ "name": "Mogadishu", "population": 5.85 },
{ "name": "Khartoum-Omdurman", "population": 4.98 },
{ "name": "Dar Es Salaam", "population": 4.7 },
{ "name": "Alexandria", "population": 4.58 },
{ "name": "Abidjan", "population": 4.4 },
{ "name": "Casablanca", "population": 3.98 }
]
However, you shouldn't parse it from JSON, but rather represent it natively in your programming language.
The top-level data structure should be an ordered collection (i.e. a list, array, vector, or similar).
Each element in this list should be an associative collection that maps from keys to values (i.e. a struct, object, hash map, dictionary, or similar).
Each of them has two entries: One string value with key "name", and one numeric value with key "population".
You may rely on the list being sorted by population count, as long as you explain this to readers.
If any of that is impossible or unreasonable in your programming language, then feel free to deviate, as long as you explain your reasons in a comment above your solution.
Test cases
Search
Expected result
Find the (zero-based) index of the first city in the list whose name is "Dar Es Salaam"
6
Find the name of the first city in this list whose population is less than 5 million
Khartoum-Omdurman
Find the population of the first city in this list whose name starts with the letter "A"
4.58
Guidance
If your programming language supports higher-order programming, then the most elegant way to implement the requested functionality in a generic and reusable way, might be to write a function (maybe called "find_index" or similar), that takes two arguments:
The list to search through.
A function/lambda/closure (the so-called "predicate"), which will be applied in turn to each element in the list, and whose boolean return value defines whether that element matches the search requirement.
If this is not the approach which would be most natural or idiomatic in your language, explain why, and show what is.
Related tasks
Search a list
|
#Julia
|
Julia
|
using DataFrames
dataset = DataFrame(name=["Lagos", "Cairo", "Kinshasa-Brazzaville", "Greater Johannesburg", "Mogadishu",
"Khartoum-Omdurman", "Dar Es Salaam", "Alexandria", "Abidjan", "Casablanca"],
population=[21.0, 15.2, 11.3, 7.55, 5.85, 4.98, 4.7, 4.58, 4.4, 3.98])
print("Find the (one-based) index of the first city in the list whose name is \"Dar Es Salaam\": ")
println(findfirst(dataset[:name], "Dar Es Salaam"))
print("Find the name of the first city in this list whose population is less than 5 million: ")
println(dataset[first(find(dataset[:population] .< 5)), :name])
print("Find the population of the first city in this list whose name starts with the letter \"A\": ")
println(dataset[first(find(startswith.(dataset[:name], 'A'))), :population])
|
http://rosettacode.org/wiki/Search_a_list_of_records
|
Search a list of records
|
Many programming languages provide convenient ways to look for a known value in a simple list of strings or numbers.
But what if the elements of the list are themselves compound records/objects/data-structures, and the search condition is more complex than a simple equality test?
Task[edit]
Write a function/method/etc. that can find the first element in a given list matching a given condition.
It should be as generic and reusable as possible.
(Of course if your programming language already provides such a feature, you can use that instead of recreating it.)
Then to demonstrate its functionality, create the data structure specified under #Data set, and perform on it the searches specified under #Test cases.
Data set
The data structure to be used contains the names and populations (in millions) of the 10 largest metropolitan areas in Africa, and looks as follows when represented in JSON:
[
{ "name": "Lagos", "population": 21.0 },
{ "name": "Cairo", "population": 15.2 },
{ "name": "Kinshasa-Brazzaville", "population": 11.3 },
{ "name": "Greater Johannesburg", "population": 7.55 },
{ "name": "Mogadishu", "population": 5.85 },
{ "name": "Khartoum-Omdurman", "population": 4.98 },
{ "name": "Dar Es Salaam", "population": 4.7 },
{ "name": "Alexandria", "population": 4.58 },
{ "name": "Abidjan", "population": 4.4 },
{ "name": "Casablanca", "population": 3.98 }
]
However, you shouldn't parse it from JSON, but rather represent it natively in your programming language.
The top-level data structure should be an ordered collection (i.e. a list, array, vector, or similar).
Each element in this list should be an associative collection that maps from keys to values (i.e. a struct, object, hash map, dictionary, or similar).
Each of them has two entries: One string value with key "name", and one numeric value with key "population".
You may rely on the list being sorted by population count, as long as you explain this to readers.
If any of that is impossible or unreasonable in your programming language, then feel free to deviate, as long as you explain your reasons in a comment above your solution.
Test cases
Search
Expected result
Find the (zero-based) index of the first city in the list whose name is "Dar Es Salaam"
6
Find the name of the first city in this list whose population is less than 5 million
Khartoum-Omdurman
Find the population of the first city in this list whose name starts with the letter "A"
4.58
Guidance
If your programming language supports higher-order programming, then the most elegant way to implement the requested functionality in a generic and reusable way, might be to write a function (maybe called "find_index" or similar), that takes two arguments:
The list to search through.
A function/lambda/closure (the so-called "predicate"), which will be applied in turn to each element in the list, and whose boolean return value defines whether that element matches the search requirement.
If this is not the approach which would be most natural or idiomatic in your language, explain why, and show what is.
Related tasks
Search a list
|
#Kotlin
|
Kotlin
|
// version 1.1.2
class City(val name: String, val pop: Double)
val cities = listOf(
City("Lagos", 21.0),
City("Cairo", 15.2),
City("Kinshasa-Brazzaville", 11.3),
City("Greater Johannesburg", 7.55),
City("Mogadishu", 5.85),
City("Khartoum-Omdurman", 4.98),
City("Dar Es Salaam", 4.7),
City("Alexandria", 4.58),
City("Abidjan", 4.4),
City("Casablanca", 3.98)
)
fun main(args: Array<String>) {
val index = cities.indexOfFirst { it.name == "Dar Es Salaam" }
println("Index of first city whose name is 'Dar Es Salaam' = $index")
val name = cities.first { it.pop < 5.0 }.name
println("Name of first city whose population is less than 5 million = $name")
val pop = cities.first { it.name[0] == 'A' }.pop
println("Population of first city whose name starts with 'A' = $pop")
}
|
http://rosettacode.org/wiki/Ruth-Aaron_numbers
|
Ruth-Aaron numbers
|
A Ruth–Aaron pair consists of two consecutive integers (e.g., 714 and 715) for which the sums of the prime divisors of each integer are equal. So called because 714 is Babe Ruth's lifetime home run record; Hank Aaron's 715th home run broke this record and 714 and 715 have the same prime divisor sum.
A Ruth–Aaron triple consists of three consecutive integers with the same properties.
There is a second variant of Ruth–Aaron numbers, one which uses prime factors rather than prime divisors. The difference; divisors are unique, factors may be repeated. The 714, 715 pair appears in both, so the name still fits.
It is common to refer to each Ruth–Aaron group by the first number in it.
Task
Find and show, here on this page, the first 30 Ruth-Aaron numbers (factors).
Find and show, here on this page, the first 30 Ruth-Aaron numbers (divisors).
Stretch
Find and show the first Ruth-Aaron triple (factors).
Find and show the first Ruth-Aaron triple (divisors).
See also
Wikipedia: Ruth–Aaron pair
OEIS:A006145 - Ruth-Aaron numbers (1): sum of prime divisors of n = sum of prime divisors of n+1
OEIS:A039752 - Ruth-Aaron numbers (2): sum of prime divisors of n = sum of prime divisors of n+1 (both taken with multiplicity)
|
#Quackery
|
Quackery
|
[ behead dup dip nested rot
witheach
[ tuck != if
[ dup dip
[ nested join ] ] ]
drop ] is -duplicates ( [ --> [ )
[ primefactors -duplicates ] is primedivisors ( n --> n )
[ 0 swap witheach + ] is sum ( [ --> n )
[ [] temp put
3 2 primefactors sum
[ over primefactors sum
tuck = if
[ over 1 -
temp take
swap join
temp put ]
dip 1+
temp share size 30 = until ]
2drop
temp take ] is raf ( --> )
[ [] temp put
3 2 primedivisors sum
[ over primedivisors sum
tuck = if
[ over 1 -
temp take
swap join
temp put ]
dip 1+
temp share size 30 = until ]
2drop
temp take ] is rad ( --> )
raf echo
cr cr
rad echo
|
http://rosettacode.org/wiki/Ruth-Aaron_numbers
|
Ruth-Aaron numbers
|
A Ruth–Aaron pair consists of two consecutive integers (e.g., 714 and 715) for which the sums of the prime divisors of each integer are equal. So called because 714 is Babe Ruth's lifetime home run record; Hank Aaron's 715th home run broke this record and 714 and 715 have the same prime divisor sum.
A Ruth–Aaron triple consists of three consecutive integers with the same properties.
There is a second variant of Ruth–Aaron numbers, one which uses prime factors rather than prime divisors. The difference; divisors are unique, factors may be repeated. The 714, 715 pair appears in both, so the name still fits.
It is common to refer to each Ruth–Aaron group by the first number in it.
Task
Find and show, here on this page, the first 30 Ruth-Aaron numbers (factors).
Find and show, here on this page, the first 30 Ruth-Aaron numbers (divisors).
Stretch
Find and show the first Ruth-Aaron triple (factors).
Find and show the first Ruth-Aaron triple (divisors).
See also
Wikipedia: Ruth–Aaron pair
OEIS:A006145 - Ruth-Aaron numbers (1): sum of prime divisors of n = sum of prime divisors of n+1
OEIS:A039752 - Ruth-Aaron numbers (2): sum of prime divisors of n = sum of prime divisors of n+1 (both taken with multiplicity)
|
#Raku
|
Raku
|
use Prime::Factor;
my @pf = lazy (^∞).hyper(:1000batch).map: *.&prime-factors.sum;
my @upf = lazy (^∞).hyper(:1000batch).map: *.&prime-factors.unique.sum;
# Task: < 1 second
put "First 30 Ruth-Aaron numbers (Factors):\n" ~
(1..∞).grep( { @pf[$_] == @pf[$_ + 1] } )[^30];
put "\nFirst 30 Ruth-Aaron numbers (Divisors):\n" ~
(1..∞).grep( { @upf[$_] == @upf[$_ + 1] } )[^30];
# Stretch: ~ 5 seconds
put "\nFirst Ruth-Aaron triple (Factors):\n" ~
(1..∞).first: { @pf[$_] == @pf[$_ + 1] == @pf[$_ + 2] }
# Really, really, _really_ slow. 186(!) minutes... but with no cheating or "leg up".
put "\nFirst Ruth-Aaron triple (Divisors):\n" ~
(1..∞).first: { @upf[$_] == @upf[$_ + 1] == @upf[$_ + 2] }
|
http://rosettacode.org/wiki/Search_a_list
|
Search a list
|
Task[edit]
Find the index of a string (needle) in an indexable, ordered collection of strings (haystack).
Raise an exception if the needle is missing.
If there is more than one occurrence then return the smallest index to the needle.
Extra credit
Return the largest index to a needle that has multiple occurrences in the haystack.
See also
Search a list of records
|
#BASIC
|
BASIC
|
DATA foo, bar, baz, quux, quuux, quuuux, bazola, ztesch, foo, bar, thud, grunt
DATA foo, bar, bletch, foo, bar, fum, fred, jim, sheila, barney, flarp, zxc
DATA spqr, wombat, shme, foo, bar, baz, bongo, spam, eggs, snork, foo, bar
DATA zot, blarg, wibble, toto, titi, tata, tutu, pippo, pluto, paperino, aap
DATA noot, mies, oogle, foogle, boogle, zork, gork, bork
DIM haystack(54) AS STRING
DIM needle AS STRING, found AS INTEGER, L0 AS INTEGER
FOR L0 = 0 TO 54
READ haystack(L0)
NEXT
DO
INPUT "Word to search for? (Leave blank to exit) ", needle
IF needle <> "" THEN
FOR L0 = 0 TO UBOUND(haystack)
IF UCASE$(haystack(L0)) = UCASE$(needle) THEN
found = 1
PRINT "Found "; CHR$(34); needle; CHR$(34); " at index "; LTRIM$(STR$(L0))
END IF
NEXT
IF found < 1 THEN
PRINT CHR$(34); needle; CHR$(34); " not found"
END IF
ELSE
EXIT DO
END IF
LOOP
|
http://rosettacode.org/wiki/Runtime_evaluation
|
Runtime evaluation
|
Task
Demonstrate a language's ability for programs to execute code written in the language provided at runtime.
Show what kind of program fragments are permitted (e.g. expressions vs. statements), and how to get values in and out (e.g. environments, arguments, return values), if applicable what lexical/static environment the program is evaluated in, and what facilities for restricting (e.g. sandboxes, resource limits) or customizing (e.g. debugging facilities) the execution.
You may not invoke a separate evaluator program, or invoke a compiler and then its output, unless the interface of that program, and the syntax and means of executing it, are considered part of your language/library/platform.
For a more constrained task giving a specific program fragment to evaluate, see Eval in environment.
|
#Factor
|
Factor
|
IN: scratchpad "\"Hello, World!\" print" ( -- ) eval
Hello, World!
IN: scratchpad 4 5 "+" ( a b -- c ) eval
9
|
http://rosettacode.org/wiki/Runtime_evaluation
|
Runtime evaluation
|
Task
Demonstrate a language's ability for programs to execute code written in the language provided at runtime.
Show what kind of program fragments are permitted (e.g. expressions vs. statements), and how to get values in and out (e.g. environments, arguments, return values), if applicable what lexical/static environment the program is evaluated in, and what facilities for restricting (e.g. sandboxes, resource limits) or customizing (e.g. debugging facilities) the execution.
You may not invoke a separate evaluator program, or invoke a compiler and then its output, unless the interface of that program, and the syntax and means of executing it, are considered part of your language/library/platform.
For a more constrained task giving a specific program fragment to evaluate, see Eval in environment.
|
#Forth
|
Forth
|
s" variable foo 1e fatan 4e f*" evaluate
f. \ 3.14159...
1 foo !
|
http://rosettacode.org/wiki/Runtime_evaluation
|
Runtime evaluation
|
Task
Demonstrate a language's ability for programs to execute code written in the language provided at runtime.
Show what kind of program fragments are permitted (e.g. expressions vs. statements), and how to get values in and out (e.g. environments, arguments, return values), if applicable what lexical/static environment the program is evaluated in, and what facilities for restricting (e.g. sandboxes, resource limits) or customizing (e.g. debugging facilities) the execution.
You may not invoke a separate evaluator program, or invoke a compiler and then its output, unless the interface of that program, and the syntax and means of executing it, are considered part of your language/library/platform.
For a more constrained task giving a specific program fragment to evaluate, see Eval in environment.
|
#Frink
|
Frink
|
eval["length = 1234 feet + 2 inches"]
|
http://rosettacode.org/wiki/Safe_primes_and_unsafe_primes
|
Safe primes and unsafe primes
|
Definitions
A safe prime is a prime p and where (p-1)/2 is also prime.
The corresponding prime (p-1)/2 is known as a Sophie Germain prime.
An unsafe prime is a prime p and where (p-1)/2 isn't a prime.
An unsafe prime is a prime that isn't a safe prime.
Task
Find and display (on one line) the first 35 safe primes.
Find and display the count of the safe primes below 1,000,000.
Find and display the count of the safe primes below 10,000,000.
Find and display (on one line) the first 40 unsafe primes.
Find and display the count of the unsafe primes below 1,000,000.
Find and display the count of the unsafe primes below 10,000,000.
(Optional) display the counts and "below numbers" with commas.
Show all output here.
Related Task
strong and weak primes.
Also see
The OEIS article: safe primes.
The OEIS article: unsafe primes.
|
#Kotlin
|
Kotlin
|
// Version 1.2.70
fun sieve(limit: Int): BooleanArray {
// True denotes composite, false denotes prime.
val c = BooleanArray(limit + 1) // all false by default
c[0] = true
c[1] = true
// apart from 2 all even numbers are of course composite
for (i in 4..limit step 2) c[i] = true
var p = 3 // start from 3
while (true) {
val p2 = p * p
if (p2 > limit) break
for (i in p2..limit step 2 * p) c[i] = true
while (true) {
p += 2
if (!c[p]) break
}
}
return c
}
fun main(args: Array<String>) {
// sieve up to 10 million
val sieved = sieve(10_000_000)
val safe = IntArray(35)
var count = 0
var i = 3
while (count < 35) {
if (!sieved[i] && !sieved[(i - 1) / 2]) safe[count++] = i
i += 2
}
println("The first 35 safe primes are:")
println(safe.joinToString(" ","[", "]\n"))
count = 0
for (j in 3 until 1_000_000 step 2) {
if (!sieved[j] && !sieved[(j - 1) / 2]) count++
}
System.out.printf("The number of safe primes below 1,000,000 is %,d\n\n", count)
for (j in 1_000_001 until 10_000_000 step 2) {
if (!sieved[j] && !sieved[(j - 1) / 2]) count++
}
System.out.printf("The number of safe primes below 10,000,000 is %,d\n\n", count)
val unsafe = IntArray(40)
unsafe[0] = 2 // since (2 - 1)/2 is not prime
count = 1
i = 3
while (count < 40) {
if (!sieved[i] && sieved[(i - 1) / 2]) unsafe[count++] = i
i += 2
}
println("The first 40 unsafe primes are:")
println(unsafe.joinToString(" ","[", "]\n"))
count = 1
for (j in 3 until 1_000_000 step 2) {
if (!sieved[j] && sieved[(j - 1) / 2]) count++
}
System.out.printf("The number of unsafe primes below 1,000,000 is %,d\n\n", count)
for (j in 1_000_001 until 10_000_000 step 2) {
if (!sieved[j] && sieved[(j - 1) / 2]) count++
}
System.out.printf("The number of unsafe primes below 10,000,000 is %,d\n\n", count)
}
|
http://rosettacode.org/wiki/Same_fringe
|
Same fringe
|
Write a routine that will compare the leaves ("fringe") of two binary trees to determine whether they are the same list of leaves when visited left-to-right. The structure or balance of the trees does not matter; only the number, order, and value of the leaves is important.
Any solution is allowed here, but many computer scientists will consider it inelegant to collect either fringe in its entirety before starting to collect the other one. In fact, this problem is usually proposed in various forums as a way to show off various forms of concurrency (tree-rotation algorithms have also been used to get around the need to collect one tree first). Thinking of it a slightly different way, an elegant solution is one that can perform the minimum amount of work to falsify the equivalence of the fringes when they differ somewhere in the middle, short-circuiting the unnecessary additional traversals and comparisons.
Any representation of a binary tree is allowed, as long as the nodes are orderable, and only downward links are used (for example, you may not use parent or sibling pointers to avoid recursion).
|
#REXX
|
REXX
|
/* REXX ***************************************************************
* Same Fringe
* 1 A A
* / \ / \ / \
* / \ / \ / \
* / \ / \ / \
* 2 3 B C B C
* / \ / / \ / / \ /
* 4 5 6 D E F D E F
* / / \ / / \ / / \
* 7 8 9 G H I G * I
*
* 23.08.2012 Walter Pachl derived from
* http://rosettacode.org/wiki/Tree_traversal
* Tree A: A B D G E C F H I
* Tree B: A B D G E C F * I
**********************************************************************/
debug=0
node.=0
lvl=0
Call mktree 'A'
Call mktree 'B'
done.=0
za=root.a; leafa=node.a.za.0name
zb=root.a; leafb=node.b.zb.0name
done.a.za=1
done.b.zb=1
Do i=1 To 12
if leafa=leafb Then Do
If leafa=0 Then Do
Say 'Fringes are equal'
Leave
End
Say leafa '=' leafb
Do j=1 To 12 Until done.a.za=0
za=go_next(za,'A'); leafa=node.a.za.0name
End
done.a.za=1
Do j=1 To 12 Until done.b.zb=0
zb=go_next(zb,'B'); leafb=node.b.zb.0name
End
done.b.zb=1
End
Else Do
Select
When leafa=0 Then
Say leafb 'exceeds leaves in tree A'
When leafb=0 Then
Say leafa 'exceeds leaves in tree B'
Otherwise
Say 'First difference' leafa '<>' leafb
End
Leave
End
End
Exit
note:
/**********************************************************************
* add the node to the preorder list unless it's already there
* add the node to the level list
**********************************************************************/
Parse Arg z,t
If z<>0 &, /* it's a node */
done.z=0 Then Do /* not yet done */
wl.t=wl.t z /* add it to the preorder list*/
ll.lvl=ll.lvl z /* add it to the level list */
done.z=1 /* remember it's done */
leafl=leafl node.t.z.0name
End
Return
go_next: Procedure Expose node. lvl
/**********************************************************************
* find the next node to visit in the treewalk
**********************************************************************/
next=0
Parse arg z,t
If node.t.z.0left<>0 Then Do /* there is a left son */
If node.t.z.0left.done=0 Then Do /* we have not visited it */
next=node.t.z.0left /* so we go there */
node.t.z.0left.done=1 /* note we were here */
lvl=lvl+1 /* increase the level */
End
End
If next=0 Then Do /* not moved yet */
If node.t.z.0rite<>0 Then Do /* there is a right son */
If node.t.z.0rite.done=0 Then Do /* we have not visited it */
next=node.t.z.0rite /* so we go there */
node.t.z.0rite.done=1 /* note we were here */
lvl=lvl+1 /* increase the level */
End
End
End
If next=0 Then Do /* not moved yet */
next=node.t.z.0father /* go to the father */
lvl=lvl-1 /* decrease the level */
End
Return next /* that's the next node */
/* or zero if we are done */
mknode: Procedure Expose node.
/**********************************************************************
* create a new node
**********************************************************************/
Parse Arg name,t
z=node.t.0+1
node.t.z.0name=name
node.t.z.0father=0
node.t.z.0left =0
node.t.z.0rite =0
node.t.0=z
Return z /* number of the node just created */
attleft: Procedure Expose node.
/**********************************************************************
* make son the left son of father
**********************************************************************/
Parse Arg son,father,t
node.t.son.0father=father
z=node.t.father.0left
If z<>0 Then Do
node.t.z.0father=son
node.t.son.0left=z
End
node.t.father.0left=son
Return
attrite: Procedure Expose node.
/**********************************************************************
* make son the right son of father
**********************************************************************/
Parse Arg son,father,t
node.t.son.0father=father
z=node.t.father.0rite
If z<>0 Then Do
node.t.z.0father=son
node.t.son.0rite=z
End
node.t.father.0rite=son
le=node.t.father.0left
If le>0 Then
node.t.le.0brother=node.t.father.0rite
Return
mktree: Procedure Expose node. root.
/**********************************************************************
* build the tree according to the task
**********************************************************************/
Parse Arg t
If t='A' Then Do
a=mknode('A',t); root.t=a
b=mknode('B',t); Call attleft b,a,t
c=mknode('C',t); Call attrite c,a,t
d=mknode('D',t); Call attleft d,b,t
e=mknode('E',t); Call attrite e,b,t
f=mknode('F',t); Call attleft f,c,t
g=mknode('G',t); Call attleft g,d,t
h=mknode('H',t); Call attleft h,f,t
i=mknode('I',t); Call attrite i,f,t
End
Else Do
a=mknode('A',t); root.t=a
b=mknode('B',t); Call attleft b,a,t
c=mknode('C',t); Call attrite c,a,t
d=mknode('D',t); Call attleft d,b,t
e=mknode('E',t); Call attrite e,b,t
f=mknode('F',t); Call attleft f,c,t
g=mknode('G',t); Call attleft g,d,t
h=mknode('*',t); Call attleft h,f,t
i=mknode('I',t); Call attrite i,f,t
End
Return
|
http://rosettacode.org/wiki/Sieve_of_Eratosthenes
|
Sieve of Eratosthenes
|
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task.
The Sieve of Eratosthenes is a simple algorithm that finds the prime numbers up to a given integer.
Task
Implement the Sieve of Eratosthenes algorithm, with the only allowed optimization that the outer loop can stop at the square root of the limit, and the inner loop may start at the square of the prime just found.
That means especially that you shouldn't optimize by using pre-computed wheels, i.e. don't assume you need only to cross out odd numbers (wheel based on 2), numbers equal to 1 or 5 modulo 6 (wheel based on 2 and 3), or similar wheels based on low primes.
If there's an easy way to add such a wheel based optimization, implement it as an alternative version.
Note
It is important that the sieve algorithm be the actual algorithm used to find prime numbers for the task.
Related tasks
Emirp primes
count in factors
prime decomposition
factors of an integer
extensible prime generator
primality by trial division
factors of a Mersenne number
trial factoring of a Mersenne number
partition an integer X into N primes
sequence of primes by Trial Division
|
#Nim
|
Nim
|
from math import sqrt
iterator primesUpto(limit: int): int =
let sqrtLimit = int(sqrt(float64(limit)))
var composites = newSeq[bool](limit + 1)
for n in 2 .. sqrtLimit: # cull to square root of limit
if not composites[n]: # if prime -> cull its composites
for c in countup(n * n, limit, n): # start at ``n`` squared
composites[c] = true
for n in 2 .. limit: # separate iteration over results
if not composites[n]:
yield n
stdout.write "The primes up to 100 are: "
for x in primesUpto(100):
stdout.write(x, " ")
echo()
var count = 0
for p in primesUpto(1000000):
count += 1
echo "There are ", count, " primes up to 1000000."
|
http://rosettacode.org/wiki/Sailors,_coconuts_and_a_monkey_problem
|
Sailors, coconuts and a monkey problem
|
Five sailors are shipwrecked on an island and collect a large pile of coconuts during the day.
That night the first sailor wakes up and decides to take his first share early so tries to divide the pile of coconuts equally into five piles but finds that there is one coconut left over, so he tosses it to a monkey and then hides "his" one of the five equally sized piles of coconuts and pushes the other four piles together to form a single visible pile of coconuts again and goes to bed.
To cut a long story short, each of the sailors in turn gets up once during the night and performs the same actions of dividing the coconut pile into five, finding that one coconut is left over and giving that single remainder coconut to the monkey.
In the morning (after the surreptitious and separate action of each of the five sailors during the night), the remaining coconuts are divided into five equal piles for each of the sailors, whereupon it is found that the pile of coconuts divides equally amongst the sailors with no remainder. (Nothing for the monkey in the morning.)
The task
Calculate the minimum possible size of the initial pile of coconuts collected during the first day.
Use a method that assumes an answer is possible, and then applies the constraints of the tale to see if it is correct. (I.e. no applying some formula that generates the correct answer without integer divisions and remainders and tests on remainders; but constraint solvers are allowed.)
Calculate the size of the initial pile of coconuts if six sailors were marooned and went through a similar process (but split into six piles instead of five of course).
Show your answers here.
Extra credit (optional)
Give some indication of the number of coconuts each sailor hides during the night.
Note
Of course the tale is told in a world where the collection of any amount of coconuts in a day and multiple divisions of the pile, etc can occur in time fitting the story line, so as not to affect the mathematics.
The tale is also told in a version where the monkey also gets a coconut in the morning. This is not that tale!
C.f
Monkeys and Coconuts - Numberphile (Video) Analytical solution.
A002021: Pile of coconuts problem The On-Line Encyclopedia of Integer Sequences. (Although some of its references may use the alternate form of the tale).
|
#Ruby
|
Ruby
|
def valid?(sailor, nuts)
sailor.times do
return false if (nuts % sailor) != 1
nuts -= 1 + nuts / sailor
end
nuts > 0 and nuts % sailor == 0
end
[5,6].each do |sailor|
n = sailor
n += 1 until valid?(sailor, n)
puts "\n#{sailor} sailors => #{n} coconuts"
(sailor+1).times do
div, mod = n.divmod(sailor)
puts " #{[n, div, mod]}"
n -= 1 + div
end
end
|
http://rosettacode.org/wiki/Sailors,_coconuts_and_a_monkey_problem
|
Sailors, coconuts and a monkey problem
|
Five sailors are shipwrecked on an island and collect a large pile of coconuts during the day.
That night the first sailor wakes up and decides to take his first share early so tries to divide the pile of coconuts equally into five piles but finds that there is one coconut left over, so he tosses it to a monkey and then hides "his" one of the five equally sized piles of coconuts and pushes the other four piles together to form a single visible pile of coconuts again and goes to bed.
To cut a long story short, each of the sailors in turn gets up once during the night and performs the same actions of dividing the coconut pile into five, finding that one coconut is left over and giving that single remainder coconut to the monkey.
In the morning (after the surreptitious and separate action of each of the five sailors during the night), the remaining coconuts are divided into five equal piles for each of the sailors, whereupon it is found that the pile of coconuts divides equally amongst the sailors with no remainder. (Nothing for the monkey in the morning.)
The task
Calculate the minimum possible size of the initial pile of coconuts collected during the first day.
Use a method that assumes an answer is possible, and then applies the constraints of the tale to see if it is correct. (I.e. no applying some formula that generates the correct answer without integer divisions and remainders and tests on remainders; but constraint solvers are allowed.)
Calculate the size of the initial pile of coconuts if six sailors were marooned and went through a similar process (but split into six piles instead of five of course).
Show your answers here.
Extra credit (optional)
Give some indication of the number of coconuts each sailor hides during the night.
Note
Of course the tale is told in a world where the collection of any amount of coconuts in a day and multiple divisions of the pile, etc can occur in time fitting the story line, so as not to affect the mathematics.
The tale is also told in a version where the monkey also gets a coconut in the morning. This is not that tale!
C.f
Monkeys and Coconuts - Numberphile (Video) Analytical solution.
A002021: Pile of coconuts problem The On-Line Encyclopedia of Integer Sequences. (Although some of its references may use the alternate form of the tale).
|
#Scala
|
Scala
|
object Sailors extends App {
var x = 0
private def valid(n: Int, _nuts: Int): Boolean = {
var nuts = _nuts
for (k <- n until 0 by -1) {
if (nuts % n != 1) return false
nuts -= 1 + nuts / n
}
nuts != 0 && (nuts % n == 0)
}
for (nSailors <- 2 until 10) {
while (!valid(nSailors, x)) x += 1
println(f"$nSailors%d: $x%d")
}
}
|
http://rosettacode.org/wiki/Search_a_list_of_records
|
Search a list of records
|
Many programming languages provide convenient ways to look for a known value in a simple list of strings or numbers.
But what if the elements of the list are themselves compound records/objects/data-structures, and the search condition is more complex than a simple equality test?
Task[edit]
Write a function/method/etc. that can find the first element in a given list matching a given condition.
It should be as generic and reusable as possible.
(Of course if your programming language already provides such a feature, you can use that instead of recreating it.)
Then to demonstrate its functionality, create the data structure specified under #Data set, and perform on it the searches specified under #Test cases.
Data set
The data structure to be used contains the names and populations (in millions) of the 10 largest metropolitan areas in Africa, and looks as follows when represented in JSON:
[
{ "name": "Lagos", "population": 21.0 },
{ "name": "Cairo", "population": 15.2 },
{ "name": "Kinshasa-Brazzaville", "population": 11.3 },
{ "name": "Greater Johannesburg", "population": 7.55 },
{ "name": "Mogadishu", "population": 5.85 },
{ "name": "Khartoum-Omdurman", "population": 4.98 },
{ "name": "Dar Es Salaam", "population": 4.7 },
{ "name": "Alexandria", "population": 4.58 },
{ "name": "Abidjan", "population": 4.4 },
{ "name": "Casablanca", "population": 3.98 }
]
However, you shouldn't parse it from JSON, but rather represent it natively in your programming language.
The top-level data structure should be an ordered collection (i.e. a list, array, vector, or similar).
Each element in this list should be an associative collection that maps from keys to values (i.e. a struct, object, hash map, dictionary, or similar).
Each of them has two entries: One string value with key "name", and one numeric value with key "population".
You may rely on the list being sorted by population count, as long as you explain this to readers.
If any of that is impossible or unreasonable in your programming language, then feel free to deviate, as long as you explain your reasons in a comment above your solution.
Test cases
Search
Expected result
Find the (zero-based) index of the first city in the list whose name is "Dar Es Salaam"
6
Find the name of the first city in this list whose population is less than 5 million
Khartoum-Omdurman
Find the population of the first city in this list whose name starts with the letter "A"
4.58
Guidance
If your programming language supports higher-order programming, then the most elegant way to implement the requested functionality in a generic and reusable way, might be to write a function (maybe called "find_index" or similar), that takes two arguments:
The list to search through.
A function/lambda/closure (the so-called "predicate"), which will be applied in turn to each element in the list, and whose boolean return value defines whether that element matches the search requirement.
If this is not the approach which would be most natural or idiomatic in your language, explain why, and show what is.
Related tasks
Search a list
|
#Lingo
|
Lingo
|
on findFirstRecord (data, condition)
cnt = data.count
repeat with i = 1 to cnt
record = data[i]
if value(condition) then return [#index:i-1, #record:record]
end repeat
end
|
http://rosettacode.org/wiki/Ruth-Aaron_numbers
|
Ruth-Aaron numbers
|
A Ruth–Aaron pair consists of two consecutive integers (e.g., 714 and 715) for which the sums of the prime divisors of each integer are equal. So called because 714 is Babe Ruth's lifetime home run record; Hank Aaron's 715th home run broke this record and 714 and 715 have the same prime divisor sum.
A Ruth–Aaron triple consists of three consecutive integers with the same properties.
There is a second variant of Ruth–Aaron numbers, one which uses prime factors rather than prime divisors. The difference; divisors are unique, factors may be repeated. The 714, 715 pair appears in both, so the name still fits.
It is common to refer to each Ruth–Aaron group by the first number in it.
Task
Find and show, here on this page, the first 30 Ruth-Aaron numbers (factors).
Find and show, here on this page, the first 30 Ruth-Aaron numbers (divisors).
Stretch
Find and show the first Ruth-Aaron triple (factors).
Find and show the first Ruth-Aaron triple (divisors).
See also
Wikipedia: Ruth–Aaron pair
OEIS:A006145 - Ruth-Aaron numbers (1): sum of prime divisors of n = sum of prime divisors of n+1
OEIS:A039752 - Ruth-Aaron numbers (2): sum of prime divisors of n = sum of prime divisors of n+1 (both taken with multiplicity)
|
#Sidef
|
Sidef
|
say "First 30 Ruth-Aaron numbers (factors):"
say 30.by {|n| (sopfr(n) == sopfr(n+1)) && (n > 0) }.join(' ')
say "\nFirst 30 Ruth-Aaron numbers (divisors):"
say 30.by {|n| ( sopf(n) == sopf(n+1)) && (n > 0) }.join(' ')
|
http://rosettacode.org/wiki/Ruth-Aaron_numbers
|
Ruth-Aaron numbers
|
A Ruth–Aaron pair consists of two consecutive integers (e.g., 714 and 715) for which the sums of the prime divisors of each integer are equal. So called because 714 is Babe Ruth's lifetime home run record; Hank Aaron's 715th home run broke this record and 714 and 715 have the same prime divisor sum.
A Ruth–Aaron triple consists of three consecutive integers with the same properties.
There is a second variant of Ruth–Aaron numbers, one which uses prime factors rather than prime divisors. The difference; divisors are unique, factors may be repeated. The 714, 715 pair appears in both, so the name still fits.
It is common to refer to each Ruth–Aaron group by the first number in it.
Task
Find and show, here on this page, the first 30 Ruth-Aaron numbers (factors).
Find and show, here on this page, the first 30 Ruth-Aaron numbers (divisors).
Stretch
Find and show the first Ruth-Aaron triple (factors).
Find and show the first Ruth-Aaron triple (divisors).
See also
Wikipedia: Ruth–Aaron pair
OEIS:A006145 - Ruth-Aaron numbers (1): sum of prime divisors of n = sum of prime divisors of n+1
OEIS:A039752 - Ruth-Aaron numbers (2): sum of prime divisors of n = sum of prime divisors of n+1 (both taken with multiplicity)
|
#Wren
|
Wren
|
import "./math" for Int, Nums
import "./seq" for Lst
import "./fmt" for Fmt
var resF = []
var resD = []
var resT = [] // factors only
var n = 2
var factors1 = []
var factors2 = [2]
var factors3 = [3]
var sum1 = 0
var sum2 = 2
var sum3 = 3
var countF = 0
var countD = 0
var countT = 0
while (countT < 1 || countD < 30 || countF < 30) {
factors1 = factors2
factors2 = factors3
factors3 = Int.primeFactors(n+2)
sum1 = sum2
sum2 = sum3
sum3 = Nums.sum(factors3)
if (countF < 30 && sum1 == sum2) {
resF.add(n)
countF = countF + 1
}
if (sum1 == sum2 && sum2 == sum3) {
resT.add(n)
countT = countT + 1
}
if (countD < 30) {
var factors4 = factors1.toList
var factors5 = factors2.toList
Lst.prune(factors4)
Lst.prune(factors5)
if (Nums.sum(factors4) == Nums.sum(factors5)) {
resD.add(n)
countD = countD + 1
}
}
n = n + 1
}
System.print("First 30 Ruth-Aaron numbers (factors):")
System.print(resF.join(" "))
System.print("\nFirst 30 Ruth-Aaron numbers (divisors):")
System.print(resD.join(" "))
System.print("\nFirst Ruth-Aaron triple (factors):")
System.print(resT[0])
resT = [] // divisors only
n = 2
factors1 = []
factors2 = [2]
factors3 = [3]
sum1 = 0
sum2 = 2
sum3 = 3
countT = 0
while (countT < 1) {
factors1 = factors2
factors2 = factors3
factors3 = Int.primeFactors(n+2)
Lst.prune(factors3)
sum1 = sum2
sum2 = sum3
sum3 = Nums.sum(factors3)
if (sum1 == sum2 && sum2 == sum3) {
resT.add(n)
countT = countT + 1
}
n = n + 1
}
System.print("\nFirst Ruth-Aaron triple (divisors):")
System.print(resT[0])
|
http://rosettacode.org/wiki/Search_a_list
|
Search a list
|
Task[edit]
Find the index of a string (needle) in an indexable, ordered collection of strings (haystack).
Raise an exception if the needle is missing.
If there is more than one occurrence then return the smallest index to the needle.
Extra credit
Return the largest index to a needle that has multiple occurrences in the haystack.
See also
Search a list of records
|
#Batch_File
|
Batch File
|
@echo off
setlocal enabledelayedexpansion
%==Sample list==%
set "data=foo, bar, baz, quux, quuux, quuuux, bazola, ztesch, foo, bar, thud, grunt"
set "data=%data% foo, bar, bletch, foo, bar, fum, fred, jim, sheila, barney, flarp, zxc"
set "data=%data% spqr, wombat, shme, foo, bar, baz, bongo, spam, eggs, snork, foo, bar"
set "data=%data% zot, blarg, wibble, toto, titi, tata, tutu, pippo, pluto, paperino, aap"
set "data=%data% noot, mies, oogle, foogle, boogle, zork, gork, bork"
%==Sample "needles" [whitespace is the delimiter]==%
set "needles=foo bar baz jim bong"
%==Counting and Seperating each Data==%
set datalen=0
for %%. in (!data!) do (
set /a datalen+=1
set data!datalen!=%%.
)
%==Do the search==%
for %%A in (!needles!) do (
set "first="
set "last="
set "found=0"
for /l %%B in (1,1,%datalen%) do (
if "!data%%B!" == "%%A" (
set /a found+=1
if !found! equ 1 set first=%%B
set last=%%B
)
)
if !found! equ 0 echo."%%A": Not found.
if !found! equ 1 echo."%%A": Found once in index [!first!].
if !found! gtr 1 echo."%%A": Found !found! times. First instance:[!first!] Last instance:[!last!].
)
%==We are done==%
echo.
pause
|
http://rosettacode.org/wiki/Runtime_evaluation
|
Runtime evaluation
|
Task
Demonstrate a language's ability for programs to execute code written in the language provided at runtime.
Show what kind of program fragments are permitted (e.g. expressions vs. statements), and how to get values in and out (e.g. environments, arguments, return values), if applicable what lexical/static environment the program is evaluated in, and what facilities for restricting (e.g. sandboxes, resource limits) or customizing (e.g. debugging facilities) the execution.
You may not invoke a separate evaluator program, or invoke a compiler and then its output, unless the interface of that program, and the syntax and means of executing it, are considered part of your language/library/platform.
For a more constrained task giving a specific program fragment to evaluate, see Eval in environment.
|
#Go
|
Go
|
package main
import (
"fmt"
"bitbucket.org/binet/go-eval/pkg/eval"
"go/token"
)
func main() {
w := eval.NewWorld();
fset := token.NewFileSet();
code, err := w.Compile(fset, "1 + 2")
if err != nil {
fmt.Println("Compile error");
return
}
val, err := code.Run();
if err != nil {
fmt.Println("Run time error");
return;
}
fmt.Println("Return value:", val) //prints, well, 3
}
|
http://rosettacode.org/wiki/Runtime_evaluation
|
Runtime evaluation
|
Task
Demonstrate a language's ability for programs to execute code written in the language provided at runtime.
Show what kind of program fragments are permitted (e.g. expressions vs. statements), and how to get values in and out (e.g. environments, arguments, return values), if applicable what lexical/static environment the program is evaluated in, and what facilities for restricting (e.g. sandboxes, resource limits) or customizing (e.g. debugging facilities) the execution.
You may not invoke a separate evaluator program, or invoke a compiler and then its output, unless the interface of that program, and the syntax and means of executing it, are considered part of your language/library/platform.
For a more constrained task giving a specific program fragment to evaluate, see Eval in environment.
|
#Groovy
|
Groovy
|
[2011, 2016, 2022, 2033, 2039, 2044, 2050, 2061, 2067, 2072, 2078, 2089, 2095, 2101, 2107, 2112, 2118]
|
http://rosettacode.org/wiki/Runtime_evaluation
|
Runtime evaluation
|
Task
Demonstrate a language's ability for programs to execute code written in the language provided at runtime.
Show what kind of program fragments are permitted (e.g. expressions vs. statements), and how to get values in and out (e.g. environments, arguments, return values), if applicable what lexical/static environment the program is evaluated in, and what facilities for restricting (e.g. sandboxes, resource limits) or customizing (e.g. debugging facilities) the execution.
You may not invoke a separate evaluator program, or invoke a compiler and then its output, unless the interface of that program, and the syntax and means of executing it, are considered part of your language/library/platform.
For a more constrained task giving a specific program fragment to evaluate, see Eval in environment.
|
#GW-BASIC
|
GW-BASIC
|
10 LINE INPUT "Type an expression: ",A$
20 OPEN "CHAIN.TMP" FOR OUTPUT AS #1
30 PRINT #1, "70 LET Y=("+A$+")"
40 CLOSE #1
50 CHAIN MERGE "CHAIN.TMP",60,ALL
60 FOR X=0 TO 5
70 REM
80 PRINT X,Y
90 NEXT X
100 GOTO 10
|
http://rosettacode.org/wiki/Safe_primes_and_unsafe_primes
|
Safe primes and unsafe primes
|
Definitions
A safe prime is a prime p and where (p-1)/2 is also prime.
The corresponding prime (p-1)/2 is known as a Sophie Germain prime.
An unsafe prime is a prime p and where (p-1)/2 isn't a prime.
An unsafe prime is a prime that isn't a safe prime.
Task
Find and display (on one line) the first 35 safe primes.
Find and display the count of the safe primes below 1,000,000.
Find and display the count of the safe primes below 10,000,000.
Find and display (on one line) the first 40 unsafe primes.
Find and display the count of the unsafe primes below 1,000,000.
Find and display the count of the unsafe primes below 10,000,000.
(Optional) display the counts and "below numbers" with commas.
Show all output here.
Related Task
strong and weak primes.
Also see
The OEIS article: safe primes.
The OEIS article: unsafe primes.
|
#Ksh
|
Ksh
|
#!/bin/ksh
# Safe primes and unsafe primes
# # Variables:
#
integer safecnt=0 safedisp=35 safecnt1M=0
integer unsacnt=0 unsadisp=40 unsacnt1M=0
typeset -a safeprime unsafeprime
# # Functions:
#
# # Function _isprime(n) return 1 for prime, 0 for not prime
#
function _isprime {
typeset _n ; integer _n=$1
typeset _i ; integer _i
(( _n < 2 )) && return 0
for (( _i=2 ; _i*_i<=_n ; _i++ )); do
(( ! ( _n % _i ) )) && return 0
done
return 1
}
# # Function _issafe(p) return 1 for safe prime, 0 for not
#
function _issafe {
typeset _p ; integer _p=$1
_isprime $(( (_p - 1) / 2 ))
return $?
}
######
# main #
######
for ((n=3; n<=10000000; n++)); do
_isprime ${n}
(( ! $? )) && continue
_issafe ${n}
if (( $? )); then
(( safecnt++ ))
(( safecnt < safedisp)) && safeprime+=( ${n} )
(( n <= 999999 )) && safecnt1M=${safecnt}
else
(( unsacnt++ ))
(( unsacnt < unsadisp)) && unsafeprime+=( ${n} )
(( n <= 999999 )) && unsacnt1M=${unsacnt}
fi
done
print "Safe primes:\n${safeprime[*]}"
print "There are ${safecnt1M} under 1,000,000"
print "There are ${safecnt} under 10,000,000\n"
print "Unsafe primes:\n${unsafeprime[*]}"
print "There are ${unsacnt1M} under 1,000,000"
print "There are ${unsacnt} under 10,000,000"
|
http://rosettacode.org/wiki/Safe_primes_and_unsafe_primes
|
Safe primes and unsafe primes
|
Definitions
A safe prime is a prime p and where (p-1)/2 is also prime.
The corresponding prime (p-1)/2 is known as a Sophie Germain prime.
An unsafe prime is a prime p and where (p-1)/2 isn't a prime.
An unsafe prime is a prime that isn't a safe prime.
Task
Find and display (on one line) the first 35 safe primes.
Find and display the count of the safe primes below 1,000,000.
Find and display the count of the safe primes below 10,000,000.
Find and display (on one line) the first 40 unsafe primes.
Find and display the count of the unsafe primes below 1,000,000.
Find and display the count of the unsafe primes below 10,000,000.
(Optional) display the counts and "below numbers" with commas.
Show all output here.
Related Task
strong and weak primes.
Also see
The OEIS article: safe primes.
The OEIS article: unsafe primes.
|
#Lua
|
Lua
|
-- FUNCS:
local function T(t) return setmetatable(t, {__index=table}) end
table.filter = function(t,f) local s=T{} for _,v in ipairs(t) do if f(v) then s[#s+1]=v end end return s end
table.map = function(t,f,...) local s=T{} for _,v in ipairs(t) do s[#s+1]=f(v,...) end return s end
table.firstn = function(t,n) local s=T{} n=n>#t and #t or n for i = 1,n do s[i]=t[i] end return s end
-- SIEVE:
local sieve, safe, unsafe, floor, N = {}, T{}, T{}, math.floor, 10000000
for i = 2,N do sieve[i]=true end
for i = 2,N do if sieve[i] then for j=i*i,N,i do sieve[j]=nil end end end
for i = 2,N do if sieve[i] then local t=sieve[floor((i-1)/2)] and safe or unsafe t[#t+1]=i end end
-- TASKS:
local function commafy(i) return tostring(i):reverse():gsub("(%d%d%d)","%1,"):reverse():gsub("^,","") end
print("First 35 safe primes : " .. safe:firstn(35):map(commafy):concat(" "))
print("# safe primes < 1,000,000 : " .. commafy(#safe:filter(function(v) return v<1e6 end)))
print("# safe primes < 10,000,000 : " .. commafy(#safe))
print("First 40 unsafe primes : " .. unsafe:firstn(40):map(commafy):concat(" "))
print("# unsafe primes < 1,000,000 : " .. commafy(#unsafe:filter(function(v) return v<1e6 end)))
print("# unsafe primes < 10,000,000: " .. commafy(#unsafe))
|
http://rosettacode.org/wiki/Same_fringe
|
Same fringe
|
Write a routine that will compare the leaves ("fringe") of two binary trees to determine whether they are the same list of leaves when visited left-to-right. The structure or balance of the trees does not matter; only the number, order, and value of the leaves is important.
Any solution is allowed here, but many computer scientists will consider it inelegant to collect either fringe in its entirety before starting to collect the other one. In fact, this problem is usually proposed in various forums as a way to show off various forms of concurrency (tree-rotation algorithms have also been used to get around the need to collect one tree first). Thinking of it a slightly different way, an elegant solution is one that can perform the minimum amount of work to falsify the equivalence of the fringes when they differ somewhere in the middle, short-circuiting the unnecessary additional traversals and comparisons.
Any representation of a binary tree is allowed, as long as the nodes are orderable, and only downward links are used (for example, you may not use parent or sibling pointers to avoid recursion).
|
#Scheme
|
Scheme
|
; binary tree helpers from "Structure and Interpretation of Computer Programs" 2.3.3
(define (entry tree) (car tree))
(define (left-branch tree) (cadr tree))
(define (right-branch tree) (caddr tree))
(define (make-tree entry left right)
(list entry left right))
; returns a list of leftmost nodes from each level of the tree
(define (descend tree ls)
(if (null? (left-branch tree))
(cons tree ls)
(descend (left-branch tree) (cons tree ls))))
; updates the list to contain leftmost nodes from each remaining level
(define (ascend ls)
(cond
((and (null? (cdr ls)) (null? (right-branch (car ls)))) '())
((null? (right-branch (car ls))) (cdr ls))
(else
(let ((ls (cons (right-branch (car ls))
(cdr ls))))
(if (null? (left-branch (car ls)))
ls
(descend (left-branch (car ls)) ls))))))
; loops thru each list until the end (true) or nodes are unequal (false)
(define (same-fringe? t1 t2)
(let next ((l1 (descend t1 '()))
(l2 (descend t2 '())))
(cond
((and (null? l1) (null? l2)) #t)
((or (null? l1)
(null? l2)
(not (eq? (entry (car l1)) (entry (car l2))))) #f)
(else (next (ascend l1) (ascend l2))))))
|
http://rosettacode.org/wiki/Sieve_of_Eratosthenes
|
Sieve of Eratosthenes
|
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task.
The Sieve of Eratosthenes is a simple algorithm that finds the prime numbers up to a given integer.
Task
Implement the Sieve of Eratosthenes algorithm, with the only allowed optimization that the outer loop can stop at the square root of the limit, and the inner loop may start at the square of the prime just found.
That means especially that you shouldn't optimize by using pre-computed wheels, i.e. don't assume you need only to cross out odd numbers (wheel based on 2), numbers equal to 1 or 5 modulo 6 (wheel based on 2 and 3), or similar wheels based on low primes.
If there's an easy way to add such a wheel based optimization, implement it as an alternative version.
Note
It is important that the sieve algorithm be the actual algorithm used to find prime numbers for the task.
Related tasks
Emirp primes
count in factors
prime decomposition
factors of an integer
extensible prime generator
primality by trial division
factors of a Mersenne number
trial factoring of a Mersenne number
partition an integer X into N primes
sequence of primes by Trial Division
|
#Niue
|
Niue
|
[ dup 2 < ] '<2 ;
[ 1 + 'count ; [ <2 [ , ] when ] count times ] 'fill-stack ;
0 'n ; 0 'v ;
[ .clr 0 'n ; 0 'v ; ] 'reset ;
[ len 1 - n - at 'v ; ] 'set-base ;
[ n 1 + 'n ; ] 'incr-n ;
[ mod 0 = ] 'is-factor ;
[ dup * ] 'sqr ;
[ set-base
v sqr 2 at > not
[ [ dup v = not swap v is-factor and ] remove-if incr-n run ] when ] 'run ;
[ fill-stack run ] 'sieve ;
( tests )
10 sieve .s ( => 2 3 5 7 9 ) reset newline
30 sieve .s ( => 2 3 5 7 11 13 17 19 23 29 )
|
http://rosettacode.org/wiki/Sailors,_coconuts_and_a_monkey_problem
|
Sailors, coconuts and a monkey problem
|
Five sailors are shipwrecked on an island and collect a large pile of coconuts during the day.
That night the first sailor wakes up and decides to take his first share early so tries to divide the pile of coconuts equally into five piles but finds that there is one coconut left over, so he tosses it to a monkey and then hides "his" one of the five equally sized piles of coconuts and pushes the other four piles together to form a single visible pile of coconuts again and goes to bed.
To cut a long story short, each of the sailors in turn gets up once during the night and performs the same actions of dividing the coconut pile into five, finding that one coconut is left over and giving that single remainder coconut to the monkey.
In the morning (after the surreptitious and separate action of each of the five sailors during the night), the remaining coconuts are divided into five equal piles for each of the sailors, whereupon it is found that the pile of coconuts divides equally amongst the sailors with no remainder. (Nothing for the monkey in the morning.)
The task
Calculate the minimum possible size of the initial pile of coconuts collected during the first day.
Use a method that assumes an answer is possible, and then applies the constraints of the tale to see if it is correct. (I.e. no applying some formula that generates the correct answer without integer divisions and remainders and tests on remainders; but constraint solvers are allowed.)
Calculate the size of the initial pile of coconuts if six sailors were marooned and went through a similar process (but split into six piles instead of five of course).
Show your answers here.
Extra credit (optional)
Give some indication of the number of coconuts each sailor hides during the night.
Note
Of course the tale is told in a world where the collection of any amount of coconuts in a day and multiple divisions of the pile, etc can occur in time fitting the story line, so as not to affect the mathematics.
The tale is also told in a version where the monkey also gets a coconut in the morning. This is not that tale!
C.f
Monkeys and Coconuts - Numberphile (Video) Analytical solution.
A002021: Pile of coconuts problem The On-Line Encyclopedia of Integer Sequences. (Although some of its references may use the alternate form of the tale).
|
#Sidef
|
Sidef
|
func coconuts(sailors, monkeys=1) {
if ((sailors < 2) || (monkeys < 1) || (sailors <= monkeys)) {
return 0
}
var blue_cocos = sailors-1
var pow_bc = blue_cocos**sailors
var x_cocos = pow_bc
while ((x_cocos-blue_cocos)%sailors || ((x_cocos-blue_cocos)/sailors < 1)) {
x_cocos += pow_bc
}
return monkeys*(x_cocos / pow_bc * sailors**sailors - blue_cocos)
}
2.to(9).each { |sailor|
say "#{sailor}: #{coconuts(sailor)}";
}
|
http://rosettacode.org/wiki/Search_a_list_of_records
|
Search a list of records
|
Many programming languages provide convenient ways to look for a known value in a simple list of strings or numbers.
But what if the elements of the list are themselves compound records/objects/data-structures, and the search condition is more complex than a simple equality test?
Task[edit]
Write a function/method/etc. that can find the first element in a given list matching a given condition.
It should be as generic and reusable as possible.
(Of course if your programming language already provides such a feature, you can use that instead of recreating it.)
Then to demonstrate its functionality, create the data structure specified under #Data set, and perform on it the searches specified under #Test cases.
Data set
The data structure to be used contains the names and populations (in millions) of the 10 largest metropolitan areas in Africa, and looks as follows when represented in JSON:
[
{ "name": "Lagos", "population": 21.0 },
{ "name": "Cairo", "population": 15.2 },
{ "name": "Kinshasa-Brazzaville", "population": 11.3 },
{ "name": "Greater Johannesburg", "population": 7.55 },
{ "name": "Mogadishu", "population": 5.85 },
{ "name": "Khartoum-Omdurman", "population": 4.98 },
{ "name": "Dar Es Salaam", "population": 4.7 },
{ "name": "Alexandria", "population": 4.58 },
{ "name": "Abidjan", "population": 4.4 },
{ "name": "Casablanca", "population": 3.98 }
]
However, you shouldn't parse it from JSON, but rather represent it natively in your programming language.
The top-level data structure should be an ordered collection (i.e. a list, array, vector, or similar).
Each element in this list should be an associative collection that maps from keys to values (i.e. a struct, object, hash map, dictionary, or similar).
Each of them has two entries: One string value with key "name", and one numeric value with key "population".
You may rely on the list being sorted by population count, as long as you explain this to readers.
If any of that is impossible or unreasonable in your programming language, then feel free to deviate, as long as you explain your reasons in a comment above your solution.
Test cases
Search
Expected result
Find the (zero-based) index of the first city in the list whose name is "Dar Es Salaam"
6
Find the name of the first city in this list whose population is less than 5 million
Khartoum-Omdurman
Find the population of the first city in this list whose name starts with the letter "A"
4.58
Guidance
If your programming language supports higher-order programming, then the most elegant way to implement the requested functionality in a generic and reusable way, might be to write a function (maybe called "find_index" or similar), that takes two arguments:
The list to search through.
A function/lambda/closure (the so-called "predicate"), which will be applied in turn to each element in the list, and whose boolean return value defines whether that element matches the search requirement.
If this is not the approach which would be most natural or idiomatic in your language, explain why, and show what is.
Related tasks
Search a list
|
#Lua
|
Lua
|
-- Dataset declaration
local cityPops = {
{name = "Lagos", population = 21.0},
{name = "Cairo", population = 15.2},
{name = "Kinshasa-Brazzaville", population = 11.3},
{name = "Greater Johannesburg", population = 7.55},
{name = "Mogadishu", population = 5.85},
{name = "Khartoum-Omdurman", population = 4.98},
{name = "Dar Es Salaam", population = 4.7},
{name = "Alexandria", population = 4.58},
{name = "Abidjan", population = 4.4},
{name = "Casablanca", population = 3.98}
}
-- Function to search a dataset using a custom match function
function recordSearch (dataset, matchFunction)
local returnValue
for index, element in pairs(dataset) do
returnValue = matchFunction(index, element)
if returnValue then return returnValue end
end
return nil
end
-- Main procedure
local testCases = {
function (i, e) if e.name == "Dar Es Salaam" then return i - 1 end end,
function (i, e) if e.population < 5 then return e.name end end,
function (i, e) if e.name:sub(1, 1) == "A" then return e.population end end
}
for _, func in pairs(testCases) do print(recordSearch(cityPops, func)) end
|
http://rosettacode.org/wiki/Ruth-Aaron_numbers
|
Ruth-Aaron numbers
|
A Ruth–Aaron pair consists of two consecutive integers (e.g., 714 and 715) for which the sums of the prime divisors of each integer are equal. So called because 714 is Babe Ruth's lifetime home run record; Hank Aaron's 715th home run broke this record and 714 and 715 have the same prime divisor sum.
A Ruth–Aaron triple consists of three consecutive integers with the same properties.
There is a second variant of Ruth–Aaron numbers, one which uses prime factors rather than prime divisors. The difference; divisors are unique, factors may be repeated. The 714, 715 pair appears in both, so the name still fits.
It is common to refer to each Ruth–Aaron group by the first number in it.
Task
Find and show, here on this page, the first 30 Ruth-Aaron numbers (factors).
Find and show, here on this page, the first 30 Ruth-Aaron numbers (divisors).
Stretch
Find and show the first Ruth-Aaron triple (factors).
Find and show the first Ruth-Aaron triple (divisors).
See also
Wikipedia: Ruth–Aaron pair
OEIS:A006145 - Ruth-Aaron numbers (1): sum of prime divisors of n = sum of prime divisors of n+1
OEIS:A039752 - Ruth-Aaron numbers (2): sum of prime divisors of n = sum of prime divisors of n+1 (both taken with multiplicity)
|
#XPL0
|
XPL0
|
func DivSum(N, AllDiv); \Return sum of divisors
int N, AllDiv; \all divisors vs. only prime divisors
int F, F0, S, Q;
[F:= 2; F0:= 0; S:= 0;
repeat Q:= N/F;
if rem(0) = 0 then
[if AllDiv then S:= S+F
else if F # F0 then
[S:= S+F; F0:= F];
N:= Q;
]
else F:= F+1;
until F > N;
return S;
];
proc Ruth(AllDiv); \Show Ruth-Aaron numbers
int AllDiv;
int C, S, S0, N;
[C:= 0; S0:= 0;
N:= 2;
repeat S:= DivSum(N, AllDiv);
if S = S0 then
[IntOut(0, N-1);
C:= C+1;
if rem(C/10) = 0 then CrLf(0) else ChOut(0, ^ );
];
S0:= S;
N:= N+1;
until C >= 30;
];
[Ruth(true);
CrLf(0);
Ruth(false);
]
|
http://rosettacode.org/wiki/Search_a_list
|
Search a list
|
Task[edit]
Find the index of a string (needle) in an indexable, ordered collection of strings (haystack).
Raise an exception if the needle is missing.
If there is more than one occurrence then return the smallest index to the needle.
Extra credit
Return the largest index to a needle that has multiple occurrences in the haystack.
See also
Search a list of records
|
#BBC_BASIC
|
BBC BASIC
|
DIM haystack$(27)
haystack$() = "alpha","bravo","charlie","delta","echo","foxtrot","golf", \
\ "hotel","india","juliet","kilo","lima","mike","needle", \
\ "november","oscar","papa","quebec","romeo","sierra","tango", \
\ "needle","uniform","victor","whisky","x-ray","yankee","zulu"
needle$ = "needle"
maxindex% = DIM(haystack$(), 1)
FOR index% = 0 TO maxindex%
IF needle$ = haystack$(index%) EXIT FOR
NEXT
IF index% <= maxindex% THEN
PRINT "First found at index "; index%
FOR last% = maxindex% TO 0 STEP -1
IF needle$ = haystack$(last%) EXIT FOR
NEXT
IF last%<>index% PRINT "Last found at index "; last%
ELSE
ERROR 100, "Not found"
ENDIF
|
http://rosettacode.org/wiki/Runtime_evaluation
|
Runtime evaluation
|
Task
Demonstrate a language's ability for programs to execute code written in the language provided at runtime.
Show what kind of program fragments are permitted (e.g. expressions vs. statements), and how to get values in and out (e.g. environments, arguments, return values), if applicable what lexical/static environment the program is evaluated in, and what facilities for restricting (e.g. sandboxes, resource limits) or customizing (e.g. debugging facilities) the execution.
You may not invoke a separate evaluator program, or invoke a compiler and then its output, unless the interface of that program, and the syntax and means of executing it, are considered part of your language/library/platform.
For a more constrained task giving a specific program fragment to evaluate, see Eval in environment.
|
#Harbour
|
Harbour
|
Procedure Main()
local bAdd := {|Label,n1,n2| Qout( Label ), QQout( n1 + n2 )}
Eval( bAdd, "5+5 = ", 5, 5 )
Eval( bAdd, "5-5 = ", 5, -5 )
return
Upon execution you see:
5+5 = 10
5-5 = 0
|
http://rosettacode.org/wiki/Runtime_evaluation
|
Runtime evaluation
|
Task
Demonstrate a language's ability for programs to execute code written in the language provided at runtime.
Show what kind of program fragments are permitted (e.g. expressions vs. statements), and how to get values in and out (e.g. environments, arguments, return values), if applicable what lexical/static environment the program is evaluated in, and what facilities for restricting (e.g. sandboxes, resource limits) or customizing (e.g. debugging facilities) the execution.
You may not invoke a separate evaluator program, or invoke a compiler and then its output, unless the interface of that program, and the syntax and means of executing it, are considered part of your language/library/platform.
For a more constrained task giving a specific program fragment to evaluate, see Eval in environment.
|
#HicEst
|
HicEst
|
value = XEQ( " temp = 1 + 2 + 3 ") ! value is assigned 6
! temp is undefined outside XEQ, if it was not defined before.
XEQ(" WRITE(Messagebox) 'Hello World !' ")
OPEN(FIle="my_file.txt")
READ(FIle="my_file.txt", Row=6) string
XEQ( string ) ! executes row 6 of my_file.txt
|
http://rosettacode.org/wiki/Runtime_evaluation
|
Runtime evaluation
|
Task
Demonstrate a language's ability for programs to execute code written in the language provided at runtime.
Show what kind of program fragments are permitted (e.g. expressions vs. statements), and how to get values in and out (e.g. environments, arguments, return values), if applicable what lexical/static environment the program is evaluated in, and what facilities for restricting (e.g. sandboxes, resource limits) or customizing (e.g. debugging facilities) the execution.
You may not invoke a separate evaluator program, or invoke a compiler and then its output, unless the interface of that program, and the syntax and means of executing it, are considered part of your language/library/platform.
For a more constrained task giving a specific program fragment to evaluate, see Eval in environment.
|
#J
|
J
|
". 'a =: +/ 1 2 3' NB. execute a string to sum 1, 2 and 3 and assign to noun a
|
http://rosettacode.org/wiki/Safe_primes_and_unsafe_primes
|
Safe primes and unsafe primes
|
Definitions
A safe prime is a prime p and where (p-1)/2 is also prime.
The corresponding prime (p-1)/2 is known as a Sophie Germain prime.
An unsafe prime is a prime p and where (p-1)/2 isn't a prime.
An unsafe prime is a prime that isn't a safe prime.
Task
Find and display (on one line) the first 35 safe primes.
Find and display the count of the safe primes below 1,000,000.
Find and display the count of the safe primes below 10,000,000.
Find and display (on one line) the first 40 unsafe primes.
Find and display the count of the unsafe primes below 1,000,000.
Find and display the count of the unsafe primes below 10,000,000.
(Optional) display the counts and "below numbers" with commas.
Show all output here.
Related Task
strong and weak primes.
Also see
The OEIS article: safe primes.
The OEIS article: unsafe primes.
|
#Maple
|
Maple
|
showSafePrimes := proc(n::posint)
local prime_list, k;
prime_list := [5];
for k to n - 1 do
prime_list := [op(prime_list), NumberTheory:-NextSafePrime(prime_list[-1])];
end do;
return prime_list;
end proc;
showUnsafePrimes := proc(n::posint)
local prime_num, k;
prime_num := [2];
for k to n-1 do
prime_num := [op(prime_num), nextprime(prime_num[-1])];
end do;
return remove(x -> member(x, showSafePrimes(n)), prime_num);
end proc:
countSafePrimes := proc(n::posint)
local counts, prime;
counts := 0;
prime := 5;
while prime < n do prime := NumberTheory:-NextSafePrime(prime);
counts := counts + 1;
end do;
return counts;
end proc;
countUnsafePrimes := proc(n::posint)
local safe_counts, total;
safe_counts := countSafePrimes(n);
total := NumberTheory:-PrimeCounting(n);
return total - safe_counts;
end proc;
showSafePrimes(35);
showUnsafePrimes(40);
countSafePrimes(1000000);
countSafePrimes(10000000);
countUnsafePrimes(1000000);
countUnsafePrimes(10000000);
|
http://rosettacode.org/wiki/Safe_primes_and_unsafe_primes
|
Safe primes and unsafe primes
|
Definitions
A safe prime is a prime p and where (p-1)/2 is also prime.
The corresponding prime (p-1)/2 is known as a Sophie Germain prime.
An unsafe prime is a prime p and where (p-1)/2 isn't a prime.
An unsafe prime is a prime that isn't a safe prime.
Task
Find and display (on one line) the first 35 safe primes.
Find and display the count of the safe primes below 1,000,000.
Find and display the count of the safe primes below 10,000,000.
Find and display (on one line) the first 40 unsafe primes.
Find and display the count of the unsafe primes below 1,000,000.
Find and display the count of the unsafe primes below 10,000,000.
(Optional) display the counts and "below numbers" with commas.
Show all output here.
Related Task
strong and weak primes.
Also see
The OEIS article: safe primes.
The OEIS article: unsafe primes.
|
#Mathematica.2FWolfram_Language
|
Mathematica/Wolfram Language
|
ClearAll[SafePrimeQ, UnsafePrimeQ]
SafePrimeQ[n_Integer] := PrimeQ[n] \[And] PrimeQ[(n - 1)/2]
UnsafePrimeQ[n_Integer] := PrimeQ[n] \[And] ! PrimeQ[(n - 1)/2]
res = {};
i = 1;
While[Length[res] < 35,
test = SafePrimeQ[Prime[i]];
If[test, AppendTo[res, Prime[i]]];
i++
]
res
Count[Range[PrimePi[10^6]], _?(Prime /* SafePrimeQ)]
Count[Range[PrimePi[10^7]], _?(Prime /* SafePrimeQ)]
res = {};
i = 1;
While[Length[res] < 40,
test = UnsafePrimeQ[Prime[i]];
If[test, AppendTo[res, Prime[i]]];
i++
]
res
Count[Range[PrimePi[10^6]], _?(Prime /* UnsafePrimeQ)]
Count[Range[PrimePi[10^7]], _?(Prime /* UnsafePrimeQ)]
|
http://rosettacode.org/wiki/Same_fringe
|
Same fringe
|
Write a routine that will compare the leaves ("fringe") of two binary trees to determine whether they are the same list of leaves when visited left-to-right. The structure or balance of the trees does not matter; only the number, order, and value of the leaves is important.
Any solution is allowed here, but many computer scientists will consider it inelegant to collect either fringe in its entirety before starting to collect the other one. In fact, this problem is usually proposed in various forums as a way to show off various forms of concurrency (tree-rotation algorithms have also been used to get around the need to collect one tree first). Thinking of it a slightly different way, an elegant solution is one that can perform the minimum amount of work to falsify the equivalence of the fringes when they differ somewhere in the middle, short-circuiting the unnecessary additional traversals and comparisons.
Any representation of a binary tree is allowed, as long as the nodes are orderable, and only downward links are used (for example, you may not use parent or sibling pointers to avoid recursion).
|
#Sidef
|
Sidef
|
var trees = [
# 0..2 are same
[ 'd', [ 'c', [ 'a', 'b', ], ], ],
[ [ 'd', 'c' ], [ 'a', 'b' ] ],
[ [ [ 'd', 'c', ], 'a', ], 'b', ],
# and this one's different!
[ [ [ [ [ [ 'a' ], 'b' ], 'c', ], 'd', ], 'e', ], 'f' ],
]
func get_tree_iterator(*rtrees) {
var tree
func {
tree = rtrees.pop
while (defined(tree) && tree.kind_of(Array)) {
rtrees.append(tree[1])
tree = tree[0]
}
return tree
}
}
func cmp_fringe(a, b) {
var ti1 = get_tree_iterator(a)
var ti2 = get_tree_iterator(b)
loop {
var (L, R) = (ti1(), ti2())
defined(L) && defined(R) && (L == R) && next
!defined(L) && !defined(R) && return "Same"
return "Different"
}
}
for idx in ^(trees.end) {
say ("tree[#{idx}] vs tree[#{idx+1}]: ",
cmp_fringe(trees[idx], trees[idx+1]))
}
|
http://rosettacode.org/wiki/Sieve_of_Eratosthenes
|
Sieve of Eratosthenes
|
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task.
The Sieve of Eratosthenes is a simple algorithm that finds the prime numbers up to a given integer.
Task
Implement the Sieve of Eratosthenes algorithm, with the only allowed optimization that the outer loop can stop at the square root of the limit, and the inner loop may start at the square of the prime just found.
That means especially that you shouldn't optimize by using pre-computed wheels, i.e. don't assume you need only to cross out odd numbers (wheel based on 2), numbers equal to 1 or 5 modulo 6 (wheel based on 2 and 3), or similar wheels based on low primes.
If there's an easy way to add such a wheel based optimization, implement it as an alternative version.
Note
It is important that the sieve algorithm be the actual algorithm used to find prime numbers for the task.
Related tasks
Emirp primes
count in factors
prime decomposition
factors of an integer
extensible prime generator
primality by trial division
factors of a Mersenne number
trial factoring of a Mersenne number
partition an integer X into N primes
sequence of primes by Trial Division
|
#Oberon-2
|
Oberon-2
|
MODULE Primes;
IMPORT Out, Math;
CONST N = 1000;
VAR a: ARRAY N OF BOOLEAN;
i, j, m: INTEGER;
BEGIN
(* Set all elements of a to TRUE. *)
FOR i := 1 TO N - 1 DO
a[i] := TRUE;
END;
(* Compute square root of N and convert back to INTEGER. *)
m := ENTIER(Math.Sqrt(N));
FOR i := 2 TO m DO
IF a[i] THEN
FOR j := 2 TO (N - 1) DIV i DO
a[i*j] := FALSE;
END;
END;
END;
(* Print all the elements of a that are TRUE. *)
FOR i := 2 TO N - 1 DO
IF a[i] THEN
Out.Int(i, 4);
END;
END;
Out.Ln;
END Primes.
|
http://rosettacode.org/wiki/Sailors,_coconuts_and_a_monkey_problem
|
Sailors, coconuts and a monkey problem
|
Five sailors are shipwrecked on an island and collect a large pile of coconuts during the day.
That night the first sailor wakes up and decides to take his first share early so tries to divide the pile of coconuts equally into five piles but finds that there is one coconut left over, so he tosses it to a monkey and then hides "his" one of the five equally sized piles of coconuts and pushes the other four piles together to form a single visible pile of coconuts again and goes to bed.
To cut a long story short, each of the sailors in turn gets up once during the night and performs the same actions of dividing the coconut pile into five, finding that one coconut is left over and giving that single remainder coconut to the monkey.
In the morning (after the surreptitious and separate action of each of the five sailors during the night), the remaining coconuts are divided into five equal piles for each of the sailors, whereupon it is found that the pile of coconuts divides equally amongst the sailors with no remainder. (Nothing for the monkey in the morning.)
The task
Calculate the minimum possible size of the initial pile of coconuts collected during the first day.
Use a method that assumes an answer is possible, and then applies the constraints of the tale to see if it is correct. (I.e. no applying some formula that generates the correct answer without integer divisions and remainders and tests on remainders; but constraint solvers are allowed.)
Calculate the size of the initial pile of coconuts if six sailors were marooned and went through a similar process (but split into six piles instead of five of course).
Show your answers here.
Extra credit (optional)
Give some indication of the number of coconuts each sailor hides during the night.
Note
Of course the tale is told in a world where the collection of any amount of coconuts in a day and multiple divisions of the pile, etc can occur in time fitting the story line, so as not to affect the mathematics.
The tale is also told in a version where the monkey also gets a coconut in the morning. This is not that tale!
C.f
Monkeys and Coconuts - Numberphile (Video) Analytical solution.
A002021: Pile of coconuts problem The On-Line Encyclopedia of Integer Sequences. (Although some of its references may use the alternate form of the tale).
|
#Tcl
|
Tcl
|
proc assert {expr {msg ""}} { ;# for "static" assertions that throw nice errors
if {![uplevel 1 [list expr $expr]]} {
if {$msg eq ""} {
catch {set msg "{[uplevel 1 [list subst -noc $expr]]}"}
}
throw {ASSERT ERROR} "{$expr} $msg"
}
}
proc divmod {a b} {
list [expr {$a / $b}] [expr {$a % $b}]
}
proc overnight {ns nn} {
set result {}
for {set s 0} {$s < $ns} {incr s} {
lassign [divmod $nn $ns] q r
assert {$r eq 1} "Incorrect remainder in round $s (expected 1, got $r)"
set nn [expr {$q*($ns-1)}]
lappend result $s $q $r $nn
}
lassign [divmod $nn $ns] q r
assert {$r eq 0} "Incorrect remainder at end (expected 0, got $r)"
return $result
}
proc minnuts {nsailors} {
while 1 {
incr nnuts
try {
set result [overnight $nsailors $nnuts]
} on error {} {
# continue
} on ok {} {
break
}
}
puts "$nsailors: $nnuts"
foreach {sailor takes gives leaves} $result {
puts " Sailor #$sailor takes $takes, giving $gives to the monkey and leaves $leaves"
}
puts "In the morning, each sailor gets [expr {$leaves/$nsailors}] nuts"
}
foreach n {5 6} {
puts "Solution with $n sailors:"
minnuts $n
}
|
http://rosettacode.org/wiki/Search_a_list_of_records
|
Search a list of records
|
Many programming languages provide convenient ways to look for a known value in a simple list of strings or numbers.
But what if the elements of the list are themselves compound records/objects/data-structures, and the search condition is more complex than a simple equality test?
Task[edit]
Write a function/method/etc. that can find the first element in a given list matching a given condition.
It should be as generic and reusable as possible.
(Of course if your programming language already provides such a feature, you can use that instead of recreating it.)
Then to demonstrate its functionality, create the data structure specified under #Data set, and perform on it the searches specified under #Test cases.
Data set
The data structure to be used contains the names and populations (in millions) of the 10 largest metropolitan areas in Africa, and looks as follows when represented in JSON:
[
{ "name": "Lagos", "population": 21.0 },
{ "name": "Cairo", "population": 15.2 },
{ "name": "Kinshasa-Brazzaville", "population": 11.3 },
{ "name": "Greater Johannesburg", "population": 7.55 },
{ "name": "Mogadishu", "population": 5.85 },
{ "name": "Khartoum-Omdurman", "population": 4.98 },
{ "name": "Dar Es Salaam", "population": 4.7 },
{ "name": "Alexandria", "population": 4.58 },
{ "name": "Abidjan", "population": 4.4 },
{ "name": "Casablanca", "population": 3.98 }
]
However, you shouldn't parse it from JSON, but rather represent it natively in your programming language.
The top-level data structure should be an ordered collection (i.e. a list, array, vector, or similar).
Each element in this list should be an associative collection that maps from keys to values (i.e. a struct, object, hash map, dictionary, or similar).
Each of them has two entries: One string value with key "name", and one numeric value with key "population".
You may rely on the list being sorted by population count, as long as you explain this to readers.
If any of that is impossible or unreasonable in your programming language, then feel free to deviate, as long as you explain your reasons in a comment above your solution.
Test cases
Search
Expected result
Find the (zero-based) index of the first city in the list whose name is "Dar Es Salaam"
6
Find the name of the first city in this list whose population is less than 5 million
Khartoum-Omdurman
Find the population of the first city in this list whose name starts with the letter "A"
4.58
Guidance
If your programming language supports higher-order programming, then the most elegant way to implement the requested functionality in a generic and reusable way, might be to write a function (maybe called "find_index" or similar), that takes two arguments:
The list to search through.
A function/lambda/closure (the so-called "predicate"), which will be applied in turn to each element in the list, and whose boolean return value defines whether that element matches the search requirement.
If this is not the approach which would be most natural or idiomatic in your language, explain why, and show what is.
Related tasks
Search a list
|
#Ksh
|
Ksh
|
#!/bin/ksh
# Search a list of records
# # Variables:
#
json='{ "name": "Lagos", "population": 21.0 },
{ "name": "Cairo", "population": 15.2 },
{ "name": "Kinshasa-Brazzaville", "population": 11.3 },
{ "name": "Greater Johannesburg", "population": 7.55 },
{ "name": "Mogadishu", "population": 5.85 },
{ "name": "Khartoum-Omdurman", "population": 4.98 },
{ "name": "Dar Es Salaam", "population": 4.7 },
{ "name": "Alexandria", "population": 4.58 },
{ "name": "Abidjan", "population": 4.4 },
{ "name": "Casablanca", "population": 3.98 }'
typeset -a African_Metro
integer i=0
typeset -T Metro_Africa_t=(
typeset -h 'Metro name' met_name=''
typeset -E3 -h 'Metro population' met_pop
function init_metro {
typeset name ; name="$1"
typeset pop ; typeset -E3 pop=$2
_.met_name=${name}
_.met_pop=${pop}
}
function prt_name {
print "${_.met_name}"
}
function prt_pop {
print "${_.met_pop}"
}
)
# # Functions:
#
# # Function _findcityindex(arr, name) - return array index of citry named "name"
#
function _findcityindex {
typeset _arr ; nameref _arr="$1"
typeset _name ; _name="$2"
typeset _i ; integer _i
for ((_i=0; _i<${#_arr[*]}; _i++)); do
[[ ${_name} == $(_arr[_i].prt_name) ]] && echo ${_i} && return 0
done
echo "-1"
return 1
}
# # Function _findcitynamepop(arr, pop, xx) - find 1st city name pop $3 of $2
#
function _findcitynamepop {
typeset _arr ; nameref _arr="$1"
typeset _pop ; typeset -E3 _pop=$2
typeset _comp ; _comp="$3"
typeset _i ; integer _i
for ((_i=0; _i<${#_arr[*]}; _i++)); do
case ${_comp} in
gt)
[[ $(_arr[_i].prt_pop) -gt ${_pop} ]] && _arr[_i].prt_name && return 0 ;;
lt)
[[ $(_arr[_i].prt_pop) -lt ${_pop} ]] && _arr[_i].prt_name && return 0 ;;
esac
done
echo "DNE"
return 1
}
# # Function _findcitypopname(arr, pat) - find pop of first city starting w/ pat
#
function _findcitypopname {
typeset _arr ; nameref _arr="$1"
typeset _pat ; _pat="$2"
typeset _i ; integer _i
for ((_i=0; _i<${#_arr[*]}; _i++)); do
[[ $(_arr[_i].prt_name) == ${_pat}* ]] && _arr[_i].prt_pop && return 0
done
echo "-1"
return 1
}
######
# main #
######
# # An indexed array of Type variable (objects)
#
echo "${json}" | while read; do
metro="${REPLY#*\"name\"\:\ }" ; metro="${metro%%\,*}" ; metro="${metro//\"/}"
population="${REPLY#*\"population\"\:\ }" ; population=${population%+(\ )\}*(\,)}
Metro_Africa_t African_Metro[i]
African_Metro[i++].init_metro "${metro}" ${population}
done
_findcityindex African_Metro "Dar Es Salaam"
_findcitynamepop African_Metro 5.0 lt
_findcitypopname African_Metro "A"
|
http://rosettacode.org/wiki/Search_a_list_of_records
|
Search a list of records
|
Many programming languages provide convenient ways to look for a known value in a simple list of strings or numbers.
But what if the elements of the list are themselves compound records/objects/data-structures, and the search condition is more complex than a simple equality test?
Task[edit]
Write a function/method/etc. that can find the first element in a given list matching a given condition.
It should be as generic and reusable as possible.
(Of course if your programming language already provides such a feature, you can use that instead of recreating it.)
Then to demonstrate its functionality, create the data structure specified under #Data set, and perform on it the searches specified under #Test cases.
Data set
The data structure to be used contains the names and populations (in millions) of the 10 largest metropolitan areas in Africa, and looks as follows when represented in JSON:
[
{ "name": "Lagos", "population": 21.0 },
{ "name": "Cairo", "population": 15.2 },
{ "name": "Kinshasa-Brazzaville", "population": 11.3 },
{ "name": "Greater Johannesburg", "population": 7.55 },
{ "name": "Mogadishu", "population": 5.85 },
{ "name": "Khartoum-Omdurman", "population": 4.98 },
{ "name": "Dar Es Salaam", "population": 4.7 },
{ "name": "Alexandria", "population": 4.58 },
{ "name": "Abidjan", "population": 4.4 },
{ "name": "Casablanca", "population": 3.98 }
]
However, you shouldn't parse it from JSON, but rather represent it natively in your programming language.
The top-level data structure should be an ordered collection (i.e. a list, array, vector, or similar).
Each element in this list should be an associative collection that maps from keys to values (i.e. a struct, object, hash map, dictionary, or similar).
Each of them has two entries: One string value with key "name", and one numeric value with key "population".
You may rely on the list being sorted by population count, as long as you explain this to readers.
If any of that is impossible or unreasonable in your programming language, then feel free to deviate, as long as you explain your reasons in a comment above your solution.
Test cases
Search
Expected result
Find the (zero-based) index of the first city in the list whose name is "Dar Es Salaam"
6
Find the name of the first city in this list whose population is less than 5 million
Khartoum-Omdurman
Find the population of the first city in this list whose name starts with the letter "A"
4.58
Guidance
If your programming language supports higher-order programming, then the most elegant way to implement the requested functionality in a generic and reusable way, might be to write a function (maybe called "find_index" or similar), that takes two arguments:
The list to search through.
A function/lambda/closure (the so-called "predicate"), which will be applied in turn to each element in the list, and whose boolean return value defines whether that element matches the search requirement.
If this is not the approach which would be most natural or idiomatic in your language, explain why, and show what is.
Related tasks
Search a list
|
#Maple
|
Maple
|
rec := [table(["name"="Lagos","population"=21.0]),
table(["name"="Cairo","population"=15.2]),
table(["name"="Kinshasa-Brazzaville","population"=11.3]),
table(["name"="Greater Johannesburg","population"=7.55]),
table(["name"="Mogadishu","population"=5.85]),
table(["name"="Khartoum-Omdurman","population"=4.98]),
table(["name"="Dar Es Salaam","population"=4.7 ]),
table(["name"="Alexandria","population"=4.58]),
table(["name"="Abidjan","population"=4.4]),
table(["name"="Casablanca","population"=3.98])]:
searchRec := proc(rec, pred, operation)
local i:
for i to numelems(rec) do
if pred(rec[i]) then
return operation(rec[i],i):
fi:
od:
end proc:
searchRec(rec, x->x["name"] = "Dar Es Salaam", (x,i)->print(i-1)): # minus 1 since Maple is 1-indexed
searchRec(rec, x->x["population"]<5, (x,i)->print(x["name"])):
searchRec(rec, x->x["name"][1] = "A", (x,i)->print(x["population"])):
|
http://rosettacode.org/wiki/Search_a_list
|
Search a list
|
Task[edit]
Find the index of a string (needle) in an indexable, ordered collection of strings (haystack).
Raise an exception if the needle is missing.
If there is more than one occurrence then return the smallest index to the needle.
Extra credit
Return the largest index to a needle that has multiple occurrences in the haystack.
See also
Search a list of records
|
#BQN
|
BQN
|
list ← ⟨"Zig", "Zag", "Wally", "Ronald", "Bush", "Krusty", "Charlie", "Bush", "Boz", "Zag"⟩
IndexOf ← {
("Error: '" ∾𝕩∾ "' Not found in list") ! (≠𝕨)≠ind ← ⊑𝕨⊐⋈𝕩
ind
}
•Show list ⊐ "Wally"‿"Hi" # intended
•Show list IndexOf "Wally"
list IndexOf "Hi"
|
http://rosettacode.org/wiki/Runtime_evaluation
|
Runtime evaluation
|
Task
Demonstrate a language's ability for programs to execute code written in the language provided at runtime.
Show what kind of program fragments are permitted (e.g. expressions vs. statements), and how to get values in and out (e.g. environments, arguments, return values), if applicable what lexical/static environment the program is evaluated in, and what facilities for restricting (e.g. sandboxes, resource limits) or customizing (e.g. debugging facilities) the execution.
You may not invoke a separate evaluator program, or invoke a compiler and then its output, unless the interface of that program, and the syntax and means of executing it, are considered part of your language/library/platform.
For a more constrained task giving a specific program fragment to evaluate, see Eval in environment.
|
#Java
|
Java
|
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.lang.reflect.InvocationTargetException;
import java.net.URI;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import javax.tools.FileObject;
import javax.tools.ForwardingJavaFileManager;
import javax.tools.JavaCompiler;
import javax.tools.JavaFileObject;
import javax.tools.SimpleJavaFileObject;
import javax.tools.StandardJavaFileManager;
import javax.tools.StandardLocation;
import javax.tools.ToolProvider;
public class Evaluator{
public static void main(String[] args){
new Evaluator().eval(
"SayHello",
"public class SayHello{public void speak(){System.out.println(\"Hello world\");}}",
"speak"
);
}
void eval(String className, String classCode, String methodName){
Map<String, ByteArrayOutputStream> classCache = new HashMap<>();
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
if ( null == compiler )
throw new RuntimeException("Could not get a compiler.");
StandardJavaFileManager sfm = compiler.getStandardFileManager(null, null, null);
ForwardingJavaFileManager<StandardJavaFileManager> fjfm = new ForwardingJavaFileManager<StandardJavaFileManager>(sfm){
@Override
public JavaFileObject getJavaFileForOutput(Location location, String className, JavaFileObject.Kind kind, FileObject sibling)
throws IOException{
if (StandardLocation.CLASS_OUTPUT == location && JavaFileObject.Kind.CLASS == kind)
return new SimpleJavaFileObject(URI.create("mem:///" + className + ".class"), JavaFileObject.Kind.CLASS){
@Override
public OutputStream openOutputStream()
throws IOException{
ByteArrayOutputStream baos = new ByteArrayOutputStream();
classCache.put(className, baos);
return baos;
}
};
else
throw new IllegalArgumentException("Unexpected output file requested: " + location + ", " + className + ", " + kind);
}
};
List<JavaFileObject> files = new LinkedList<JavaFileObject>(){{
add(
new SimpleJavaFileObject(URI.create("string:///" + className + ".java"), JavaFileObject.Kind.SOURCE){
@Override
public CharSequence getCharContent(boolean ignoreEncodingErrors){
return classCode;
}
}
);
}};
// Now we can compile!
compiler.getTask(null, fjfm, null, null, null, files).call();
try{
Class<?> clarse = new ClassLoader(){
@Override
public Class<?> findClass(String name){
if (! name.startsWith(className))
throw new IllegalArgumentException("This class loader is for " + className + " - could not handle \"" + name + '"');
byte[] bytes = classCache.get(name).toByteArray();
return defineClass(name, bytes, 0, bytes.length);
}
}.loadClass(className);
// Invoke a method on the thing we compiled
clarse.getMethod(methodName).invoke(clarse.newInstance());
}catch(ClassNotFoundException | InstantiationException | IllegalAccessException | NoSuchMethodException | InvocationTargetException x){
throw new RuntimeException("Run failed: " + x, x);
}
}
}
|
http://rosettacode.org/wiki/Safe_primes_and_unsafe_primes
|
Safe primes and unsafe primes
|
Definitions
A safe prime is a prime p and where (p-1)/2 is also prime.
The corresponding prime (p-1)/2 is known as a Sophie Germain prime.
An unsafe prime is a prime p and where (p-1)/2 isn't a prime.
An unsafe prime is a prime that isn't a safe prime.
Task
Find and display (on one line) the first 35 safe primes.
Find and display the count of the safe primes below 1,000,000.
Find and display the count of the safe primes below 10,000,000.
Find and display (on one line) the first 40 unsafe primes.
Find and display the count of the unsafe primes below 1,000,000.
Find and display the count of the unsafe primes below 10,000,000.
(Optional) display the counts and "below numbers" with commas.
Show all output here.
Related Task
strong and weak primes.
Also see
The OEIS article: safe primes.
The OEIS article: unsafe primes.
|
#Nim
|
Nim
|
import sequtils, strutils
const N = 10_000_000
# Erathostene's Sieve. Only odd values are represented. False value means prime.
var sieve: array[N div 2 + 1, bool]
sieve[0] = true # 1 is not prime.
for i in 1..sieve.high:
if not sieve[i]:
let n = 2 * i + 1
for k in countup(n * n, N, 2 * n):
sieve[k shr 1] = true
proc isprime(n: Positive): bool =
## Check if a number is prime.
n == 2 or (n and 1) != 0 and not sieve[n shr 1]
proc classifyPrimes(): tuple[safe, unsafe: seq[int]] =
## Classify prime numbers in safe and unsafe numbers.
for n in 2..N:
if n.isprime():
if (n shr 1).isprime():
result[0].add n
else:
result[1].add n
when isMainModule:
let (safe, unsafe) = classifyPrimes()
echo "First 35 safe primes:"
echo safe[0..<35].join(" ")
echo "Count of safe primes below 1_000_000:",
($safe.filterIt(it < 1_000_000).len).insertSep(',').align(7)
echo "Count of safe primes below 10_000_000:",
($safe.filterIt(it < 10_000_000).len).insertSep(',').align(7)
echo "First 40 unsafe primes:"
echo unsafe[0..<40].join(" ")
echo "Count of unsafe primes below 1_000_000:",
($unsafe.filterIt(it < 1_000_000).len).insertSep(',').align(8)
echo "Count of unsafe primes below 10_000_000:",
($unsafe.filterIt(it < 10_000_000).len).insertSep(',').align(8)
|
http://rosettacode.org/wiki/Safe_primes_and_unsafe_primes
|
Safe primes and unsafe primes
|
Definitions
A safe prime is a prime p and where (p-1)/2 is also prime.
The corresponding prime (p-1)/2 is known as a Sophie Germain prime.
An unsafe prime is a prime p and where (p-1)/2 isn't a prime.
An unsafe prime is a prime that isn't a safe prime.
Task
Find and display (on one line) the first 35 safe primes.
Find and display the count of the safe primes below 1,000,000.
Find and display the count of the safe primes below 10,000,000.
Find and display (on one line) the first 40 unsafe primes.
Find and display the count of the unsafe primes below 1,000,000.
Find and display the count of the unsafe primes below 10,000,000.
(Optional) display the counts and "below numbers" with commas.
Show all output here.
Related Task
strong and weak primes.
Also see
The OEIS article: safe primes.
The OEIS article: unsafe primes.
|
#Pascal
|
Pascal
|
program Sophie;
{ Find and count Sophie Germain primes }
{ uses unit mp_prime out of mparith of Wolfgang Ehrhardt
* http://wolfgang-ehrhardt.de/misc_en.html#mparith
http://wolfgang-ehrhardt.de/mp_intro.html }
{$APPTYPE CONSOLE}
uses
mp_prime,sysutils;
var
pS0,pS1:TSieve;
procedure SafeOrNoSavePrimeOut(totCnt:NativeInt;CntSafe:boolean);
var
cnt,pr,pSG,testPr : NativeUint;
begin
prime_sieve_reset(pS0,1);
prime_sieve_reset(pS1,1);
cnt := 0;
// memorize prime of the sieve, because sometimes prime_sieve_next(pS1) is to far ahead.
testPr := prime_sieve_next(pS1);
IF CntSafe then
Begin
writeln('First ',totCnt,' safe primes');
repeat
pr := prime_sieve_next(pS0);
pSG := 2*pr+1;
while testPr< pSG do
testPr := prime_sieve_next(pS1);
if pSG = testPr then
begin
write(pSG,',');
inc(cnt);
end;
until cnt >= totCnt
end
else
Begin
writeln('First ',totCnt,' unsafe primes');
repeat
pr := prime_sieve_next(pS0);
pSG := (pr-1) DIV 2;
while testPr< pSG do
testPr := prime_sieve_next(pS1);
if pSG <> testPr then
begin
write(pr,',');
inc(cnt);
end;
until cnt >= totCnt;
end;
writeln(#8,#32);
end;
function CountSafePrimes(Limit:NativeInt):NativeUint;
var
cnt,pr,pSG,testPr : NativeUint;
begin
prime_sieve_reset(pS0,1);
prime_sieve_reset(pS1,1);
cnt := 0;
testPr := 0;
repeat
pr := prime_sieve_next(pS0);
pSG := 2*pr+1;
while testPr< pSG do
testPr := prime_sieve_next(pS1);
if pSG = testPr then
inc(cnt);
until pSG >= Limit;
CountSafePrimes := cnt;
end;
procedure CountSafePrimesOut(Limit:NativeUint);
Begin
writeln('there are ',CountSafePrimes(limit),' safe primes out of ',
primepi32(limit),' primes up to ',Limit);
end;
procedure CountUnSafePrimesOut(Limit:NativeUint);
var
prCnt: NativeUint;
Begin
prCnt := primepi32(limit);
writeln('there are ',prCnt-CountSafePrimes(limit),' unsafe primes out of ',
prCnt,' primes up to ',Limit);
end;
var
T1,T0 : INt64;
begin
T0 :=gettickcount64;
prime_sieve_init(pS0,1);
prime_sieve_init(pS1,1);
//Find and display (on one line) the first 35 safe primes.
SafeOrNoSavePrimeOut(35,true);
//Find and display the count of the safe primes below 1,000,000.
CountSafePrimesOut(1000*1000);
//Find and display the count of the safe primes below 10,000,000.
CountSafePrimesOut(10*1000*1000);
//Find and display (on one line) the first 40 unsafe primes.
SafeOrNoSavePrimeOut(40,false);
//Find and display the count of the unsafe primes below 1,000,000.
CountUnSafePrimesOut(1000*1000);
//Find and display the count of the unsafe primes below 10,000,000.
CountUnSafePrimesOut(10*1000*1000);
writeln;
CountSafePrimesOut(1000*1000*1000);
T1 :=gettickcount64;
writeln('runtime ',T1-T0,' ms');
end.
|
http://rosettacode.org/wiki/Runtime_evaluation/In_an_environment
|
Runtime evaluation/In an environment
|
x
x
x
Do so in a way which:
does not involve string manipulation of the input source code
is plausibly extensible to a runtime-chosen set of bindings rather than just x
does not make x a global variable
or note that these are impossible.
See also
For more general examples and language-specific details, see Eval.
Dynamic variable names is a similar task.
|
#ALGOL_68
|
ALGOL 68
|
PROC eval_with_x = (STRING code, INT a, b)STRING:
(INT x=a; evaluate(code) ) + (INT x=b; evaluate(code));
print((eval_with_x("2 ** x", 3, 5), new line))
|
http://rosettacode.org/wiki/Same_fringe
|
Same fringe
|
Write a routine that will compare the leaves ("fringe") of two binary trees to determine whether they are the same list of leaves when visited left-to-right. The structure or balance of the trees does not matter; only the number, order, and value of the leaves is important.
Any solution is allowed here, but many computer scientists will consider it inelegant to collect either fringe in its entirety before starting to collect the other one. In fact, this problem is usually proposed in various forums as a way to show off various forms of concurrency (tree-rotation algorithms have also been used to get around the need to collect one tree first). Thinking of it a slightly different way, an elegant solution is one that can perform the minimum amount of work to falsify the equivalence of the fringes when they differ somewhere in the middle, short-circuiting the unnecessary additional traversals and comparisons.
Any representation of a binary tree is allowed, as long as the nodes are orderable, and only downward links are used (for example, you may not use parent or sibling pointers to avoid recursion).
|
#Tcl
|
Tcl
|
package require Tcl 8.6
package require struct::tree
# A wrapper round a coroutine for iterating over the leaves of a tree in order
proc leafiterator {tree} {
coroutine coro[incr ::coroutines] apply {tree {
yield [info coroutine]
$tree walk [$tree rootname] node {
if {[$tree isleaf $node]} {
yield $node
}
}
yieldto break
}} $tree
}
# Compare two trees for equality of their leaf node names
proc samefringe {tree1 tree2} {
set c1 [leafiterator $tree1]
set c2 [leafiterator $tree2]
try {
while 1 {
if {[set l1 [$c1]] ne [set l2 [$c2]]} {
puts "$l1 != $l2"; # Just so we can see where we failed
return 0
}
}
return 1
} finally {
rename $c1 {}
rename $c2 {}
}
}
|
http://rosettacode.org/wiki/Sieve_of_Eratosthenes
|
Sieve of Eratosthenes
|
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task.
The Sieve of Eratosthenes is a simple algorithm that finds the prime numbers up to a given integer.
Task
Implement the Sieve of Eratosthenes algorithm, with the only allowed optimization that the outer loop can stop at the square root of the limit, and the inner loop may start at the square of the prime just found.
That means especially that you shouldn't optimize by using pre-computed wheels, i.e. don't assume you need only to cross out odd numbers (wheel based on 2), numbers equal to 1 or 5 modulo 6 (wheel based on 2 and 3), or similar wheels based on low primes.
If there's an easy way to add such a wheel based optimization, implement it as an alternative version.
Note
It is important that the sieve algorithm be the actual algorithm used to find prime numbers for the task.
Related tasks
Emirp primes
count in factors
prime decomposition
factors of an integer
extensible prime generator
primality by trial division
factors of a Mersenne number
trial factoring of a Mersenne number
partition an integer X into N primes
sequence of primes by Trial Division
|
#OCaml
|
OCaml
|
let sieve n =
let is_prime = Array.create n true in
let limit = truncate(sqrt (float (n - 1))) in
for i = 2 to limit do
if is_prime.(i) then
let j = ref (i*i) in
while !j < n do
is_prime.(!j) <- false;
j := !j + i;
done
done;
is_prime.(0) <- false;
is_prime.(1) <- false;
is_prime
|
http://rosettacode.org/wiki/Sailors,_coconuts_and_a_monkey_problem
|
Sailors, coconuts and a monkey problem
|
Five sailors are shipwrecked on an island and collect a large pile of coconuts during the day.
That night the first sailor wakes up and decides to take his first share early so tries to divide the pile of coconuts equally into five piles but finds that there is one coconut left over, so he tosses it to a monkey and then hides "his" one of the five equally sized piles of coconuts and pushes the other four piles together to form a single visible pile of coconuts again and goes to bed.
To cut a long story short, each of the sailors in turn gets up once during the night and performs the same actions of dividing the coconut pile into five, finding that one coconut is left over and giving that single remainder coconut to the monkey.
In the morning (after the surreptitious and separate action of each of the five sailors during the night), the remaining coconuts are divided into five equal piles for each of the sailors, whereupon it is found that the pile of coconuts divides equally amongst the sailors with no remainder. (Nothing for the monkey in the morning.)
The task
Calculate the minimum possible size of the initial pile of coconuts collected during the first day.
Use a method that assumes an answer is possible, and then applies the constraints of the tale to see if it is correct. (I.e. no applying some formula that generates the correct answer without integer divisions and remainders and tests on remainders; but constraint solvers are allowed.)
Calculate the size of the initial pile of coconuts if six sailors were marooned and went through a similar process (but split into six piles instead of five of course).
Show your answers here.
Extra credit (optional)
Give some indication of the number of coconuts each sailor hides during the night.
Note
Of course the tale is told in a world where the collection of any amount of coconuts in a day and multiple divisions of the pile, etc can occur in time fitting the story line, so as not to affect the mathematics.
The tale is also told in a version where the monkey also gets a coconut in the morning. This is not that tale!
C.f
Monkeys and Coconuts - Numberphile (Video) Analytical solution.
A002021: Pile of coconuts problem The On-Line Encyclopedia of Integer Sequences. (Although some of its references may use the alternate form of the tale).
|
#uBasic.2F4tH
|
uBasic/4tH
|
For n = 2 To 7
t = 0
For x = 1 Step 1 While t = 0
t = FUNC(_Total(n,x))
Next
Print n;": ";t;Tab(12); x - 1
Next
End
_Total Param(2)
Local(1)
b@ = b@ * a@
a@ = a@ - 1
For c@ = 0 To a@
If b@ % a@ Then
b@ = 0
Break
EndIf
b@ = b@ + 1 + b@ / a@
Next
Return (b@)
|
http://rosettacode.org/wiki/Sailors,_coconuts_and_a_monkey_problem
|
Sailors, coconuts and a monkey problem
|
Five sailors are shipwrecked on an island and collect a large pile of coconuts during the day.
That night the first sailor wakes up and decides to take his first share early so tries to divide the pile of coconuts equally into five piles but finds that there is one coconut left over, so he tosses it to a monkey and then hides "his" one of the five equally sized piles of coconuts and pushes the other four piles together to form a single visible pile of coconuts again and goes to bed.
To cut a long story short, each of the sailors in turn gets up once during the night and performs the same actions of dividing the coconut pile into five, finding that one coconut is left over and giving that single remainder coconut to the monkey.
In the morning (after the surreptitious and separate action of each of the five sailors during the night), the remaining coconuts are divided into five equal piles for each of the sailors, whereupon it is found that the pile of coconuts divides equally amongst the sailors with no remainder. (Nothing for the monkey in the morning.)
The task
Calculate the minimum possible size of the initial pile of coconuts collected during the first day.
Use a method that assumes an answer is possible, and then applies the constraints of the tale to see if it is correct. (I.e. no applying some formula that generates the correct answer without integer divisions and remainders and tests on remainders; but constraint solvers are allowed.)
Calculate the size of the initial pile of coconuts if six sailors were marooned and went through a similar process (but split into six piles instead of five of course).
Show your answers here.
Extra credit (optional)
Give some indication of the number of coconuts each sailor hides during the night.
Note
Of course the tale is told in a world where the collection of any amount of coconuts in a day and multiple divisions of the pile, etc can occur in time fitting the story line, so as not to affect the mathematics.
The tale is also told in a version where the monkey also gets a coconut in the morning. This is not that tale!
C.f
Monkeys and Coconuts - Numberphile (Video) Analytical solution.
A002021: Pile of coconuts problem The On-Line Encyclopedia of Integer Sequences. (Although some of its references may use the alternate form of the tale).
|
#VBA
|
VBA
|
Option Explicit
Public Sub coconuts()
Dim sailors As Integer
Dim share As Long
Dim finalshare As Integer
Dim minimum As Long, pile As Long
Dim i As Long, j As Integer
Debug.Print "Sailors", "Pile", "Final share"
For sailors = 2 To 6
i = 1
Do While True
pile = i
For j = 1 To sailors
If (pile - 1) Mod sailors <> 0 Then Exit For
share = (pile - 1) / sailors
pile = pile - share - 1
Next j
If j > sailors Then
If share Mod sailors = 0 And share > 0 Then
minimum = i
finalshare = pile / sailors
Exit Do
End If
End If
i = i + 1
Loop
Debug.Print sailors, minimum, finalshare
Next sailors
End Sub
|
http://rosettacode.org/wiki/Search_a_list_of_records
|
Search a list of records
|
Many programming languages provide convenient ways to look for a known value in a simple list of strings or numbers.
But what if the elements of the list are themselves compound records/objects/data-structures, and the search condition is more complex than a simple equality test?
Task[edit]
Write a function/method/etc. that can find the first element in a given list matching a given condition.
It should be as generic and reusable as possible.
(Of course if your programming language already provides such a feature, you can use that instead of recreating it.)
Then to demonstrate its functionality, create the data structure specified under #Data set, and perform on it the searches specified under #Test cases.
Data set
The data structure to be used contains the names and populations (in millions) of the 10 largest metropolitan areas in Africa, and looks as follows when represented in JSON:
[
{ "name": "Lagos", "population": 21.0 },
{ "name": "Cairo", "population": 15.2 },
{ "name": "Kinshasa-Brazzaville", "population": 11.3 },
{ "name": "Greater Johannesburg", "population": 7.55 },
{ "name": "Mogadishu", "population": 5.85 },
{ "name": "Khartoum-Omdurman", "population": 4.98 },
{ "name": "Dar Es Salaam", "population": 4.7 },
{ "name": "Alexandria", "population": 4.58 },
{ "name": "Abidjan", "population": 4.4 },
{ "name": "Casablanca", "population": 3.98 }
]
However, you shouldn't parse it from JSON, but rather represent it natively in your programming language.
The top-level data structure should be an ordered collection (i.e. a list, array, vector, or similar).
Each element in this list should be an associative collection that maps from keys to values (i.e. a struct, object, hash map, dictionary, or similar).
Each of them has two entries: One string value with key "name", and one numeric value with key "population".
You may rely on the list being sorted by population count, as long as you explain this to readers.
If any of that is impossible or unreasonable in your programming language, then feel free to deviate, as long as you explain your reasons in a comment above your solution.
Test cases
Search
Expected result
Find the (zero-based) index of the first city in the list whose name is "Dar Es Salaam"
6
Find the name of the first city in this list whose population is less than 5 million
Khartoum-Omdurman
Find the population of the first city in this list whose name starts with the letter "A"
4.58
Guidance
If your programming language supports higher-order programming, then the most elegant way to implement the requested functionality in a generic and reusable way, might be to write a function (maybe called "find_index" or similar), that takes two arguments:
The list to search through.
A function/lambda/closure (the so-called "predicate"), which will be applied in turn to each element in the list, and whose boolean return value defines whether that element matches the search requirement.
If this is not the approach which would be most natural or idiomatic in your language, explain why, and show what is.
Related tasks
Search a list
|
#Mathematica.2FWolfram_Language
|
Mathematica/Wolfram Language
|
data = Dataset[{
<|"name" -> "Lagos", "population" -> 21.|>,
<|"name" -> "Cairo", "population" -> 15.2|>,
<|"name" -> "Kinshasa-Brazzaville", "population" -> 11.3|>,
<|"name" -> "Greater Johannesburg", "population" -> 7.55|>,
<|"name" -> "Mogadishu", "population" -> 5.85|>,
<|"name" -> "Khartoum-Omdurman", "population" -> 4.98|>,
<|"name" -> "Dar Es Salaam", "population" -> 4.7|>,
<|"name" -> "Alexandria", "population" -> 4.58|>,
<|"name" -> "Abidjan", "population" -> 4.4|>,
<|"name" -> "Casablanca", "population" -> 3.98|>
}]
data[Position["Dar Es Salaam"], "name"][1, 1] - 1
data[Select[#population < 5 &]][1, "name"]
data[Select[StringMatchQ[#name, "A*"] &]][1, "population"]
|
http://rosettacode.org/wiki/Search_a_list
|
Search a list
|
Task[edit]
Find the index of a string (needle) in an indexable, ordered collection of strings (haystack).
Raise an exception if the needle is missing.
If there is more than one occurrence then return the smallest index to the needle.
Extra credit
Return the largest index to a needle that has multiple occurrences in the haystack.
See also
Search a list of records
|
#Bracmat
|
Bracmat
|
( return the largest index to a needle that has multiple
occurrences in the haystack and print the needle
: ?list
& ( !list:? haystack [?index ?
& out$("The word 'haystack' occurs at 1-based index" !index)
| out$"The word 'haystack' does not occur"
)
& ( !list
: ? %@?needle ? !needle ?
: ( ? !needle [?index (?&~)
| ?
& out
$ ( str
$ ( "The word '"
!needle
"' occurs more than once. The last 1-based index is "
!index
)
)
)
| out$"No word occurs more than once."
)
);
|
http://rosettacode.org/wiki/Runtime_evaluation
|
Runtime evaluation
|
Task
Demonstrate a language's ability for programs to execute code written in the language provided at runtime.
Show what kind of program fragments are permitted (e.g. expressions vs. statements), and how to get values in and out (e.g. environments, arguments, return values), if applicable what lexical/static environment the program is evaluated in, and what facilities for restricting (e.g. sandboxes, resource limits) or customizing (e.g. debugging facilities) the execution.
You may not invoke a separate evaluator program, or invoke a compiler and then its output, unless the interface of that program, and the syntax and means of executing it, are considered part of your language/library/platform.
For a more constrained task giving a specific program fragment to evaluate, see Eval in environment.
|
#JavaScript
|
JavaScript
|
var foo = eval('{value: 42}');
eval('var bar = "Hello, world!";');
typeof foo; // 'object'
typeof bar; // 'string'
|
http://rosettacode.org/wiki/Runtime_evaluation
|
Runtime evaluation
|
Task
Demonstrate a language's ability for programs to execute code written in the language provided at runtime.
Show what kind of program fragments are permitted (e.g. expressions vs. statements), and how to get values in and out (e.g. environments, arguments, return values), if applicable what lexical/static environment the program is evaluated in, and what facilities for restricting (e.g. sandboxes, resource limits) or customizing (e.g. debugging facilities) the execution.
You may not invoke a separate evaluator program, or invoke a compiler and then its output, unless the interface of that program, and the syntax and means of executing it, are considered part of your language/library/platform.
For a more constrained task giving a specific program fragment to evaluate, see Eval in environment.
|
#Jsish
|
Jsish
|
/* Runtime evaluation, in Jsish */
var foo = eval('{value: 42}');
eval('var bar = "Hello, world!";');
;typeof foo;
;foo.value;
;typeof bar;
;bar;
/*
=!EXPECTSTART!=
typeof foo ==> object
foo.value ==> 42
typeof bar ==> string
bar ==> Hello, world!
=!EXPECTEND!=
*/
|
http://rosettacode.org/wiki/Safe_primes_and_unsafe_primes
|
Safe primes and unsafe primes
|
Definitions
A safe prime is a prime p and where (p-1)/2 is also prime.
The corresponding prime (p-1)/2 is known as a Sophie Germain prime.
An unsafe prime is a prime p and where (p-1)/2 isn't a prime.
An unsafe prime is a prime that isn't a safe prime.
Task
Find and display (on one line) the first 35 safe primes.
Find and display the count of the safe primes below 1,000,000.
Find and display the count of the safe primes below 10,000,000.
Find and display (on one line) the first 40 unsafe primes.
Find and display the count of the unsafe primes below 1,000,000.
Find and display the count of the unsafe primes below 10,000,000.
(Optional) display the counts and "below numbers" with commas.
Show all output here.
Related Task
strong and weak primes.
Also see
The OEIS article: safe primes.
The OEIS article: unsafe primes.
|
#Perl
|
Perl
|
use ntheory qw(forprimes is_prime);
my $upto = 1e7;
my %class = ( safe => [], unsafe => [2] );
forprimes {
push @{$class{ is_prime(($_-1)>>1) ? 'safe' : 'unsafe' }}, $_;
} 3, $upto;
for (['safe', 35], ['unsafe', 40]) {
my($type, $quantity) = @$_;
print "The first $quantity $type primes are:\n";
print join(" ", map { comma($class{$type}->[$_-1]) } 1..$quantity), "\n";
for my $q ($upto/10, $upto) {
my $n = scalar(grep { $_ <= $q } @{$class{$type}});
printf "The number of $type primes up to %s: %s\n", comma($q), comma($n);
}
}
sub comma {
(my $s = reverse shift) =~ s/(.{3})/$1,/g;
$s =~ s/,(-?)$/$1/;
$s = reverse $s;
}
|
http://rosettacode.org/wiki/Runtime_evaluation/In_an_environment
|
Runtime evaluation/In an environment
|
x
x
x
Do so in a way which:
does not involve string manipulation of the input source code
is plausibly extensible to a runtime-chosen set of bindings rather than just x
does not make x a global variable
or note that these are impossible.
See also
For more general examples and language-specific details, see Eval.
Dynamic variable names is a similar task.
|
#AppleScript
|
AppleScript
|
on task_with_x(pgrm, x1, x2)
local rslt1, rslt2
set rslt1 to run script pgrm with parameters {x1}
set rslt2 to run script pgrm with parameters {x2}
rslt2 - rslt1
end task_with_x
|
http://rosettacode.org/wiki/Runtime_evaluation/In_an_environment
|
Runtime evaluation/In an environment
|
x
x
x
Do so in a way which:
does not involve string manipulation of the input source code
is plausibly extensible to a runtime-chosen set of bindings rather than just x
does not make x a global variable
or note that these are impossible.
See also
For more general examples and language-specific details, see Eval.
Dynamic variable names is a similar task.
|
#AutoHotkey
|
AutoHotkey
|
msgbox % first := evalWithX("x + 4", 5)
msgbox % second := evalWithX("x + 4", 6)
msgbox % second - first
return
evalWithX(expression, xvalue)
{
global script
script =
(
expression(){
x = %xvalue% ; := would need quotes
return %expression%
}
)
renameFunction("expression", "") ; remove any previous expressions
gosub load ; cannot use addScript inside a function yet
exp := "expression"
return %exp%()
}
load:
DllCall(A_AhkPath "\addScript","Str",script,"Uchar",0,"Cdecl UInt")
return
renameFunction(funcName, newname){
static
x%newname% := newname ; store newname in a static variable so its memory is not freed
strput(newname, &x%newname%, strlen(newname) + 1)
if fnp := FindFunc(funcName)
numput(&x%newname%, fnp+0, 0, "uint")
}
|
http://rosettacode.org/wiki/Same_fringe
|
Same fringe
|
Write a routine that will compare the leaves ("fringe") of two binary trees to determine whether they are the same list of leaves when visited left-to-right. The structure or balance of the trees does not matter; only the number, order, and value of the leaves is important.
Any solution is allowed here, but many computer scientists will consider it inelegant to collect either fringe in its entirety before starting to collect the other one. In fact, this problem is usually proposed in various forums as a way to show off various forms of concurrency (tree-rotation algorithms have also been used to get around the need to collect one tree first). Thinking of it a slightly different way, an elegant solution is one that can perform the minimum amount of work to falsify the equivalence of the fringes when they differ somewhere in the middle, short-circuiting the unnecessary additional traversals and comparisons.
Any representation of a binary tree is allowed, as long as the nodes are orderable, and only downward links are used (for example, you may not use parent or sibling pointers to avoid recursion).
|
#Wren
|
Wren
|
import "/dynamic" for Struct
var Node = Struct.create("Node", ["key", "left", "right"])
// 'leaves' returns a fiber that yields the leaves of the tree
// until all leaves have been received.
var leaves = Fn.new { |t|
// recursive function to walk tree
var f
f = Fn.new { |n|
if (!n) return
// leaves are identified by having no children
if (!n.left && !n.right) {
Fiber.yield(n.key)
} else {
f.call(n.left)
f.call(n.right)
}
}
// return a fiber which walks the tree
return Fiber.new { f.call(t) }
}
var sameFringe = Fn.new { |t1, t2|
var f1 = leaves.call(t1)
var f2 = leaves.call(t2)
var l1
while (l1 = f1.call()) {
// both trees must yield a leaf, and the leaves must be equal
var l2
if ((l2 = f2.call()) && (!l2 || l1 != l2)) return false
}
// there must be nothing left in f2 after consuming all of f1
return !f2.call()
}
// the different shapes of the trees is shown with indention,
// the leaves being easy to spot by the key
var t1 = Node.new(3,
Node.new(1,
Node.new(1, null, null),
Node.new(2, null, null)
),
Node.new(8,
Node.new(5, null, null),
Node.new(13, null, null)
)
)
// t2 with negative values for internal nodes that can't possibly match
// positive values in t1, just to show that only leaves are being compared.
var t2 = Node.new(-8,
Node.new(-3,
Node.new(-1,
Node.new(1, null, null),
Node.new(2, null, null)
),
Node.new(5, null,null)
),
Node.new(13, null, null)
)
// t3 as t2 but with a different leave
var t3 = Node.new(-8,
Node.new(-3,
Node.new(-1,
Node.new(1, null, null),
Node.new(2, null, null)
),
Node.new(5, null,null)
),
Node.new(14, null, null) // 14 instead of 13
)
System.print("tree 1 and tree 2 have the same leaves: %(sameFringe.call(t1, t2))")
System.print("tree 1 and tree 3 have the same leaves: %(sameFringe.call(t1, t3))")
System.print("tree 2 and tree 3 have the same leaves: %(sameFringe.call(t2, t3))")
|
http://rosettacode.org/wiki/Sieve_of_Eratosthenes
|
Sieve of Eratosthenes
|
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task.
The Sieve of Eratosthenes is a simple algorithm that finds the prime numbers up to a given integer.
Task
Implement the Sieve of Eratosthenes algorithm, with the only allowed optimization that the outer loop can stop at the square root of the limit, and the inner loop may start at the square of the prime just found.
That means especially that you shouldn't optimize by using pre-computed wheels, i.e. don't assume you need only to cross out odd numbers (wheel based on 2), numbers equal to 1 or 5 modulo 6 (wheel based on 2 and 3), or similar wheels based on low primes.
If there's an easy way to add such a wheel based optimization, implement it as an alternative version.
Note
It is important that the sieve algorithm be the actual algorithm used to find prime numbers for the task.
Related tasks
Emirp primes
count in factors
prime decomposition
factors of an integer
extensible prime generator
primality by trial division
factors of a Mersenne number
trial factoring of a Mersenne number
partition an integer X into N primes
sequence of primes by Trial Division
|
#Oforth
|
Oforth
|
: eratosthenes(n)
| i j |
ListBuffer newSize(n) dup add(null) seqFrom(2, n) over addAll
2 n sqrt asInteger for: i [
dup at(i) ifNotNull: [ i sq n i step: j [ dup put(j, null) ] ]
]
filter(#notNull) ;
|
http://rosettacode.org/wiki/Sailors,_coconuts_and_a_monkey_problem
|
Sailors, coconuts and a monkey problem
|
Five sailors are shipwrecked on an island and collect a large pile of coconuts during the day.
That night the first sailor wakes up and decides to take his first share early so tries to divide the pile of coconuts equally into five piles but finds that there is one coconut left over, so he tosses it to a monkey and then hides "his" one of the five equally sized piles of coconuts and pushes the other four piles together to form a single visible pile of coconuts again and goes to bed.
To cut a long story short, each of the sailors in turn gets up once during the night and performs the same actions of dividing the coconut pile into five, finding that one coconut is left over and giving that single remainder coconut to the monkey.
In the morning (after the surreptitious and separate action of each of the five sailors during the night), the remaining coconuts are divided into five equal piles for each of the sailors, whereupon it is found that the pile of coconuts divides equally amongst the sailors with no remainder. (Nothing for the monkey in the morning.)
The task
Calculate the minimum possible size of the initial pile of coconuts collected during the first day.
Use a method that assumes an answer is possible, and then applies the constraints of the tale to see if it is correct. (I.e. no applying some formula that generates the correct answer without integer divisions and remainders and tests on remainders; but constraint solvers are allowed.)
Calculate the size of the initial pile of coconuts if six sailors were marooned and went through a similar process (but split into six piles instead of five of course).
Show your answers here.
Extra credit (optional)
Give some indication of the number of coconuts each sailor hides during the night.
Note
Of course the tale is told in a world where the collection of any amount of coconuts in a day and multiple divisions of the pile, etc can occur in time fitting the story line, so as not to affect the mathematics.
The tale is also told in a version where the monkey also gets a coconut in the morning. This is not that tale!
C.f
Monkeys and Coconuts - Numberphile (Video) Analytical solution.
A002021: Pile of coconuts problem The On-Line Encyclopedia of Integer Sequences. (Although some of its references may use the alternate form of the tale).
|
#Wren
|
Wren
|
var coconuts = 11
for (ns in 2..9) {
var hidden = List.filled(ns, 0)
coconuts = (coconuts/ns).floor * ns + 1
while (true) {
var nc = coconuts
var outer = false
for (s in 1..ns) {
if (nc%ns == 1) {
hidden[s-1] = (nc/ns).floor
nc = nc - hidden[s-1] - 1
if (s == ns && nc%ns == 0) {
System.print("%(ns) sailors require a minimum of %(coconuts) coconuts")
for (t in 1..ns) System.print("\tSailor %(t) hides %(hidden[t-1])")
System.print("\tThe monkey gets %(ns)")
System.print("\tFinally, each sailor takes %((nc/ns).floor)\n")
outer = true
break
}
} else {
break
}
}
if (outer) break
coconuts = coconuts + ns
}
}
|
http://rosettacode.org/wiki/Search_a_list_of_records
|
Search a list of records
|
Many programming languages provide convenient ways to look for a known value in a simple list of strings or numbers.
But what if the elements of the list are themselves compound records/objects/data-structures, and the search condition is more complex than a simple equality test?
Task[edit]
Write a function/method/etc. that can find the first element in a given list matching a given condition.
It should be as generic and reusable as possible.
(Of course if your programming language already provides such a feature, you can use that instead of recreating it.)
Then to demonstrate its functionality, create the data structure specified under #Data set, and perform on it the searches specified under #Test cases.
Data set
The data structure to be used contains the names and populations (in millions) of the 10 largest metropolitan areas in Africa, and looks as follows when represented in JSON:
[
{ "name": "Lagos", "population": 21.0 },
{ "name": "Cairo", "population": 15.2 },
{ "name": "Kinshasa-Brazzaville", "population": 11.3 },
{ "name": "Greater Johannesburg", "population": 7.55 },
{ "name": "Mogadishu", "population": 5.85 },
{ "name": "Khartoum-Omdurman", "population": 4.98 },
{ "name": "Dar Es Salaam", "population": 4.7 },
{ "name": "Alexandria", "population": 4.58 },
{ "name": "Abidjan", "population": 4.4 },
{ "name": "Casablanca", "population": 3.98 }
]
However, you shouldn't parse it from JSON, but rather represent it natively in your programming language.
The top-level data structure should be an ordered collection (i.e. a list, array, vector, or similar).
Each element in this list should be an associative collection that maps from keys to values (i.e. a struct, object, hash map, dictionary, or similar).
Each of them has two entries: One string value with key "name", and one numeric value with key "population".
You may rely on the list being sorted by population count, as long as you explain this to readers.
If any of that is impossible or unreasonable in your programming language, then feel free to deviate, as long as you explain your reasons in a comment above your solution.
Test cases
Search
Expected result
Find the (zero-based) index of the first city in the list whose name is "Dar Es Salaam"
6
Find the name of the first city in this list whose population is less than 5 million
Khartoum-Omdurman
Find the population of the first city in this list whose name starts with the letter "A"
4.58
Guidance
If your programming language supports higher-order programming, then the most elegant way to implement the requested functionality in a generic and reusable way, might be to write a function (maybe called "find_index" or similar), that takes two arguments:
The list to search through.
A function/lambda/closure (the so-called "predicate"), which will be applied in turn to each element in the list, and whose boolean return value defines whether that element matches the search requirement.
If this is not the approach which would be most natural or idiomatic in your language, explain why, and show what is.
Related tasks
Search a list
|
#Nim
|
Nim
|
template findIt(data, pred: untyped): int =
## Return the index of the first element in "data" satisfying
## the predicate "pred" or -1 if no such element is found.
var result = -1
for i, it {.inject.} in data.pairs:
if pred:
result = i
break
result
when isMainModule:
import strutils
type City = tuple[name: string; population: float]
const Cities: seq[City] = @[("Lagos", 21.0),
("Cairo", 15.2),
("Kinshasa-Brazzaville", 11.3),
("Greater Johannesburg", 7.55),
("Mogadishu", 5.85),
("Khartoum-Omdurman", 4.98),
("Dar Es Salaam", 4.7),
("Alexandria", 4.58),
("Abidjan", 4.4),
("Casablanca", 3.98)]
echo "Index of the first city whose name is “Dar Es Salaam”: ",
Cities.findIt(it.name == "Dar Es Salaam")
let idx1 = Cities.findIt(it.population < 5)
echo "Name of the first city whose population is less than 5 million: ",
if idx1 == -1: "<none>" else: Cities[idx1].name
let idx2 = Cities.findIt(it.name.startsWith("A"))
echo "Population of the first city whose name starts with the letter “A”: ",
if idx2 == -1: "<none>" else: $Cities[idx2].population
|
http://rosettacode.org/wiki/Search_a_list
|
Search a list
|
Task[edit]
Find the index of a string (needle) in an indexable, ordered collection of strings (haystack).
Raise an exception if the needle is missing.
If there is more than one occurrence then return the smallest index to the needle.
Extra credit
Return the largest index to a needle that has multiple occurrences in the haystack.
See also
Search a list of records
|
#Burlesque
|
Burlesque
|
blsq ) {"Zig" "Zag" "Wally" "Bush" "Ronald" "Bush"}"Bush"Fi
3
|
http://rosettacode.org/wiki/Runtime_evaluation
|
Runtime evaluation
|
Task
Demonstrate a language's ability for programs to execute code written in the language provided at runtime.
Show what kind of program fragments are permitted (e.g. expressions vs. statements), and how to get values in and out (e.g. environments, arguments, return values), if applicable what lexical/static environment the program is evaluated in, and what facilities for restricting (e.g. sandboxes, resource limits) or customizing (e.g. debugging facilities) the execution.
You may not invoke a separate evaluator program, or invoke a compiler and then its output, unless the interface of that program, and the syntax and means of executing it, are considered part of your language/library/platform.
For a more constrained task giving a specific program fragment to evaluate, see Eval in environment.
|
#Julia
|
Julia
|
include("myfile.jl")
|
http://rosettacode.org/wiki/Runtime_evaluation
|
Runtime evaluation
|
Task
Demonstrate a language's ability for programs to execute code written in the language provided at runtime.
Show what kind of program fragments are permitted (e.g. expressions vs. statements), and how to get values in and out (e.g. environments, arguments, return values), if applicable what lexical/static environment the program is evaluated in, and what facilities for restricting (e.g. sandboxes, resource limits) or customizing (e.g. debugging facilities) the execution.
You may not invoke a separate evaluator program, or invoke a compiler and then its output, unless the interface of that program, and the syntax and means of executing it, are considered part of your language/library/platform.
For a more constrained task giving a specific program fragment to evaluate, see Eval in environment.
|
#Kotlin
|
Kotlin
|
$ kotlinc
Welcome to Kotlin version 1.2.31 (JRE 1.8.0_162-8u162-b12-0ubuntu0.16.04.2-b12)
Type :help for help, :quit for quit
>>> 20 + 22
42
>>> 5 * Math.sqrt(81.0)
45.0
>>> fun triple(x: Int) = x * 3
>>> triple(16)
48
>>> :quit
|
http://rosettacode.org/wiki/Runtime_evaluation
|
Runtime evaluation
|
Task
Demonstrate a language's ability for programs to execute code written in the language provided at runtime.
Show what kind of program fragments are permitted (e.g. expressions vs. statements), and how to get values in and out (e.g. environments, arguments, return values), if applicable what lexical/static environment the program is evaluated in, and what facilities for restricting (e.g. sandboxes, resource limits) or customizing (e.g. debugging facilities) the execution.
You may not invoke a separate evaluator program, or invoke a compiler and then its output, unless the interface of that program, and the syntax and means of executing it, are considered part of your language/library/platform.
For a more constrained task giving a specific program fragment to evaluate, see Eval in environment.
|
#Lasso
|
Lasso
|
//code, fragment name, autocollect, inplaintext
local(mycode = "'Hello world, it is '+date")
sourcefile('['+#mycode+']','arbritraty_name', true, true)->invoke
'\r'
var(x = 100)
local(mycode = "Outside Lasso\r['Hello world, var x is '+var(x)]")
// autocollect (3rd param): return any output generated
// inplaintext (4th param): if true, assumes this is mixed Lasso and plain text,
// requires Lasso code to be in square brackets or other supported code block demarkation.
sourcefile(#mycode,'arbritraty_name', true, true)->invoke
'\r'
var(y = 2)
local(mycode = "'Hello world, is there output?\r'
var(x) *= var(y)")
// autocollect (3rd param): as false, no output returned
// inplaintext (4th param): as false, assumes this is Lasso code, no mixed-mode Lasso and text.
sourcefile(#mycode,'arbritraty_name', false, false)->invoke
'var x is now: '+$x
'\r'
var(z = 3)
local(mycode = "var(x) *= var(z)")
sourcefile(#mycode,'arbritraty_name', false, false)->invoke
'var x is now: '+$x
|
http://rosettacode.org/wiki/Safe_primes_and_unsafe_primes
|
Safe primes and unsafe primes
|
Definitions
A safe prime is a prime p and where (p-1)/2 is also prime.
The corresponding prime (p-1)/2 is known as a Sophie Germain prime.
An unsafe prime is a prime p and where (p-1)/2 isn't a prime.
An unsafe prime is a prime that isn't a safe prime.
Task
Find and display (on one line) the first 35 safe primes.
Find and display the count of the safe primes below 1,000,000.
Find and display the count of the safe primes below 10,000,000.
Find and display (on one line) the first 40 unsafe primes.
Find and display the count of the unsafe primes below 1,000,000.
Find and display the count of the unsafe primes below 10,000,000.
(Optional) display the counts and "below numbers" with commas.
Show all output here.
Related Task
strong and weak primes.
Also see
The OEIS article: safe primes.
The OEIS article: unsafe primes.
|
#Phix
|
Phix
|
with javascript_semantics
sequence safe = {}, unsafe = {}
function filter_range(integer lo, hi)
while true do
integer p = get_prime(lo)
if p>hi then return lo end if
if p>2 and is_prime((p-1)/2) then
safe &= p
else
unsafe &= p
end if
lo += 1
end while
end function
integer lo = filter_range(1,1_000_000),
ls = length(safe),
lu = length(unsafe)
{} = filter_range(lo,10_000_000)
printf(1,"The first 35 safe primes: %v\n",{safe[1..35]})
printf(1,"Count of safe primes below 1,000,000: %,d\n",ls)
printf(1,"Count of safe primes below 10,000,000: %,d\n",length(safe))
printf(1,"The first 40 unsafe primes: %v\n",{unsafe[1..40]})
printf(1,"Count of unsafe primes below 1,000,000: %,d\n",lu)
printf(1,"Count of unsafe primes below 10,000,000: %,d\n",length(unsafe))
|
http://rosettacode.org/wiki/Runtime_evaluation/In_an_environment
|
Runtime evaluation/In an environment
|
x
x
x
Do so in a way which:
does not involve string manipulation of the input source code
is plausibly extensible to a runtime-chosen set of bindings rather than just x
does not make x a global variable
or note that these are impossible.
See also
For more general examples and language-specific details, see Eval.
Dynamic variable names is a similar task.
|
#BBC_BASIC
|
BBC BASIC
|
expression$ = "x^2 - 7"
one = FN_eval_with_x(expression$, 1.2)
two = FN_eval_with_x(expression$, 3.4)
PRINT two - one
END
DEF FN_eval_with_x(expr$, x)
= EVAL(expr$)
|
http://rosettacode.org/wiki/Runtime_evaluation/In_an_environment
|
Runtime evaluation/In an environment
|
x
x
x
Do so in a way which:
does not involve string manipulation of the input source code
is plausibly extensible to a runtime-chosen set of bindings rather than just x
does not make x a global variable
or note that these are impossible.
See also
For more general examples and language-specific details, see Eval.
Dynamic variable names is a similar task.
|
#Bracmat
|
Bracmat
|
( ( eval-with-x
= code a b argument
. !arg:((=?code),?a,?b,?argument)
& (!b:?x&!code$!argument)
+ -1*(!a:?x&!code$!argument)
)
& out$(eval-with-x$((='(.$x^!arg)),3,5,2))
& out$(eval-with-x$((='(.$x^!arg)),12,13,2))
);
|
http://rosettacode.org/wiki/Runtime_evaluation/In_an_environment
|
Runtime evaluation/In an environment
|
x
x
x
Do so in a way which:
does not involve string manipulation of the input source code
is plausibly extensible to a runtime-chosen set of bindings rather than just x
does not make x a global variable
or note that these are impossible.
See also
For more general examples and language-specific details, see Eval.
Dynamic variable names is a similar task.
|
#Clojure
|
Clojure
|
(def ^:dynamic x nil)
(defn eval-with-x [program a b]
(- (binding [x b] (eval program))
(binding [x a] (eval program))))
|
http://rosettacode.org/wiki/Same_fringe
|
Same fringe
|
Write a routine that will compare the leaves ("fringe") of two binary trees to determine whether they are the same list of leaves when visited left-to-right. The structure or balance of the trees does not matter; only the number, order, and value of the leaves is important.
Any solution is allowed here, but many computer scientists will consider it inelegant to collect either fringe in its entirety before starting to collect the other one. In fact, this problem is usually proposed in various forums as a way to show off various forms of concurrency (tree-rotation algorithms have also been used to get around the need to collect one tree first). Thinking of it a slightly different way, an elegant solution is one that can perform the minimum amount of work to falsify the equivalence of the fringes when they differ somewhere in the middle, short-circuiting the unnecessary additional traversals and comparisons.
Any representation of a binary tree is allowed, as long as the nodes are orderable, and only downward links are used (for example, you may not use parent or sibling pointers to avoid recursion).
|
#zkl
|
zkl
|
var G=Utils.Generator;
//Tree: (node,left,right) or (leaf) or (node,left) ...
aTree := T(1, T(2, T(4, T(7)), T(5)), T(3, T(6, T(8), T(9))));
bTree := aTree;
println("aTree and bTree ",sameFringe(aTree,bTree) and "have" or "don't have",
" the same leaves.");
cTree := T(1, T(2, T(4, T(7)), T(5)), T(3, T(6, T(8))));
dTree := T(1, T(2, T(4, T(7)), T(5)), T(3, T(6, T(8), T(9))));
println("cTree and dTree ",sameFringe(cTree,dTree) and "have"or"don't have",
" the same leaves.");
fcn sameFringe(a,b){ same(G(genLeaves,a),G(genLeaves,b)) }
fcn same(g1,g2){ //(Generator,Generator)
foreach n1,n2 in (g1.zip(g2)){ //-->(int,int) ...
if(n1 != n2) return(); // == return(Void)
}
return(not (g2._next() or g2._next())); //-->False if g1 or g2 has leaves
}
fcn genLeaves(tree){
switch(tree.len()){ // (), (leaf), (node,left, [right])
case(1){ vm.yield(tree[0]) } // leaf: int
case(2){ genLeaves(tree[1]); }
else { genLeaves(tree[1]); genLeaves(tree[2]); }
}
}
|
http://rosettacode.org/wiki/Sieve_of_Eratosthenes
|
Sieve of Eratosthenes
|
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task.
The Sieve of Eratosthenes is a simple algorithm that finds the prime numbers up to a given integer.
Task
Implement the Sieve of Eratosthenes algorithm, with the only allowed optimization that the outer loop can stop at the square root of the limit, and the inner loop may start at the square of the prime just found.
That means especially that you shouldn't optimize by using pre-computed wheels, i.e. don't assume you need only to cross out odd numbers (wheel based on 2), numbers equal to 1 or 5 modulo 6 (wheel based on 2 and 3), or similar wheels based on low primes.
If there's an easy way to add such a wheel based optimization, implement it as an alternative version.
Note
It is important that the sieve algorithm be the actual algorithm used to find prime numbers for the task.
Related tasks
Emirp primes
count in factors
prime decomposition
factors of an integer
extensible prime generator
primality by trial division
factors of a Mersenne number
trial factoring of a Mersenne number
partition an integer X into N primes
sequence of primes by Trial Division
|
#Ol
|
Ol
|
(define all (iota 999 2))
(print
(let main ((left '()) (right all))
(if (null? right)
(reverse left)
(unless (car right)
(main left (cdr right))
(let loop ((l '()) (r right) (n 0) (every (car right)))
(if (null? r)
(let ((l (reverse l)))
(main (cons (car l) left) (cdr l)))
(if (eq? n every)
(loop (cons #false l) (cdr r) 1 every)
(loop (cons (car r) l) (cdr r) (+ n 1) every)))))))
)
|
http://rosettacode.org/wiki/Sailors,_coconuts_and_a_monkey_problem
|
Sailors, coconuts and a monkey problem
|
Five sailors are shipwrecked on an island and collect a large pile of coconuts during the day.
That night the first sailor wakes up and decides to take his first share early so tries to divide the pile of coconuts equally into five piles but finds that there is one coconut left over, so he tosses it to a monkey and then hides "his" one of the five equally sized piles of coconuts and pushes the other four piles together to form a single visible pile of coconuts again and goes to bed.
To cut a long story short, each of the sailors in turn gets up once during the night and performs the same actions of dividing the coconut pile into five, finding that one coconut is left over and giving that single remainder coconut to the monkey.
In the morning (after the surreptitious and separate action of each of the five sailors during the night), the remaining coconuts are divided into five equal piles for each of the sailors, whereupon it is found that the pile of coconuts divides equally amongst the sailors with no remainder. (Nothing for the monkey in the morning.)
The task
Calculate the minimum possible size of the initial pile of coconuts collected during the first day.
Use a method that assumes an answer is possible, and then applies the constraints of the tale to see if it is correct. (I.e. no applying some formula that generates the correct answer without integer divisions and remainders and tests on remainders; but constraint solvers are allowed.)
Calculate the size of the initial pile of coconuts if six sailors were marooned and went through a similar process (but split into six piles instead of five of course).
Show your answers here.
Extra credit (optional)
Give some indication of the number of coconuts each sailor hides during the night.
Note
Of course the tale is told in a world where the collection of any amount of coconuts in a day and multiple divisions of the pile, etc can occur in time fitting the story line, so as not to affect the mathematics.
The tale is also told in a version where the monkey also gets a coconut in the morning. This is not that tale!
C.f
Monkeys and Coconuts - Numberphile (Video) Analytical solution.
A002021: Pile of coconuts problem The On-Line Encyclopedia of Integer Sequences. (Although some of its references may use the alternate form of the tale).
|
#Yabasic
|
Yabasic
|
coconuts = 11
for ns = 2 to 9
dim hidden(ns)
coconuts = int(coconuts / ns) * ns + 1
do
nc = coconuts
for s = 1 to ns+1
if mod(nc, ns) = 1 then
hidden(s-1) = int(nc / ns)
nc = nc - (hidden(s-1) + 1)
if s = ns and not mod(nc, ns) then
print ns, " sailors require a minimum of ", coconuts, " coconuts"
for t = 1 to ns
print "\tSailor ", t, " hides ", hidden(t - 1)
next
print "\tThe monkey gets ", ns
print "\tFinally, each sailor takes ", int(nc / ns), "\n"
break 2
end if
else
break
end if
next
coconuts = coconuts + ns
loop
next
|
http://rosettacode.org/wiki/Sailors,_coconuts_and_a_monkey_problem
|
Sailors, coconuts and a monkey problem
|
Five sailors are shipwrecked on an island and collect a large pile of coconuts during the day.
That night the first sailor wakes up and decides to take his first share early so tries to divide the pile of coconuts equally into five piles but finds that there is one coconut left over, so he tosses it to a monkey and then hides "his" one of the five equally sized piles of coconuts and pushes the other four piles together to form a single visible pile of coconuts again and goes to bed.
To cut a long story short, each of the sailors in turn gets up once during the night and performs the same actions of dividing the coconut pile into five, finding that one coconut is left over and giving that single remainder coconut to the monkey.
In the morning (after the surreptitious and separate action of each of the five sailors during the night), the remaining coconuts are divided into five equal piles for each of the sailors, whereupon it is found that the pile of coconuts divides equally amongst the sailors with no remainder. (Nothing for the monkey in the morning.)
The task
Calculate the minimum possible size of the initial pile of coconuts collected during the first day.
Use a method that assumes an answer is possible, and then applies the constraints of the tale to see if it is correct. (I.e. no applying some formula that generates the correct answer without integer divisions and remainders and tests on remainders; but constraint solvers are allowed.)
Calculate the size of the initial pile of coconuts if six sailors were marooned and went through a similar process (but split into six piles instead of five of course).
Show your answers here.
Extra credit (optional)
Give some indication of the number of coconuts each sailor hides during the night.
Note
Of course the tale is told in a world where the collection of any amount of coconuts in a day and multiple divisions of the pile, etc can occur in time fitting the story line, so as not to affect the mathematics.
The tale is also told in a version where the monkey also gets a coconut in the morning. This is not that tale!
C.f
Monkeys and Coconuts - Numberphile (Video) Analytical solution.
A002021: Pile of coconuts problem The On-Line Encyclopedia of Integer Sequences. (Although some of its references may use the alternate form of the tale).
|
#zkl
|
zkl
|
fcn monkey_coconuts(sailors=5){
nuts,wakes:=sailors,List();
while(True){
n0:=nuts; wakes.clear();
foreach sailor in (sailors + 1){
portion, remainder := n0.divr(sailors);
wakes.append(T(n0, portion, remainder));
if(portion <= 0 or remainder != (sailor != sailors).toInt()){
nuts += 1;
break;
}
n0 = n0 - portion - remainder;
}
fallthrough{ break }
}
return(nuts, wakes)
}
foreach sailors in ([5..6]){
nuts, wake_stats := monkey_coconuts(sailors);
println("For %d sailors the initial nut count is %,d".fmt(sailors, nuts));
println("On each waking, the nut count, portion taken, and monkeys share are:\n ",
wake_stats.concat("\n "));
}
|
http://rosettacode.org/wiki/Search_a_list_of_records
|
Search a list of records
|
Many programming languages provide convenient ways to look for a known value in a simple list of strings or numbers.
But what if the elements of the list are themselves compound records/objects/data-structures, and the search condition is more complex than a simple equality test?
Task[edit]
Write a function/method/etc. that can find the first element in a given list matching a given condition.
It should be as generic and reusable as possible.
(Of course if your programming language already provides such a feature, you can use that instead of recreating it.)
Then to demonstrate its functionality, create the data structure specified under #Data set, and perform on it the searches specified under #Test cases.
Data set
The data structure to be used contains the names and populations (in millions) of the 10 largest metropolitan areas in Africa, and looks as follows when represented in JSON:
[
{ "name": "Lagos", "population": 21.0 },
{ "name": "Cairo", "population": 15.2 },
{ "name": "Kinshasa-Brazzaville", "population": 11.3 },
{ "name": "Greater Johannesburg", "population": 7.55 },
{ "name": "Mogadishu", "population": 5.85 },
{ "name": "Khartoum-Omdurman", "population": 4.98 },
{ "name": "Dar Es Salaam", "population": 4.7 },
{ "name": "Alexandria", "population": 4.58 },
{ "name": "Abidjan", "population": 4.4 },
{ "name": "Casablanca", "population": 3.98 }
]
However, you shouldn't parse it from JSON, but rather represent it natively in your programming language.
The top-level data structure should be an ordered collection (i.e. a list, array, vector, or similar).
Each element in this list should be an associative collection that maps from keys to values (i.e. a struct, object, hash map, dictionary, or similar).
Each of them has two entries: One string value with key "name", and one numeric value with key "population".
You may rely on the list being sorted by population count, as long as you explain this to readers.
If any of that is impossible or unreasonable in your programming language, then feel free to deviate, as long as you explain your reasons in a comment above your solution.
Test cases
Search
Expected result
Find the (zero-based) index of the first city in the list whose name is "Dar Es Salaam"
6
Find the name of the first city in this list whose population is less than 5 million
Khartoum-Omdurman
Find the population of the first city in this list whose name starts with the letter "A"
4.58
Guidance
If your programming language supports higher-order programming, then the most elegant way to implement the requested functionality in a generic and reusable way, might be to write a function (maybe called "find_index" or similar), that takes two arguments:
The list to search through.
A function/lambda/closure (the so-called "predicate"), which will be applied in turn to each element in the list, and whose boolean return value defines whether that element matches the search requirement.
If this is not the approach which would be most natural or idiomatic in your language, explain why, and show what is.
Related tasks
Search a list
|
#OCaml
|
OCaml
|
#load "str.cma"
(* We are going to use literally a list of records as said in the title of the
* task. *)
(* First: Definition of the record type. *)
type city = {
name : string;
population : float
}
(* Second: The actual list of records containing the data. *)
let cities = [
{ name = "Lagos"; population = 21.0 };
{ name = "Cairo"; population = 15.2 };
{ name = "Kinshasa-Brazzaville"; population = 11.3 };
{ name = "Greater Johannesburg"; population = 7.55 };
{ name = "Mogadishu"; population = 5.85 };
{ name = "Khartoum-Omdurman"; population = 4.98 };
{ name = "Dar Es Salaam"; population = 4.7 };
{ name = "Alexandria"; population = 4.58 };
{ name = "Abidjan"; population = 4.4 };
{ name = "Casablanca"; population = 3.98 }
]
(* I can't find in the standard library any function in module List that returns
* an index. Well, never mind, I make my own... *)
let find_index pred =
let rec doloop i = function
| [] -> raise Not_found
| x :: xs -> if pred x then i else doloop (i + 1) xs
in
doloop 0
(* List.find returns the first element that satisfies the predicate.
* List.filter or List.find_all would return *all* the elements that satisfy the
* predicate. *)
let get_first pred = List.find pred
(* Simulate the 'startswith' function found in other languages. *)
let startswith sub s =
Str.string_match (Str.regexp sub) s 0
let () =
(* We use a typical dot notation to access the record fields. *)
find_index (fun c -> c.name = "Dar Es Salaam") cities
|> print_int
|> print_newline;
(get_first (fun c -> c.population < 5.0) cities).name
|> print_endline;
(get_first (fun c -> startswith "A" c.name) cities).population
|> print_float
|> print_newline;
|
http://rosettacode.org/wiki/Search_a_list
|
Search a list
|
Task[edit]
Find the index of a string (needle) in an indexable, ordered collection of strings (haystack).
Raise an exception if the needle is missing.
If there is more than one occurrence then return the smallest index to the needle.
Extra credit
Return the largest index to a needle that has multiple occurrences in the haystack.
See also
Search a list of records
|
#C
|
C
|
#include <stdio.h>
#include <string.h>
const char *haystack[] = {
"Zig", "Zag", "Wally", "Ronald", "Bush", "Krusty", "Charlie",
"Bush", "Boz", "Zag", NULL
};
int search_needle(const char *needle, const char **hs)
{
int i = 0;
while( hs[i] != NULL ) {
if ( strcmp(hs[i], needle) == 0 ) return i;
i++;
}
return -1;
}
int search_last_needle(const char *needle, const char **hs)
{
int i, last=0;
i = last = search_needle(needle, hs);
if ( last < 0 ) return -1;
while( hs[++i] != NULL ) {
if ( strcmp(needle, hs[i]) == 0 ) {
last = i;
}
}
return last;
}
int main()
{
printf("Bush is at %d\n", search_needle("Bush", haystack));
if ( search_needle("Washington", haystack) == -1 )
printf("Washington is not in the haystack\n");
printf("First index for Zag: %d\n", search_needle("Zag", haystack));
printf("Last index for Zag: %d\n", search_last_needle("Zag", haystack));
return 0;
}
|
http://rosettacode.org/wiki/Runtime_evaluation
|
Runtime evaluation
|
Task
Demonstrate a language's ability for programs to execute code written in the language provided at runtime.
Show what kind of program fragments are permitted (e.g. expressions vs. statements), and how to get values in and out (e.g. environments, arguments, return values), if applicable what lexical/static environment the program is evaluated in, and what facilities for restricting (e.g. sandboxes, resource limits) or customizing (e.g. debugging facilities) the execution.
You may not invoke a separate evaluator program, or invoke a compiler and then its output, unless the interface of that program, and the syntax and means of executing it, are considered part of your language/library/platform.
For a more constrained task giving a specific program fragment to evaluate, see Eval in environment.
|
#Liberty_BASIC
|
Liberty BASIC
|
'Dimension a numerical and string array
Dim myArray(5)
Dim myStringArray$(5)
'Fill both arrays with the appropriate data
For i = 0 To 5
myArray(i) = i
myStringArray$(i) = "String - " + str$(i)
Next i
'Set two variables with the names of each array
numArrayName$ = "myArray"
strArrayName$ = "myStringArray"
'Retrieve the array data by evaluating a string
'that correlates to the array
For i = 0 To 5
Print Eval$(numArrayName$ + "(" + str$(i) + ")")
Print Eval$(strArrayName$ + "$(" + str$(i) + ")")
Next i
|
http://rosettacode.org/wiki/Runtime_evaluation
|
Runtime evaluation
|
Task
Demonstrate a language's ability for programs to execute code written in the language provided at runtime.
Show what kind of program fragments are permitted (e.g. expressions vs. statements), and how to get values in and out (e.g. environments, arguments, return values), if applicable what lexical/static environment the program is evaluated in, and what facilities for restricting (e.g. sandboxes, resource limits) or customizing (e.g. debugging facilities) the execution.
You may not invoke a separate evaluator program, or invoke a compiler and then its output, unless the interface of that program, and the syntax and means of executing it, are considered part of your language/library/platform.
For a more constrained task giving a specific program fragment to evaluate, see Eval in environment.
|
#Lua
|
Lua
|
f = loadstring(s) -- load a string as a function. Returns a function.
one = loadstring"return 1" -- one() returns 1
two = loadstring"return ..." -- two() returns the arguments passed to it
|
http://rosettacode.org/wiki/Safe_primes_and_unsafe_primes
|
Safe primes and unsafe primes
|
Definitions
A safe prime is a prime p and where (p-1)/2 is also prime.
The corresponding prime (p-1)/2 is known as a Sophie Germain prime.
An unsafe prime is a prime p and where (p-1)/2 isn't a prime.
An unsafe prime is a prime that isn't a safe prime.
Task
Find and display (on one line) the first 35 safe primes.
Find and display the count of the safe primes below 1,000,000.
Find and display the count of the safe primes below 10,000,000.
Find and display (on one line) the first 40 unsafe primes.
Find and display the count of the unsafe primes below 1,000,000.
Find and display the count of the unsafe primes below 10,000,000.
(Optional) display the counts and "below numbers" with commas.
Show all output here.
Related Task
strong and weak primes.
Also see
The OEIS article: safe primes.
The OEIS article: unsafe primes.
|
#PureBasic
|
PureBasic
|
#MAX=10000000
Global Dim P.b(#MAX) : FillMemory(@P(),#MAX,1,#PB_Byte)
Global NewList Primes.i()
Global NewList SaveP.i()
Global NewList UnSaveP.i()
For n=2 To Sqr(#MAX)+1 : If P(n) : m=n*n : While m<=#MAX : P(m)=0 : m+n : Wend : EndIf : Next
For i=2 To #MAX : If p(i) : AddElement(Primes()) : Primes()=i : EndIf : Next
ForEach Primes()
If P((Primes()-1)/2) And Primes()>3 : AddElement(SaveP()) : SaveP()=Primes() : If Primes()<1000000 : c1+1 : EndIf
Else
AddElement(UnSaveP()) : UnSaveP()=Primes() : If Primes()<1000000 : c2+1 : EndIf
EndIf
Next
OpenConsole()
PrintN("First 35 safe primes:")
If FirstElement(SaveP())
For i=1 To 35 : Print(Str(SaveP())+" ") : NextElement(SaveP()) : Next
EndIf
PrintN(~"\nThere are "+FormatNumber(c1,0,".","'")+" safe primes below 1'000'000")
PrintN("There are "+FormatNumber(ListSize(SaveP()),0,".","'")+" safe primes below 10'000'000")
PrintN("")
PrintN("First 40 unsafe primes:")
If FirstElement(UnSaveP())
For i=1 To 40 : Print(Str(UnSaveP())+" ") : NextElement(UnSaveP()) : Next
EndIf
PrintN(~"\nThere are "+FormatNumber(c2,0,".","'")+" unsafe primes below 1'000'000")
PrintN("There are "+FormatNumber(ListSize(UnSaveP()),0,".","'")+" unsafe primes below 10'000'000")
Input()
|
http://rosettacode.org/wiki/Runtime_evaluation/In_an_environment
|
Runtime evaluation/In an environment
|
x
x
x
Do so in a way which:
does not involve string manipulation of the input source code
is plausibly extensible to a runtime-chosen set of bindings rather than just x
does not make x a global variable
or note that these are impossible.
See also
For more general examples and language-specific details, see Eval.
Dynamic variable names is a similar task.
|
#Common_Lisp
|
Common Lisp
|
(defun eval-with-x (program a b)
(let ((at-a (eval `(let ((x ',a)) ,program)))
(at-b (eval `(let ((x ',b)) ,program))))
(- at-b at-a)))
|
http://rosettacode.org/wiki/Runtime_evaluation/In_an_environment
|
Runtime evaluation/In an environment
|
x
x
x
Do so in a way which:
does not involve string manipulation of the input source code
is plausibly extensible to a runtime-chosen set of bindings rather than just x
does not make x a global variable
or note that these are impossible.
See also
For more general examples and language-specific details, see Eval.
Dynamic variable names is a similar task.
|
#D.C3.A9j.C3.A0_Vu
|
Déjà Vu
|
local fib n:
if <= n 1:
n
else:
+ fib - n 1 fib - n 2
local :code !compile-string dup "-- fib x" #one less than the xth fibonacci number
!run-blob-in { :fib @fib :x 4 } code
!run-blob-in { :fib @fib :x 6 } code
!. -
|
http://rosettacode.org/wiki/RSA_code
|
RSA code
|
Given an RSA key (n,e,d), construct a program to encrypt and decrypt plaintext messages strings.
Background
RSA code is used to encode secret messages. It is named after Ron Rivest, Adi Shamir, and Leonard Adleman who published it at MIT in 1977. The advantage of this type of encryption is that you can distribute the number “
n
{\displaystyle n}
” and “
e
{\displaystyle e}
” (which makes up the Public Key used for encryption) to everyone. The Private Key used for decryption “
d
{\displaystyle d}
” is kept secret, so that only the recipient can read the encrypted plaintext.
The process by which this is done is that a message, for example “Hello World” is encoded as numbers (This could be encoding as ASCII or as a subset of characters
a
=
01
,
b
=
02
,
.
.
.
,
z
=
26
{\displaystyle a=01,b=02,...,z=26}
). This yields a string of numbers, generally referred to as "numerical plaintext", “
P
{\displaystyle P}
”. For example, “Hello World” encoded with a=1,...,z=26 by hundreds would yield
08051212152315181204
{\displaystyle 08051212152315181204}
.
The plaintext must also be split into blocks so that the numerical plaintext is smaller than
n
{\displaystyle n}
otherwise the decryption will fail.
The ciphertext,
C
{\displaystyle C}
, is then computed by taking each block of
P
{\displaystyle P}
, and computing
C
≡
P
e
mod
n
{\displaystyle C\equiv P^{e}\mod n}
Similarly, to decode, one computes
P
≡
C
d
mod
n
{\displaystyle P\equiv C^{d}\mod n}
To generate a key, one finds 2 (ideally large) primes
p
{\displaystyle p}
and
q
{\displaystyle q}
. the value “
n
{\displaystyle n}
” is simply:
n
=
p
×
q
{\displaystyle n=p\times q}
.
One must then choose an “
e
{\displaystyle e}
” such that
gcd
(
e
,
(
p
−
1
)
×
(
q
−
1
)
)
=
1
{\displaystyle \gcd(e,(p-1)\times (q-1))=1}
. That is to say,
e
{\displaystyle e}
and
(
p
−
1
)
×
(
q
−
1
)
{\displaystyle (p-1)\times (q-1)}
are relatively prime to each other.
The decryption value
d
{\displaystyle d}
is then found by solving
d
×
e
≡
1
mod
(
p
−
1
)
×
(
q
−
1
)
{\displaystyle d\times e\equiv 1\mod (p-1)\times (q-1)}
The security of the code is based on the secrecy of the Private Key (decryption exponent) “
d
{\displaystyle d}
” and the difficulty in factoring “
n
{\displaystyle n}
”. Research into RSA facilitated advances in factoring and a number of factoring challenges. Keys of 768 bits have been successfully factored. While factoring of keys of 1024 bits has not been demonstrated, NIST expected them to be factorable by 2010 and now recommends 2048 bit keys going forward (see Asymmetric algorithm key lengths or NIST 800-57 Pt 1 Revised Table 4: Recommended algorithms and minimum key sizes).
Summary of the task requirements:
Encrypt and Decrypt a short message or two using RSA with a demonstration key.
Implement RSA do not call a library.
Encode and decode the message using any reversible method of your choice (ASCII or a=1,..,z=26 are equally fine).
Either support blocking or give an error if the message would require blocking)
Demonstrate that your solution could support real keys by using a non-trivial key that requires large integer support (built-in or libraries). There is no need to include library code but it must be referenced unless it is built into the language. The following keys will be meet this requirement;however, they are NOT long enough to be considered secure:
n = 9516311845790656153499716760847001433441357
e = 65537
d = 5617843187844953170308463622230283376298685
Messages can be hard-coded into the program, there is no need for elaborate input coding.
Demonstrate that your implementation works by showing plaintext, intermediate results, encrypted text, and decrypted text.
Warning
Rosetta Code is not a place you should rely on for examples of code in critical roles, including security.
Cryptographic routines should be validated before being used.
For a discussion of limitations and please refer to Talk:RSA_code#Difference_from_practical_cryptographical_version.
|
#11l
|
11l
|
V n = BigInt(‘9516311845790656153499716760847001433441357’)
V e = BigInt(65537)
V d = BigInt(‘5617843187844953170308463622230283376298685’)
V txt = ‘Rosetta Code’
print(‘Plain text: ’txt)
V txtN = txt.reduce(BigInt(0), (a, b) -> a * 256 + b.code)
print(‘Plain text as a number: ’txtN)
V enc = pow(txtN, e, n)
print(‘Encoded: ’enc)
V dec = pow(enc, d, n)
print(‘Decoded: ’dec)
V decTxt = ‘’
L dec != 0
decTxt ‘’= Char(code' dec % 256)
dec I/= 256
print(‘Decoded number as text: ’reversed(decTxt))
|
http://rosettacode.org/wiki/Sieve_of_Eratosthenes
|
Sieve of Eratosthenes
|
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task.
The Sieve of Eratosthenes is a simple algorithm that finds the prime numbers up to a given integer.
Task
Implement the Sieve of Eratosthenes algorithm, with the only allowed optimization that the outer loop can stop at the square root of the limit, and the inner loop may start at the square of the prime just found.
That means especially that you shouldn't optimize by using pre-computed wheels, i.e. don't assume you need only to cross out odd numbers (wheel based on 2), numbers equal to 1 or 5 modulo 6 (wheel based on 2 and 3), or similar wheels based on low primes.
If there's an easy way to add such a wheel based optimization, implement it as an alternative version.
Note
It is important that the sieve algorithm be the actual algorithm used to find prime numbers for the task.
Related tasks
Emirp primes
count in factors
prime decomposition
factors of an integer
extensible prime generator
primality by trial division
factors of a Mersenne number
trial factoring of a Mersenne number
partition an integer X into N primes
sequence of primes by Trial Division
|
#Oz
|
Oz
|
declare
fun {Sieve N}
S = {Array.new 2 N true}
M = {Float.toInt {Sqrt {Int.toFloat N}}}
in
for I in 2..M do
if S.I then
for J in I*I..N;I do
S.J := false
end
end
end
S
end
fun {Primes N}
S = {Sieve N}
in
for I in 2..N collect:C do
if S.I then {C I} end
end
end
in
{Show {Primes 30}}
|
http://rosettacode.org/wiki/Search_a_list_of_records
|
Search a list of records
|
Many programming languages provide convenient ways to look for a known value in a simple list of strings or numbers.
But what if the elements of the list are themselves compound records/objects/data-structures, and the search condition is more complex than a simple equality test?
Task[edit]
Write a function/method/etc. that can find the first element in a given list matching a given condition.
It should be as generic and reusable as possible.
(Of course if your programming language already provides such a feature, you can use that instead of recreating it.)
Then to demonstrate its functionality, create the data structure specified under #Data set, and perform on it the searches specified under #Test cases.
Data set
The data structure to be used contains the names and populations (in millions) of the 10 largest metropolitan areas in Africa, and looks as follows when represented in JSON:
[
{ "name": "Lagos", "population": 21.0 },
{ "name": "Cairo", "population": 15.2 },
{ "name": "Kinshasa-Brazzaville", "population": 11.3 },
{ "name": "Greater Johannesburg", "population": 7.55 },
{ "name": "Mogadishu", "population": 5.85 },
{ "name": "Khartoum-Omdurman", "population": 4.98 },
{ "name": "Dar Es Salaam", "population": 4.7 },
{ "name": "Alexandria", "population": 4.58 },
{ "name": "Abidjan", "population": 4.4 },
{ "name": "Casablanca", "population": 3.98 }
]
However, you shouldn't parse it from JSON, but rather represent it natively in your programming language.
The top-level data structure should be an ordered collection (i.e. a list, array, vector, or similar).
Each element in this list should be an associative collection that maps from keys to values (i.e. a struct, object, hash map, dictionary, or similar).
Each of them has two entries: One string value with key "name", and one numeric value with key "population".
You may rely on the list being sorted by population count, as long as you explain this to readers.
If any of that is impossible or unreasonable in your programming language, then feel free to deviate, as long as you explain your reasons in a comment above your solution.
Test cases
Search
Expected result
Find the (zero-based) index of the first city in the list whose name is "Dar Es Salaam"
6
Find the name of the first city in this list whose population is less than 5 million
Khartoum-Omdurman
Find the population of the first city in this list whose name starts with the letter "A"
4.58
Guidance
If your programming language supports higher-order programming, then the most elegant way to implement the requested functionality in a generic and reusable way, might be to write a function (maybe called "find_index" or similar), that takes two arguments:
The list to search through.
A function/lambda/closure (the so-called "predicate"), which will be applied in turn to each element in the list, and whose boolean return value defines whether that element matches the search requirement.
If this is not the approach which would be most natural or idiomatic in your language, explain why, and show what is.
Related tasks
Search a list
|
#Perl
|
Perl
|
use feature 'say';
use List::Util qw(first);
my @cities = (
{ name => 'Lagos', population => 21.0 },
{ name => 'Cairo', population => 15.2 },
{ name => 'Kinshasa-Brazzaville', population => 11.3 },
{ name => 'Greater Johannesburg', population => 7.55 },
{ name => 'Mogadishu', population => 5.85 },
{ name => 'Khartoum-Omdurman', population => 4.98 },
{ name => 'Dar Es Salaam', population => 4.7 },
{ name => 'Alexandria', population => 4.58 },
{ name => 'Abidjan', population => 4.4 },
{ name => 'Casablanca', population => 3.98 },
);
my $index1 = first { $cities[$_]{name} eq 'Dar Es Salaam' } 0..$#cities;
say $index1;
my $record2 = first { $_->{population} < 5 } @cities;
say $record2->{name};
my $record3 = first { $_->{name} =~ /^A/ } @cities;
say $record3->{population};
|
http://rosettacode.org/wiki/Search_a_list
|
Search a list
|
Task[edit]
Find the index of a string (needle) in an indexable, ordered collection of strings (haystack).
Raise an exception if the needle is missing.
If there is more than one occurrence then return the smallest index to the needle.
Extra credit
Return the largest index to a needle that has multiple occurrences in the haystack.
See also
Search a list of records
|
#C.23
|
C#
|
using System;
using System.Collections.Generic;
class Program {
static void Main(string[] args) {
List<string> haystack = new List<string>() { "Zig", "Zag", "Wally", "Ronald", "Bush", "Krusty", "Charlie", "Bush", "Bozo" };
foreach (string needle in new string[] { "Washington", "Bush" }) {
int index = haystack.IndexOf(needle);
if (index < 0) Console.WriteLine("{0} is not in haystack",needle);
else Console.WriteLine("{0} {1}",index,needle);
}
}
}
|
http://rosettacode.org/wiki/Runtime_evaluation
|
Runtime evaluation
|
Task
Demonstrate a language's ability for programs to execute code written in the language provided at runtime.
Show what kind of program fragments are permitted (e.g. expressions vs. statements), and how to get values in and out (e.g. environments, arguments, return values), if applicable what lexical/static environment the program is evaluated in, and what facilities for restricting (e.g. sandboxes, resource limits) or customizing (e.g. debugging facilities) the execution.
You may not invoke a separate evaluator program, or invoke a compiler and then its output, unless the interface of that program, and the syntax and means of executing it, are considered part of your language/library/platform.
For a more constrained task giving a specific program fragment to evaluate, see Eval in environment.
|
#M2000_Interpreter
|
M2000 Interpreter
|
Module checkit {
Module dummy {
i++
Print Number
}
\\ using Stack New { } we open a new stack for values, and old one connected back at the end
\\ using block For This {} we erase any new definition, so we erase i (which Local make a new one)
a$={
Stack New {
For this {
Local i
for i=1 to 10 : print i : next i
}
}
If valid(k) then print k
}
i=500
k=600
Push 1000
inline a$
Print i=500
Print Number=1000
\\ eval an expression
Print Eval("i+k")
\\ eval a function
Print Function("{read x : = x**2}", 2)=4
Dim k(10)=123
\\ eval array only
Print array("k()", 2)=123
Push 10, 10
\\ call a module by make it inline first
inline code dummy, dummy
Print i=502
}
CheckIt
|
http://rosettacode.org/wiki/Runtime_evaluation
|
Runtime evaluation
|
Task
Demonstrate a language's ability for programs to execute code written in the language provided at runtime.
Show what kind of program fragments are permitted (e.g. expressions vs. statements), and how to get values in and out (e.g. environments, arguments, return values), if applicable what lexical/static environment the program is evaluated in, and what facilities for restricting (e.g. sandboxes, resource limits) or customizing (e.g. debugging facilities) the execution.
You may not invoke a separate evaluator program, or invoke a compiler and then its output, unless the interface of that program, and the syntax and means of executing it, are considered part of your language/library/platform.
For a more constrained task giving a specific program fragment to evaluate, see Eval in environment.
|
#Mathematica.2FWolfram_Language
|
Mathematica/Wolfram Language
|
Print[ToExpression["1 + 1"]];
Print[ToExpression["Print[\"Hello, world!\"]; 10!"]];
x = 5;
Print[ToExpression["x!"]];
Print[ToExpression["Module[{x = 8}, x!]"]];
Print[MemoryConstrained[ToExpression["Range[5]"], 10000, {}]];
Print[MemoryConstrained[ToExpression["Range[10^5]"], 10000, {}]];
Print[TimeConstrained[ToExpression["Pause[1]; True"], 2, False]];
Print[TimeConstrained[ToExpression["Pause[60]; True"], 2, False]];
|
http://rosettacode.org/wiki/Runtime_evaluation
|
Runtime evaluation
|
Task
Demonstrate a language's ability for programs to execute code written in the language provided at runtime.
Show what kind of program fragments are permitted (e.g. expressions vs. statements), and how to get values in and out (e.g. environments, arguments, return values), if applicable what lexical/static environment the program is evaluated in, and what facilities for restricting (e.g. sandboxes, resource limits) or customizing (e.g. debugging facilities) the execution.
You may not invoke a separate evaluator program, or invoke a compiler and then its output, unless the interface of that program, and the syntax and means of executing it, are considered part of your language/library/platform.
For a more constrained task giving a specific program fragment to evaluate, see Eval in environment.
|
#MATLAB
|
MATLAB
|
function testEval
fprintf('Expressions:\n')
x = eval('5+10^2')
eval('y = (x-100).*[1 2 3]')
eval('z = strcat(''my'', '' string'')')
try
w eval(' = 45')
catch
fprintf('Runtime error: interpretation of w is a function\n\n')
end
% eval('v') = 5
% Invalid at compile-time as MATLAB interprets as using eval as a variable
fprintf('Other Statements:\n')
nl = sprintf('\n');
eval(['for k = 1:20' nl ...
'fprintf(''%.3f\n'', k)' nl ...
'if k == 3' nl ...
'break' nl ...
'end' nl ...
'end'])
true == eval('1')
try
true eval(' == 1')
catch
fprintf('Runtime error: interpretation of == 1 is of input to true\n\n')
end
fprintf('Programming on the fly:\n')
userIn = true;
codeBlock = '';
while userIn
userIn = input('Enter next line of code: ', 's');
codeBlock = [codeBlock nl userIn];
end
eval(codeBlock)
end
|
http://rosettacode.org/wiki/Safe_primes_and_unsafe_primes
|
Safe primes and unsafe primes
|
Definitions
A safe prime is a prime p and where (p-1)/2 is also prime.
The corresponding prime (p-1)/2 is known as a Sophie Germain prime.
An unsafe prime is a prime p and where (p-1)/2 isn't a prime.
An unsafe prime is a prime that isn't a safe prime.
Task
Find and display (on one line) the first 35 safe primes.
Find and display the count of the safe primes below 1,000,000.
Find and display the count of the safe primes below 10,000,000.
Find and display (on one line) the first 40 unsafe primes.
Find and display the count of the unsafe primes below 1,000,000.
Find and display the count of the unsafe primes below 10,000,000.
(Optional) display the counts and "below numbers" with commas.
Show all output here.
Related Task
strong and weak primes.
Also see
The OEIS article: safe primes.
The OEIS article: unsafe primes.
|
#Python
|
Python
|
primes =[]
sp =[]
usp=[]
n = 10000000
if 2<n:
primes.append(2)
for i in range(3,n+1,2):
for j in primes:
if(j>i/2) or (j==primes[-1]):
primes.append(i)
if((i-1)/2) in primes:
sp.append(i)
break
else:
usp.append(i)
break
if (i%j==0):
break
print('First 35 safe primes are:\n' , sp[:35])
print('There are '+str(len(sp[:1000000]))+' safe primes below 1,000,000')
print('There are '+str(len(sp))+' safe primes below 10,000,000')
print('First 40 unsafe primes:\n',usp[:40])
print('There are '+str(len(usp[:1000000]))+' unsafe primes below 1,000,000')
print('There are '+str(len(usp))+' safe primes below 10,000,000')
|
http://rosettacode.org/wiki/Runtime_evaluation/In_an_environment
|
Runtime evaluation/In an environment
|
x
x
x
Do so in a way which:
does not involve string manipulation of the input source code
is plausibly extensible to a runtime-chosen set of bindings rather than just x
does not make x a global variable
or note that these are impossible.
See also
For more general examples and language-specific details, see Eval.
Dynamic variable names is a similar task.
|
#E
|
E
|
# Constructing an environment has to be done by way of evaluation
#for historical reasons which will hopefully be entirely eliminated soon.
def bindX(value) {
def [resolver, env] := e` # bind x and capture its resolver and the
def x # resulting environment
`.evalToPair(safeScope)
resolver.resolve(value) # set the value
return env
}
def evalWithX(program, a, b) {
def atA := program.eval(bindX(a))
def atB := program.eval(bindX(b))
return atB - atA
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.