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/Scope_modifiers
|
Scope modifiers
|
Most programming languages offer support for subroutines.
When execution changes between subroutines, different sets of variables and functions ("scopes") are available to the program.
Frequently these sets are defined by the placement of the variable and function declarations ("static scoping" or "lexical scoping").
These sets may also be defined by special modifiers to the variable and function declarations.
Show the different scope modifiers available in your language and briefly explain how they change the scope of their variable or function.
If your language has no scope modifiers, note it.
|
#PARI.2FGP
|
PARI/GP
|
procedure super;
var
f: boolean;
procedure nestedProcedure;
var
c: char;
begin
// here, `f`, `c`, `nestedProcedure` and `super` are available
end;
procedure commonTask;
var
f: boolean;
begin
// here, `super`, `commonTask` and _only_ the _local_ `f` is available
end;
var
c: char;
procedure fooBar;
begin
// here, `super`, `fooBar`, `f` and `c` are available
end;
var
x: integer;
begin
// here, `c`, `f`, and `x`, as well as,
// `nestedProcedure`, `commonTask`, `fooBar` and `super` are available
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).
|
#D
|
D
|
import std.stdio;
void main() {
auto coconuts = 11;
outer:
foreach (ns; 2..10) {
int[] hidden = new int[ns];
coconuts = (coconuts / ns) * ns + 1;
while (true) {
auto nc = coconuts;
foreach (s; 1..ns+1) {
if (nc % ns == 1) {
hidden[s-1] = nc/ns;
nc -= hidden[s-1] + 1;
if (s==ns && nc%ns==0) {
writeln(ns, " sailors require a minimum of ", coconuts, " coconuts");
foreach (t; 1..ns+1) {
writeln("\tSailor ", t, " hides ", hidden[t - 1]);
}
writeln("\tThe monkey gets ", ns);
writeln("\tFinally, each sailor takes ", nc / ns);
continue outer;
}
} else {
break;
}
}
coconuts += ns;
}
}
}
|
http://rosettacode.org/wiki/Secure_temporary_file
|
Secure temporary file
|
Task
Create a temporary file, securely and exclusively (opening it such that there are no possible race conditions).
It's fine assuming local filesystem semantics (NFS or other networking filesystems can have signficantly more complicated semantics for satisfying the "no race conditions" criteria).
The function should automatically resolve name collisions and should only fail in cases where permission is denied, the filesystem is read-only or full, or similar conditions exist (returning an error or raising an exception as appropriate to the language/environment).
|
#Rust
|
Rust
|
// 202100322 Rust programming solution
use tempfile::tempfile;
fn main() {
let fh = tempfile();
println!("{:?}", fh);
}
|
http://rosettacode.org/wiki/Secure_temporary_file
|
Secure temporary file
|
Task
Create a temporary file, securely and exclusively (opening it such that there are no possible race conditions).
It's fine assuming local filesystem semantics (NFS or other networking filesystems can have signficantly more complicated semantics for satisfying the "no race conditions" criteria).
The function should automatically resolve name collisions and should only fail in cases where permission is denied, the filesystem is read-only or full, or similar conditions exist (returning an error or raising an exception as appropriate to the language/environment).
|
#Scala
|
Scala
|
import java.io.{File, FileWriter, IOException}
def writeStringToFile(file: File, data: String, appending: Boolean = false) =
using(new FileWriter(file, appending))(_.write(data))
def using[A <: {def close() : Unit}, B](resource: A)(f: A => B): B =
try f(resource) finally resource.close()
try {
val file = File.createTempFile("_rosetta", ".passwd")
// Just an example how you can fill a file
using(new FileWriter(file))(writer => rawDataIter.foreach(line => writer.write(line)))
scala.compat.Platform.collectGarbage() // JVM Windows related bug workaround JDK-4715154
file.deleteOnExit()
println(file)
} catch {
case e: IOException => println(s"Running Example failed: ${e.getMessage}")
}
|
http://rosettacode.org/wiki/Scope/Function_names_and_labels
|
Scope/Function names and labels
|
Task
Explain or demonstrate the levels of visibility of function names and labels within the language.
See also
Variables for levels of scope relating to visibility of program variables
Scope modifiers for general scope modification facilities
|
#Objeck
|
Objeck
|
no warnings 'redefine';
sub logger { print shift . ": Dicitur clamantis in deserto." }; # discarded
logger('A'); # can use before defined
HighLander::logger('B'); # ditto, but referring to another package
package HighLander {
logger('C');
sub logger { print shift . ": I have something to say.\n" }; # discarded
sub down_one_level {
sub logger { print shift . ": I am a man, not a fish.\n" }; # discarded
sub down_two_levels {
sub logger { print shift . ": There can be only one!\n" }; # routine for 'Highlander' package
}
}
logger('D');
}
logger('E');
sub logger {
print shift . ": This thought intentionally left blank.\n" # routine for 'main' package
};
|
http://rosettacode.org/wiki/Scope/Function_names_and_labels
|
Scope/Function names and labels
|
Task
Explain or demonstrate the levels of visibility of function names and labels within the language.
See also
Variables for levels of scope relating to visibility of program variables
Scope modifiers for general scope modification facilities
|
#Oforth
|
Oforth
|
no warnings 'redefine';
sub logger { print shift . ": Dicitur clamantis in deserto." }; # discarded
logger('A'); # can use before defined
HighLander::logger('B'); # ditto, but referring to another package
package HighLander {
logger('C');
sub logger { print shift . ": I have something to say.\n" }; # discarded
sub down_one_level {
sub logger { print shift . ": I am a man, not a fish.\n" }; # discarded
sub down_two_levels {
sub logger { print shift . ": There can be only one!\n" }; # routine for 'Highlander' package
}
}
logger('D');
}
logger('E');
sub logger {
print shift . ": This thought intentionally left blank.\n" # routine for 'main' package
};
|
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
|
#Arturo
|
Arturo
|
define :city [name population][]
records: map [
["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]
] => [to :city]
find: function [block f][
loop.with: 'i block 'elt [
if f elt -> return @[elt i]
]
return false
]
; Print the index of the first city named Dar Es Salaam.
print last find records $[c][equal? c\name "Dar Es Salaam"]
; Print the name of the first city with under 5 million people.
print get first find records $[c][less? c\population 5] 'name
; Print the population of the first city starting with 'A'.
print get first find records $[c][equal? first c\name `A`] 'population
|
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).
|
#Bracmat
|
Bracmat
|
( ( T
=
. ( next
= node stack rhs
. !arg:%?node ?stack
& whl
' ( !node:(?node.?rhs)
& !rhs !stack:?stack
)
& (!node.!stack)
)
& !arg:(?stackA,?stackB)
& whl
' ( !stackA:~
& !stackB:~
& next$!stackA:(?leafA.?stackA)
& next$!stackB:(?leafB.?stackB)
& !leafA:!leafB
)
& out$!arg
& ( !stackA:!stackB:
& !leafA:!leafB
& out$equal
| out$"not equal"
)
)
& T$(x,x)
& T$((x.y),(x.y))
& T$(((x.y).z),(x.y.z))
& T$((x.y.z),(x.y.q))
& T$((x.y),(x.y.q))
& T$((x.y.z),(x.y))
& T$(((x.y).z),(x.z.y))
& T
$ ( (a.b.c.(x.y).z)
, (((a.b).c).x.y.z)
)
);
|
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).
|
#C
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <ucontext.h>
typedef struct {
ucontext_t caller, callee;
char stack[8192];
void *in, *out;
} co_t;
co_t * co_new(void(*f)(), void *data)
{
co_t * c = malloc(sizeof(*c));
getcontext(&c->callee);
c->in = data;
c->callee.uc_stack.ss_sp = c->stack;
c->callee.uc_stack.ss_size = sizeof(c->stack);
c->callee.uc_link = &c->caller;
makecontext(&c->callee, f, 1, (int)c);
return c;
}
void co_del(co_t *c)
{
free(c);
}
inline void
co_yield(co_t *c, void *data)
{
c->out = data;
swapcontext(&c->callee, &c->caller);
}
inline void *
co_collect(co_t *c)
{
c->out = 0;
swapcontext(&c->caller, &c->callee);
return c->out;
}
// end of coroutine stuff
typedef struct node node;
struct node {
int v;
node *left, *right;
};
node *newnode(int v)
{
node *n = malloc(sizeof(node));
n->left = n->right = 0;
n->v = v;
return n;
}
void tree_insert(node **root, node *n)
{
while (*root) root = ((*root)->v > n->v)
? &(*root)->left
: &(*root)->right;
*root = n;
}
void tree_trav(int x)
{
co_t *c = (co_t *) x;
void trav(node *root) {
if (!root) return;
trav(root->left);
co_yield(c, root);
trav(root->right);
}
trav(c->in);
}
int tree_eq(node *t1, node *t2)
{
co_t *c1 = co_new(tree_trav, t1);
co_t *c2 = co_new(tree_trav, t2);
node *p = 0, *q = 0;
do {
p = co_collect(c1);
q = co_collect(c2);
} while (p && q && (p->v == q->v));
co_del(c1);
co_del(c2);
return !p && !q;
}
int main()
{
int x[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, -1 };
int y[] = { 2, 5, 7, 1, 9, 0, 6, 4, 8, 3, -1 };
int z[] = { 0, 1, 2, 3, 4, 5, 6, 8, 9, -1 };
node *t1 = 0, *t2 = 0, *t3 = 0;
void mktree(int *buf, node **root) {
int i;
for (i = 0; buf[i] >= 0; i++)
tree_insert(root, newnode(buf[i]));
}
mktree(x, &t1); // ordered binary tree, result of traversing
mktree(y, &t2); // should be independent of insertion, so t1 == t2
mktree(z, &t3);
printf("t1 == t2: %s\n", tree_eq(t1, t2) ? "yes" : "no");
printf("t1 == t3: %s\n", tree_eq(t1, t3) ? "yes" : "no");
return 0;
}
|
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
|
#M2000_Interpreter
|
M2000 Interpreter
|
Module EratosthenesSieve (x) {
\\ Κόσκινο του Ερατοσθένη
If x>200000 Then Exit
Dim i(x+1)
k=2
k2=sqrt(x)
While k<=k2 {
m=k+k
While m<=x {
i(m)=1
m+=k
}
{k++:if i(k) then loop
}
}
For i=2 to x {If i(i)=0 Then Print i,
}
Print
}
EratosthenesSieve 1000
|
http://rosettacode.org/wiki/Scope_modifiers
|
Scope modifiers
|
Most programming languages offer support for subroutines.
When execution changes between subroutines, different sets of variables and functions ("scopes") are available to the program.
Frequently these sets are defined by the placement of the variable and function declarations ("static scoping" or "lexical scoping").
These sets may also be defined by special modifiers to the variable and function declarations.
Show the different scope modifiers available in your language and briefly explain how they change the scope of their variable or function.
If your language has no scope modifiers, note it.
|
#Pascal
|
Pascal
|
procedure super;
var
f: boolean;
procedure nestedProcedure;
var
c: char;
begin
// here, `f`, `c`, `nestedProcedure` and `super` are available
end;
procedure commonTask;
var
f: boolean;
begin
// here, `super`, `commonTask` and _only_ the _local_ `f` is available
end;
var
c: char;
procedure fooBar;
begin
// here, `super`, `fooBar`, `f` and `c` are available
end;
var
x: integer;
begin
// here, `c`, `f`, and `x`, as well as,
// `nestedProcedure`, `commonTask`, `fooBar` and `super` are available
end;
|
http://rosettacode.org/wiki/Scope_modifiers
|
Scope modifiers
|
Most programming languages offer support for subroutines.
When execution changes between subroutines, different sets of variables and functions ("scopes") are available to the program.
Frequently these sets are defined by the placement of the variable and function declarations ("static scoping" or "lexical scoping").
These sets may also be defined by special modifiers to the variable and function declarations.
Show the different scope modifiers available in your language and briefly explain how they change the scope of their variable or function.
If your language has no scope modifiers, note it.
|
#Perl
|
Perl
|
use strict;
$x = 1; # Compilation error.
our $y = 2;
print "$y\n"; # Legal; refers to $main::y.
package Foo;
our $z = 3;
package Bar;
print "$z\n"; # Refers to $Foo::z.
|
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).
|
#Elixir
|
Elixir
|
defmodule RC do
def valid?(sailor, nuts), do: valid?(sailor, nuts, sailor)
def valid?(sailor, nuts, 0), do: nuts > 0 and rem(nuts,sailor) == 0
def valid?(sailor, nuts, _) when rem(nuts,sailor)!=1, do: false
def valid?(sailor, nuts, i) do
valid?(sailor, nuts - div(nuts,sailor) - 1, i-1)
end
end
Enum.each([5,6], fn sailor ->
nuts = Enum.find(Stream.iterate(sailor, &(&1+1)), fn n -> RC.valid?(sailor, n) end)
IO.puts "\n#{sailor} sailors => #{nuts} coconuts"
Enum.reduce(0..sailor, nuts, fn _,n ->
{d, r} = {div(n,sailor), rem(n,sailor)}
IO.puts " #{inspect [n, d, r]}"
n - 1 - d
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).
|
#Forth
|
Forth
|
: total
over * over 1- rot 0 ?do
over over mod if dup xor swap leave else over over / 1+ rot + swap then
loop drop
;
: sailors
1+ 2 ?do
1 begin i over total dup 0= while drop 1+ repeat cr i 0 .r ." : " . .
loop
;
9 sailors
|
http://rosettacode.org/wiki/Secure_temporary_file
|
Secure temporary file
|
Task
Create a temporary file, securely and exclusively (opening it such that there are no possible race conditions).
It's fine assuming local filesystem semantics (NFS or other networking filesystems can have signficantly more complicated semantics for satisfying the "no race conditions" criteria).
The function should automatically resolve name collisions and should only fail in cases where permission is denied, the filesystem is read-only or full, or similar conditions exist (returning an error or raising an exception as appropriate to the language/environment).
|
#Sidef
|
Sidef
|
var tmpfile = require('File::Temp');
var fh = tmpfile.new(UNLINK => 0);
say fh.filename;
fh.print("Hello, World!\n");
fh.close;
|
http://rosettacode.org/wiki/Secure_temporary_file
|
Secure temporary file
|
Task
Create a temporary file, securely and exclusively (opening it such that there are no possible race conditions).
It's fine assuming local filesystem semantics (NFS or other networking filesystems can have signficantly more complicated semantics for satisfying the "no race conditions" criteria).
The function should automatically resolve name collisions and should only fail in cases where permission is denied, the filesystem is read-only or full, or similar conditions exist (returning an error or raising an exception as appropriate to the language/environment).
|
#Standard_ML
|
Standard ML
|
val filename = OS.FileSys.tmpName ();
|
http://rosettacode.org/wiki/Secure_temporary_file
|
Secure temporary file
|
Task
Create a temporary file, securely and exclusively (opening it such that there are no possible race conditions).
It's fine assuming local filesystem semantics (NFS or other networking filesystems can have signficantly more complicated semantics for satisfying the "no race conditions" criteria).
The function should automatically resolve name collisions and should only fail in cases where permission is denied, the filesystem is read-only or full, or similar conditions exist (returning an error or raising an exception as appropriate to the language/environment).
|
#Tcl
|
Tcl
|
set chan [file tempfile filenameVar]
|
http://rosettacode.org/wiki/Secure_temporary_file
|
Secure temporary file
|
Task
Create a temporary file, securely and exclusively (opening it such that there are no possible race conditions).
It's fine assuming local filesystem semantics (NFS or other networking filesystems can have signficantly more complicated semantics for satisfying the "no race conditions" criteria).
The function should automatically resolve name collisions and should only fail in cases where permission is denied, the filesystem is read-only or full, or similar conditions exist (returning an error or raising an exception as appropriate to the language/environment).
|
#TUSCRIPT
|
TUSCRIPT
|
$$ MODE TUSCRIPT
tmpfile="test.txt"
ERROR/STOP CREATE (tmpfile,seq-E,-std-)
text="hello world"
FILE $tmpfile = text
- tmpfile "test.txt" can only be accessed by one user an will be deleted upon programm termination
|
http://rosettacode.org/wiki/Scope/Function_names_and_labels
|
Scope/Function names and labels
|
Task
Explain or demonstrate the levels of visibility of function names and labels within the language.
See also
Variables for levels of scope relating to visibility of program variables
Scope modifiers for general scope modification facilities
|
#Perl
|
Perl
|
no warnings 'redefine';
sub logger { print shift . ": Dicitur clamantis in deserto." }; # discarded
logger('A'); # can use before defined
HighLander::logger('B'); # ditto, but referring to another package
package HighLander {
logger('C');
sub logger { print shift . ": I have something to say.\n" }; # discarded
sub down_one_level {
sub logger { print shift . ": I am a man, not a fish.\n" }; # discarded
sub down_two_levels {
sub logger { print shift . ": There can be only one!\n" }; # routine for 'Highlander' package
}
}
logger('D');
}
logger('E');
sub logger {
print shift . ": This thought intentionally left blank.\n" # routine for 'main' package
};
|
http://rosettacode.org/wiki/Scope/Function_names_and_labels
|
Scope/Function names and labels
|
Task
Explain or demonstrate the levels of visibility of function names and labels within the language.
See also
Variables for levels of scope relating to visibility of program variables
Scope modifiers for general scope modification facilities
|
#Phix
|
Phix
|
Functions are normally internal to a program. If they are at the nesting level
immediately within the program, they are accessible from anywhere in the program.
Functions can also be encapsuled in a package, and the function name exported.
Functions can be compiled separately, and then linked with a program
in which case they are globally accessible.
|
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
|
#BASIC
|
BASIC
|
100 nc=0
110 read n$
120 if n$="" then 160
130 read p$
140 nc=nc+1
150 goto 110
160 restore
170 dim ci$(nc-1,1)
180 for i=0 to nc-1
190 : for j=0 to 1
200 : read ci$(i,j)
210 : next j
220 next i
230 :
240 print chr$(14);:rem text mode
250 print: print "Test 1. name='Dar Es Salaam':"
260 rem search uses query function fnq
270 def fnq(i) = ci$(i,0) = "Dar Es Salaam"
280 gosub 500
290 if i<0 then print " None found.":goto 310
300 print " Index="i"."
310 print: print "Test 2. population < 5M:"
320 def fnq(i) = val(ci$(i,1)) < 5
330 gosub 500
340 if i<0 then print " None found.":goto 360
350 print " Name="ci$(i,0)"."
360 print: print "Test 3. name like 'A%':"
370 def fnq(i) = left$(ci$(i,0),1)="A"
380 gosub 500
390 if i<0 then print " None found.":goto 410
400 print " Population="ci$(i,1)"."
410 end
420 :
500 for i=0 to nc-1
510 : if fnq(i) then return
520 next i
530 i=-1
540 return
550 :
560 data "Lagos", 21.0
570 data "Cairo", 15.2
580 data "Kinshasa-Brazzaville", 11.3
590 data "Greater Johannesburg", 7.55
600 data "Mogadishu", 5.85
610 data "Khartoum-Omdurman", 4.98
620 data "Dar Es Salaam", 4.7
630 data "Alexandria", 4.58
640 data "Abidjan", 4.4
650 data "Casablanca", 3.98
660 data ""
|
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).
|
#C.23
|
C#
|
using System;
using System.Collections.Generic;
using System.Linq;
namespace Same_Fringe
{
class Program
{
static void Main()
{
var rnd = new Random(110456);
var randList = Enumerable.Range(0, 20).Select(i => rnd.Next(1000)).ToList();
var bt1 = new BinTree<int>(randList);
// Shuffling will create a tree with the same values but different topology
Shuffle(randList, 428);
var bt2 = new BinTree<int>(randList);
Console.WriteLine(bt1.CompareTo(bt2) ? "True compare worked" : "True compare failed");
// Insert a 0 in the first tree which should cause a failure
bt1.Insert(0);
Console.WriteLine(bt1.CompareTo(bt2) ? "False compare failed" : "False compare worked");
}
static void Shuffle<T>(List<T> values, int seed)
{
var rnd = new Random(seed);
for (var i = 0; i < values.Count - 2; i++)
{
var iSwap = rnd.Next(values.Count - i) + i;
var tmp = values[iSwap];
values[iSwap] = values[i];
values[i] = tmp;
}
}
}
// Define other methods and classes here
class BinTree<T> where T:IComparable
{
private BinTree<T> _left;
private BinTree<T> _right;
private T _value;
private BinTree<T> Left
{
get { return _left; }
}
private BinTree<T> Right
{
get { return _right; }
}
// On interior nodes, any value greater than or equal to Value goes in the
// right subtree, everything else in the left.
private T Value
{
get { return _value; }
}
public bool IsLeaf { get { return Left == null; } }
private BinTree(BinTree<T> left, BinTree<T> right, T value)
{
_left = left;
_right = right;
_value = value;
}
public BinTree(T value) : this(null, null, value) { }
public BinTree(IEnumerable<T> values)
{
// ReSharper disable PossibleMultipleEnumeration
_value = values.First();
foreach (var value in values.Skip(1))
{
Insert(value);
}
// ReSharper restore PossibleMultipleEnumeration
}
public void Insert(T value)
{
if (IsLeaf)
{
if (value.CompareTo(Value) < 0)
{
_left = new BinTree<T>(value);
_right = new BinTree<T>(Value);
}
else
{
_left = new BinTree<T>(Value);
_right = new BinTree<T>(value);
_value = value;
}
}
else
{
if (value.CompareTo(Value) < 0)
{
Left.Insert(value);
}
else
{
Right.Insert(value);
}
}
}
public IEnumerable<T> GetLeaves()
{
if (IsLeaf)
{
yield return Value;
yield break;
}
foreach (var val in Left.GetLeaves())
{
yield return val;
}
foreach (var val in Right.GetLeaves())
{
yield return val;
}
}
internal bool CompareTo(BinTree<T> other)
{
return other.GetLeaves().Zip(GetLeaves(), (t1, t2) => t1.CompareTo(t2) == 0).All(f => f);
}
}
}
|
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
|
#M4
|
M4
|
define(`lim',100)dnl
define(`for',
`ifelse($#,0,
``$0'',
`ifelse(eval($2<=$3),1,
`pushdef(`$1',$2)$5`'popdef(`$1')$0(`$1',eval($2+$4),$3,$4,`$5')')')')dnl
for(`j',2,lim,1,
`ifdef(a[j],
`',
`j for(`k',eval(j*j),lim,j,
`define(a[k],1)')')')
|
http://rosettacode.org/wiki/Scope_modifiers
|
Scope modifiers
|
Most programming languages offer support for subroutines.
When execution changes between subroutines, different sets of variables and functions ("scopes") are available to the program.
Frequently these sets are defined by the placement of the variable and function declarations ("static scoping" or "lexical scoping").
These sets may also be defined by special modifiers to the variable and function declarations.
Show the different scope modifiers available in your language and briefly explain how they change the scope of their variable or function.
If your language has no scope modifiers, note it.
|
#Phix
|
Phix
|
forward function localf() -- not normally necesssary, but will not harm
forward global function globalf() -- ""
function localf()
return 1
end function
global function globalf()
return 2
end function
|
http://rosettacode.org/wiki/Scope_modifiers
|
Scope modifiers
|
Most programming languages offer support for subroutines.
When execution changes between subroutines, different sets of variables and functions ("scopes") are available to the program.
Frequently these sets are defined by the placement of the variable and function declarations ("static scoping" or "lexical scoping").
These sets may also be defined by special modifiers to the variable and function declarations.
Show the different scope modifiers available in your language and briefly explain how they change the scope of their variable or function.
If your language has no scope modifiers, note it.
|
#PicoLisp
|
PicoLisp
|
$a = "foo" # global scope
function test {
$a = "bar" # local scope
Write-Host Local: $a # "bar" - local variable
Write-Host Global: $global:a # "foo" - global variable
}
|
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).
|
#FreeBASIC
|
FreeBASIC
|
Dim As Integer cocos = 11
For ns As Integer = 2 To 9
Dim As Integer oculta(ns)
cocos = Int(cocos / ns) * ns + 1
Do
Dim As Integer nc = cocos
For s As Integer = 1 To ns+1
If nc Mod ns = 1 Then
oculta(s-1) = Int(nc / ns)
nc = nc - (oculta(s-1) + 1)
If s = ns And Not (nc Mod ns) Then
Print ns; " marineros requieren un m¡nimo de"; cocos; " cocos"
For t As Integer = 1 To ns
Print !"\tEl marinero"; t; " se esconde"; oculta(t - 1)
Next t
Print !"\tEl mono obtiene"; ns
Print !"\tFinalmente, cada marinero se lleva"; Int(nc / ns); !"\n"
Exit Do
End If
Else
Exit For
End If
Next s
cocos += ns
Loop
Next ns
Sleep
|
http://rosettacode.org/wiki/Secure_temporary_file
|
Secure temporary file
|
Task
Create a temporary file, securely and exclusively (opening it such that there are no possible race conditions).
It's fine assuming local filesystem semantics (NFS or other networking filesystems can have signficantly more complicated semantics for satisfying the "no race conditions" criteria).
The function should automatically resolve name collisions and should only fail in cases where permission is denied, the filesystem is read-only or full, or similar conditions exist (returning an error or raising an exception as appropriate to the language/environment).
|
#UNIX_Shell
|
UNIX Shell
|
RESTOREUMASK=$(umask)
TRY=0
while :; do
TRY=$(( TRY + 1 ))
umask 0077
MYTMP=${TMPDIR:-/tmp}/$(basename $0).$$.$(date +%s).$TRY
trap "rm -fr $MYTMP" EXIT
mkdir "$MYTMP" 2>/dev/null && break
done
umask "$RESTOREUMASK"
cd "$MYTMP" || {
echo "Temporary directory failure on $MYTMP" >&2
exit 1; }
|
http://rosettacode.org/wiki/Secure_temporary_file
|
Secure temporary file
|
Task
Create a temporary file, securely and exclusively (opening it such that there are no possible race conditions).
It's fine assuming local filesystem semantics (NFS or other networking filesystems can have signficantly more complicated semantics for satisfying the "no race conditions" criteria).
The function should automatically resolve name collisions and should only fail in cases where permission is denied, the filesystem is read-only or full, or similar conditions exist (returning an error or raising an exception as appropriate to the language/environment).
|
#Wren
|
Wren
|
import "random" for Random
import "/ioutil" for File, FileUtil
import "/fmt" for Fmt
var rand = Random.new()
var createTempFile = Fn.new { |lines|
var tmp
while (true) {
// create a name which includes a random 6 digit number
tmp = "/tmp/temp%(Fmt.swrite("$06d", rand.int(1e6))).tmp"
if (!File.exists(tmp)) break
}
FileUtil.writeLines(tmp, lines)
return tmp
}
var lines = ["one", "two", "three"]
var tmp = createTempFile.call(lines)
System.print("Temporary file path: %(tmp)")
System.print("Original contents of temporary file:")
System.print(File.read(tmp))
// append some more lines
var lines2 = ["four", "five", "six"]
FileUtil.appendLines(tmp, lines2)
System.print("Updated contents of temporary file:")
System.print(File.read(tmp))
File.delete(tmp)
System.print("Temporary file deleted.")
|
http://rosettacode.org/wiki/Scope/Function_names_and_labels
|
Scope/Function names and labels
|
Task
Explain or demonstrate the levels of visibility of function names and labels within the language.
See also
Variables for levels of scope relating to visibility of program variables
Scope modifiers for general scope modification facilities
|
#PL.2FI
|
PL/I
|
Functions are normally internal to a program. If they are at the nesting level
immediately within the program, they are accessible from anywhere in the program.
Functions can also be encapsuled in a package, and the function name exported.
Functions can be compiled separately, and then linked with a program
in which case they are globally accessible.
|
http://rosettacode.org/wiki/Scope/Function_names_and_labels
|
Scope/Function names and labels
|
Task
Explain or demonstrate the levels of visibility of function names and labels within the language.
See also
Variables for levels of scope relating to visibility of program variables
Scope modifiers for general scope modification facilities
|
#PowerShell
|
PowerShell
|
function global:Get-DependentService
{
Get-Service | Where-Object {$_.DependentServices}
}
|
http://rosettacode.org/wiki/Scope/Function_names_and_labels
|
Scope/Function names and labels
|
Task
Explain or demonstrate the levels of visibility of function names and labels within the language.
See also
Variables for levels of scope relating to visibility of program variables
Scope modifiers for general scope modification facilities
|
#Python
|
Python
|
(define (foo x)
(define (bar y) (+ x y))
(bar 2))
(foo 1) ; => 3
(bar 1) ; => error
|
http://rosettacode.org/wiki/Scope/Function_names_and_labels
|
Scope/Function names and labels
|
Task
Explain or demonstrate the levels of visibility of function names and labels within the language.
See also
Variables for levels of scope relating to visibility of program variables
Scope modifiers for general scope modification facilities
|
#Racket
|
Racket
|
(define (foo x)
(define (bar y) (+ x y))
(bar 2))
(foo 1) ; => 3
(bar 1) ; => error
|
http://rosettacode.org/wiki/Scope/Function_names_and_labels
|
Scope/Function names and labels
|
Task
Explain or demonstrate the levels of visibility of function names and labels within the language.
See also
Variables for levels of scope relating to visibility of program variables
Scope modifiers for general scope modification facilities
|
#Raku
|
Raku
|
CALLER # Contextual symbols in the immediate caller's lexical scope
OUTER # Symbols in the next outer lexical scope
UNIT # Symbols in the outermost lexical scope of compilation unit
SETTING # Lexical symbols in the unit's DSL (usually CORE)
PARENT # Symbols in this package's parent package (or lexical scope)
|
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
|
#C
|
C
|
#include <stdint.h> /* intptr_t */
#include <stdio.h>
#include <stdlib.h> /* bsearch */
#include <string.h>
#include <search.h> /* lfind */
#define LEN(x) (sizeof(x) / sizeof(x[0]))
struct cd {
char *name;
double population;
};
/* Return -1 if name could not be found */
int search_get_index_by_name(const char *name, const struct cd *data, const size_t data_length,
int (*cmp_func)(const void *, const void *))
{
struct cd key = { (char *) name, 0 };
struct cd *match = bsearch(&key, data, data_length,
sizeof(struct cd), cmp_func);
if (match == NULL)
return -1;
else
return ((intptr_t) match - (intptr_t) data) / sizeof(struct cd);
}
/* Return -1 if no matching record can be found */
double search_get_pop_by_name(const char *name, const struct cd *data, size_t data_length,
int (*cmp_func)(const void *, const void *))
{
struct cd key = { (char *) name, 0 };
struct cd *match = lfind(&key, data, &data_length,
sizeof(struct cd), cmp_func);
if (match == NULL)
return -1;
else
return match->population;
}
/* Return NULL if no value satisfies threshold */
char* search_get_pop_threshold(double pop_threshold, const struct cd *data, size_t data_length,
int (*cmp_func)(const void *, const void *))
{
struct cd key = { NULL, pop_threshold };
struct cd *match = lfind(&key, data, &data_length,
sizeof(struct cd), cmp_func);
if (match == NULL)
return NULL;
else
return match->name;
}
int cd_nameChar_cmp(const void *a, const void *b)
{
struct cd *aa = (struct cd *) a;
struct cd *bb = (struct cd *) b;
int i,len = strlen(aa->name);
for(i=0;i<len;i++)
if(bb->name[i]!=aa->name[i])
return -1;
return 0;
}
int cd_name_cmp(const void *a, const void *b)
{
struct cd *aa = (struct cd *) a;
struct cd *bb = (struct cd *) b;
return strcmp(bb->name, aa->name);
}
int cd_pop_cmp(const void *a, const void *b)
{
struct cd *aa = (struct cd *) a;
struct cd *bb = (struct cd *) b;
return bb->population >= aa->population;
}
int main(void)
{
const struct cd citydata[] = {
{ "Lagos", 21 },
{ "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 }
};
const size_t citydata_length = LEN(citydata);
printf("%d\n", search_get_index_by_name("Dar Es Salaam", citydata, citydata_length, cd_name_cmp));
printf("%s\n", search_get_pop_threshold(5, citydata, citydata_length, cd_pop_cmp));
printf("%lf\n", search_get_pop_by_name("A", citydata, citydata_length, cd_nameChar_cmp));
return 0;
}
|
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).
|
#C.2B.2B
|
C++
|
#include <algorithm>
#include <coroutine>
#include <iostream>
#include <memory>
#include <tuple>
#include <variant>
using namespace std;
class BinaryTree
{
// C++ does not have a built in tree type. The binary tree is a recursive
// data type that is represented by an empty tree or a node the has a value
// and a left and right sub-tree. A tuple represents the node and unique_ptr
// represents an empty vs. non-empty tree.
using Node = tuple<BinaryTree, int, BinaryTree>;
unique_ptr<Node> m_tree;
public:
// Provide ways to make trees
BinaryTree() = default; // Make an empty tree
BinaryTree(BinaryTree&& leftChild, int value, BinaryTree&& rightChild)
: m_tree {make_unique<Node>(move(leftChild), value, move(rightChild))} {}
BinaryTree(int value) : BinaryTree(BinaryTree{}, value, BinaryTree{}){}
BinaryTree(BinaryTree&& leftChild, int value)
: BinaryTree(move(leftChild), value, BinaryTree{}){}
BinaryTree(int value, BinaryTree&& rightChild)
: BinaryTree(BinaryTree{}, value, move(rightChild)){}
// Test if the tree is empty
explicit operator bool() const
{
return (bool)m_tree;
}
// Get the value of the root node of the tree
int Value() const
{
return get<1>(*m_tree);
}
// Get the left child tree
const BinaryTree& LeftChild() const
{
return get<0>(*m_tree);
}
// Get the right child tree
const BinaryTree& RightChild() const
{
return get<2>(*m_tree);
}
};
// Define a promise type to be used for coroutines
struct TreeWalker {
struct promise_type {
int val;
suspend_never initial_suspend() noexcept {return {};}
suspend_never return_void() noexcept {return {};}
suspend_always final_suspend() noexcept {return {};}
void unhandled_exception() noexcept { }
TreeWalker get_return_object()
{
return TreeWalker{coroutine_handle<promise_type>::from_promise(*this)};
}
suspend_always yield_value(int x) noexcept
{
val=x;
return {};
}
};
coroutine_handle<promise_type> coro;
TreeWalker(coroutine_handle<promise_type> h): coro(h) {}
~TreeWalker()
{
if(coro) coro.destroy();
}
// Define an iterator type to work with the coroutine
class Iterator
{
const coroutine_handle<promise_type>* m_h = nullptr;
public:
Iterator() = default;
constexpr Iterator(const coroutine_handle<promise_type>* h) : m_h(h){}
Iterator& operator++()
{
m_h->resume();
return *this;
}
Iterator operator++(int)
{
auto old(*this);
m_h->resume();
return old;
}
int operator*() const
{
return m_h->promise().val;
}
bool operator!=(monostate) const noexcept
{
return !m_h->done();
return m_h && !m_h->done();
}
bool operator==(monostate) const noexcept
{
return !operator!=(monostate{});
}
};
constexpr Iterator begin() const noexcept
{
return Iterator(&coro);
}
constexpr monostate end() const noexcept
{
return monostate{};
}
};
// Allow the iterator to be used like a standard library iterator
namespace std {
template<>
class iterator_traits<TreeWalker::Iterator>
{
public:
using difference_type = std::ptrdiff_t;
using size_type = std::size_t;
using value_type = int;
using pointer = int*;
using reference = int&;
using iterator_category = std::input_iterator_tag;
};
}
// A coroutine that iterates though all of the fringe nodes
TreeWalker WalkFringe(const BinaryTree& tree)
{
if(tree)
{
auto& left = tree.LeftChild();
auto& right = tree.RightChild();
if(!left && !right)
{
// a fringe node because it has no children
co_yield tree.Value();
}
for(auto v : WalkFringe(left))
{
co_yield v;
}
for(auto v : WalkFringe(right))
{
co_yield v;
}
}
co_return;
}
// Print a tree
void PrintTree(const BinaryTree& tree)
{
if(tree)
{
cout << "(";
PrintTree(tree.LeftChild());
cout << tree.Value();
PrintTree(tree.RightChild());
cout <<")";
}
}
// Compare two trees
void Compare(const BinaryTree& tree1, const BinaryTree& tree2)
{
// Create a lazy range for both trees
auto walker1 = WalkFringe(tree1);
auto walker2 = WalkFringe(tree2);
// Compare the ranges.
bool sameFringe = ranges::equal(walker1.begin(), walker1.end(),
walker2.begin(), walker2.end());
// Print the results
PrintTree(tree1);
cout << (sameFringe ? " has same fringe as " : " has different fringe than ");
PrintTree(tree2);
cout << "\n";
}
int main()
{
// Create two trees that that are different but have the same fringe nodes
BinaryTree tree1(BinaryTree{6}, 77, BinaryTree{BinaryTree{3}, 77,
BinaryTree{77, BinaryTree{9}}});
BinaryTree tree2(BinaryTree{BinaryTree{BinaryTree{6}, 77}, 77, BinaryTree{
BinaryTree{3}, 77, BinaryTree{9}}});
// Create a tree with a different fringe
BinaryTree tree3(BinaryTree{BinaryTree{BinaryTree{6}, 77}, 77, BinaryTree{77, BinaryTree{9}}});
// Compare the trees
Compare(tree1, tree2);
Compare(tree1, tree3);
}
|
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
|
#MAD
|
MAD
|
NORMAL MODE IS INTEGER
R TO GENERATE MORE PRIMES, CHANGE BOTH THESE NUMBERS
BOOLEAN PRIME
DIMENSION PRIME(10000)
MAXVAL = 10000
PRINT FORMAT BEGIN,MAXVAL
R ASSUME ALL ARE PRIMES AT BEGINNING
THROUGH SET, FOR I=2, 1, I.G.MAXVAL
SET PRIME(I) = 1B
R REMOVE ALL PROVEN COMPOSITES
SQMAX = SQRT.(MAXVAL)
THROUGH NEXT, FOR P=2, 1, P.G.SQMAX
WHENEVER PRIME(P)
THROUGH MARK, FOR I=P*P, P, I.G.MAXVAL
MARK PRIME(I) = 0B
NEXT END OF CONDITIONAL
R PRINT PRIMES
THROUGH SHOW, FOR P=2, 1, P.G.MAXVAL
SHOW WHENEVER PRIME(P), PRINT FORMAT NUMFMT, P
VECTOR VALUES BEGIN = $13HPRIMES UP TO ,I9*$
VECTOR VALUES NUMFMT = $I9*$
END OF PROGRAM
|
http://rosettacode.org/wiki/Scope_modifiers
|
Scope modifiers
|
Most programming languages offer support for subroutines.
When execution changes between subroutines, different sets of variables and functions ("scopes") are available to the program.
Frequently these sets are defined by the placement of the variable and function declarations ("static scoping" or "lexical scoping").
These sets may also be defined by special modifiers to the variable and function declarations.
Show the different scope modifiers available in your language and briefly explain how they change the scope of their variable or function.
If your language has no scope modifiers, note it.
|
#PowerShell
|
PowerShell
|
$a = "foo" # global scope
function test {
$a = "bar" # local scope
Write-Host Local: $a # "bar" - local variable
Write-Host Global: $global:a # "foo" - global variable
}
|
http://rosettacode.org/wiki/Scope_modifiers
|
Scope modifiers
|
Most programming languages offer support for subroutines.
When execution changes between subroutines, different sets of variables and functions ("scopes") are available to the program.
Frequently these sets are defined by the placement of the variable and function declarations ("static scoping" or "lexical scoping").
These sets may also be defined by special modifiers to the variable and function declarations.
Show the different scope modifiers available in your language and briefly explain how they change the scope of their variable or function.
If your language has no scope modifiers, note it.
|
#PureBasic
|
PureBasic
|
;define a local integer variable by simply using it
baseAge.i = 10
;explicitly define local strings
Define person.s = "Amy", friend.s = "Susan"
;define variables that are both accessible inside and outside procedures
Global ageDiff = 3
Global extraYears = 5
Procedure test()
;define a local integer variable by simply using it
baseAge.i = 30
;explicitly define a local string
Define person.s = "Bob"
;allow access to a local variable in the main body of code
Shared friend
;create a local variable distinct from a variable with global scope having the same name
Protected extraYears = 2
PrintN(person + " and " + friend + " are " + Str(baseAge) + " and " + Str(baseAge + ageDiff + extraYears) + " years old.")
EndProcedure
If OpenConsole()
test()
PrintN(person + " and " + friend + " are " + Str(baseAge) + " and " + Str(baseAge + ageDiff + extraYears) + " years old.")
Print(#CRLF$ + #CRLF$ + "Press ENTER to exit")
Input()
CloseConsole()
EndIf
|
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).
|
#Go
|
Go
|
package main
import "fmt"
func main() {
coconuts := 11
outer:
for ns := 2; ns < 10; ns++ {
hidden := make([]int, ns)
coconuts = (coconuts/ns)*ns + 1
for {
nc := coconuts
for s := 1; s <= ns; s++ {
if nc%ns == 1 {
hidden[s-1] = nc / ns
nc -= hidden[s-1] + 1
if s == ns && nc%ns == 0 {
fmt.Println(ns, "sailors require a minimum of", coconuts, "coconuts")
for t := 1; t <= ns; t++ {
fmt.Println("\tSailor", t, "hides", hidden[t-1])
}
fmt.Println("\tThe monkey gets", ns)
fmt.Println("\tFinally, each sailor takes", nc/ns, "\b\n")
continue outer
}
} else {
break
}
}
coconuts += ns
}
}
}
|
http://rosettacode.org/wiki/Secure_temporary_file
|
Secure temporary file
|
Task
Create a temporary file, securely and exclusively (opening it such that there are no possible race conditions).
It's fine assuming local filesystem semantics (NFS or other networking filesystems can have signficantly more complicated semantics for satisfying the "no race conditions" criteria).
The function should automatically resolve name collisions and should only fail in cases where permission is denied, the filesystem is read-only or full, or similar conditions exist (returning an error or raising an exception as appropriate to the language/environment).
|
#zkl
|
zkl
|
zkl: File.mktmp()
File(zklTmpFile082p1V)
|
http://rosettacode.org/wiki/Scope/Function_names_and_labels
|
Scope/Function names and labels
|
Task
Explain or demonstrate the levels of visibility of function names and labels within the language.
See also
Variables for levels of scope relating to visibility of program variables
Scope modifiers for general scope modification facilities
|
#REXX
|
REXX
|
/*REXX program demonstrates the use of labels and also a CALL statement. */
blarney = -0 /*just a blarney & balderdash statement*/
signal do_add /*transfer program control to a label.*/
ttt = sinD(30) /*this REXX statement is never executed*/
/* [↓] Note the case doesn't matter. */
DO_Add: /*coming here from the SIGNAL statement*/
say 'calling the sub: add.2.args'
call add.2.args 1, 7 /*pass two arguments: 1 and a 7 */
say 'sum =' result /*display the result from the function.*/
exit /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
add.2.args: procedure; parse arg x,y; return x+y /*first come, first served ···*/
add.2.args: say 'Whoa Nelly!! Has the universe run amok?' /*didactic, but never executed*/
add.2.args: return arg(1) + arg(2) /*concise, " " " */
|
http://rosettacode.org/wiki/Scope/Function_names_and_labels
|
Scope/Function names and labels
|
Task
Explain or demonstrate the levels of visibility of function names and labels within the language.
See also
Variables for levels of scope relating to visibility of program variables
Scope modifiers for general scope modification facilities
|
#Ring
|
Ring
|
# Project : Scope/Function names and labels
see "What is your name?" + nl
give name
welcome(name)
func welcome(name)
see "hello " + name + nl
|
http://rosettacode.org/wiki/Scope/Function_names_and_labels
|
Scope/Function names and labels
|
Task
Explain or demonstrate the levels of visibility of function names and labels within the language.
See also
Variables for levels of scope relating to visibility of program variables
Scope modifiers for general scope modification facilities
|
#Ruby
|
Ruby
|
def welcome(name)
puts "hello #{name}"
end
puts "What is your name?"
$name = STDIN.gets
welcome($name)
return
|
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
|
#C.23
|
C#
|
using System;
using System.Collections.Generic;
namespace RosettaSearchListofRecords
{
class Program
{
static void Main(string[] args)
{
var dataset = new List<Dictionary<string, object>>() {
new Dictionary<string, object> {{ "name" , "Lagos"}, {"population", 21.0 }},
new Dictionary<string, object> {{ "name" , "Cairo"}, {"population", 15.2 }},
new Dictionary<string, object> {{ "name" , "Kinshasa-Brazzaville"}, {"population", 11.3 }},
new Dictionary<string, object> {{ "name" , "Greater Johannesburg"}, {"population", 7.55 }},
new Dictionary<string, object> {{ "name" , "Mogadishu"}, {"population", 5.85 }},
new Dictionary<string, object> {{ "name" , "Khartoum-Omdurman"}, {"population", 4.98 }},
new Dictionary<string, object> {{ "name" , "Dar Es Salaam"}, {"population", 4.7 }},
new Dictionary<string, object> {{ "name" , "Alexandria"}, {"population", 4.58 }},
new Dictionary<string, object> {{ "name" , "Abidjan"}, {"population", 4.4 }},
new Dictionary<string, object> {{ "name" , "Casablanca"}, {"population", 3.98 }}
};
// Find the (zero-based) index of the first city in the list whose name is "Dar Es Salaam"
var index = dataset.FindIndex(x => ((string)x["name"]) == "Dar Es Salaam");
Console.WriteLine(index);
// Find the name of the first city in this list whose population is less than 5 million
var name = (string)dataset.Find(x => (double)x["population"] < 5.0)["name"];
Console.WriteLine(name);
// Find the population of the first city in this list whose name starts with the letter "A"
var aNamePopulation = (double)dataset.Find(x => ((string)x["name"]).StartsWith("A"))["population"];
Console.WriteLine(aNamePopulation);
}
}
}
|
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].
|
#Ada
|
Ada
|
type Interval is record
Lower : Float;
Upper : Float;
end record;
|
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).
|
#Clojure
|
Clojure
|
(defn fringe-seq [branch? children content tree]
(letfn [(walk [node]
(lazy-seq
(if (branch? node)
(if (empty? (children node))
(list (content node))
(mapcat walk (children node)))
(list node))))]
(walk tree)))
|
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
|
#Maple
|
Maple
|
Eratosthenes := proc(n::posint)
local numbers_to_check, i, k;
numbers_to_check := [seq(2 .. n)];
for i from 2 to floor(sqrt(n)) do
for k from i by i while k <= n do
if evalb(k <> i) then
numbers_to_check[k - 1] := 0;
end if;
end do;
end do;
numbers_to_check := remove(x -> evalb(x = 0), numbers_to_check);
return numbers_to_check;
end proc:
|
http://rosettacode.org/wiki/Scope_modifiers
|
Scope modifiers
|
Most programming languages offer support for subroutines.
When execution changes between subroutines, different sets of variables and functions ("scopes") are available to the program.
Frequently these sets are defined by the placement of the variable and function declarations ("static scoping" or "lexical scoping").
These sets may also be defined by special modifiers to the variable and function declarations.
Show the different scope modifiers available in your language and briefly explain how they change the scope of their variable or function.
If your language has no scope modifiers, note it.
|
#Python
|
Python
|
>>> x="From global scope"
>>> def outerfunc():
x = "From scope at outerfunc"
def scoped_local():
x = "scope local"
return "scoped_local scope gives x = " + x
print(scoped_local())
def scoped_nonlocal():
nonlocal x
return "scoped_nonlocal scope gives x = " + x
print(scoped_nonlocal())
def scoped_global():
global x
return "scoped_global scope gives x = " + x
print(scoped_global())
def scoped_notdefinedlocally():
return "scoped_notdefinedlocally scope gives x = " + x
print(scoped_notdefinedlocally())
>>> outerfunc()
scoped_local scope gives x = scope local
scoped_nonlocal scope gives x = From scope at outerfunc
scoped_global scope gives x = From global scope
scoped_notdefinedlocally scope gives x = From global scope
>>>
|
http://rosettacode.org/wiki/Scope_modifiers
|
Scope modifiers
|
Most programming languages offer support for subroutines.
When execution changes between subroutines, different sets of variables and functions ("scopes") are available to the program.
Frequently these sets are defined by the placement of the variable and function declarations ("static scoping" or "lexical scoping").
These sets may also be defined by special modifiers to the variable and function declarations.
Show the different scope modifiers available in your language and briefly explain how they change the scope of their variable or function.
If your language has no scope modifiers, note it.
|
#R
|
R
|
X <- "global x"
f <- function() {
x <- "local x"
print(x) #"local x"
}
f() #prints "local x"
print(x) #prints "global x"
|
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).
|
#Haskell
|
Haskell
|
import Control.Monad ((>=>))
import Data.Maybe (mapMaybe)
import System.Environment (getArgs)
-- Takes the number of sailors and the final number of coconuts. Returns
-- Just the associated initial number of coconuts and Nothing otherwise.
tryFor :: Int -> Int -> Maybe Int
tryFor s = foldr (>=>) pure $ replicate s step
where
step n
| n `mod` (s - 1) == 0 = Just $ n * s `div` (s - 1) + 1
| otherwise = Nothing
-- Gets the number of sailors from the first command-line argument and
-- assumes 5 as a default if none is given. Then uses tryFor to find the
-- smallest solution.
main :: IO ()
main = do
args <- getArgs
let n =
case args of
[] -> 5
s:_ -> read s
a = head . mapMaybe (tryFor n) $ [n,2 * n ..]
print a
|
http://rosettacode.org/wiki/Scope/Function_names_and_labels
|
Scope/Function names and labels
|
Task
Explain or demonstrate the levels of visibility of function names and labels within the language.
See also
Variables for levels of scope relating to visibility of program variables
Scope modifiers for general scope modification facilities
|
#Scala
|
Scala
|
object ScopeFunction extends App {
val c = new C()
val d = new D()
val n = 1
def a() = println("calling a")
trait E {
def m() = println("calling m")
}
a() // OK as a is internal
B.f() // OK as f is public
class C {
// class level function visible everywhere, by default
def g() = println("calling g")
// class level function only visible within C and its subclasses
protected def i() {
println("calling i")
println("calling h") // OK as h within same class
// nested function in scope until end of i
def j() = println("calling j")
j()
}
// class level function only visible within C
private def h() = println("calling h")
}
c.g() // OK as g is public but can't call h or i via c
class D extends C with E {
// class level function visible anywhere within the same module
def k() {
println("calling k")
i() // OK as C.i is protected
m() // OK as E.m is public and has a body
}
}
d.k() // OK as k is public
object B {
// object level function visible everywhere, by default
def f() = println("calling f")
}
val l = (i:Int, j: Int) => println(i,j)
println("Good-bye!") // will be executed
}
|
http://rosettacode.org/wiki/Scope/Function_names_and_labels
|
Scope/Function names and labels
|
Task
Explain or demonstrate the levels of visibility of function names and labels within the language.
See also
Variables for levels of scope relating to visibility of program variables
Scope modifiers for general scope modification facilities
|
#Sidef
|
Sidef
|
# Nested functions
func outer {
func inner {}; # not visible outside
}
# Nested classes
class Outer {
class Inner {}; # not visisble outside
}
|
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
|
#C.2B.2B
|
C++
|
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
struct city {
std::string name;
float population;
};
int main()
{
std::vector<city> cities = {
{ "Lagos", 21 },
{ "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 },
};
auto i1 = std::find_if( cities.begin(), cities.end(),
[](city c){ return c.name == "Dar Es Salaam"; } );
if (i1 != cities.end()) {
std::cout << i1 - cities.begin() << "\n";
}
auto i2 = std::find_if( cities.begin(), cities.end(),
[](city c){ return c.population < 5.0; } );
if (i2 != cities.end()) {
std::cout << i2->name << "\n";
}
auto i3 = std::find_if( cities.begin(), cities.end(),
[](city c){ return c.name.length() > 0 && c.name[0] == 'A'; } );
if (i3 != cities.end()) {
std::cout << i3->population << "\n";
}
}
|
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].
|
#AutoHotkey
|
AutoHotkey
|
Msgbox % IntervalAdd(1,2) ; [2.999999,3.000001]
SetFormat, FloatFast, 0.20
Msgbox % IntervalAdd(1,2) ; [2.99999999999999910000,3.00000000000000090000]
;In v1.0.48+, floating point variables have about 15 digits of precision internally
;unless SetFormat Float (i.e. the slow mode) is present anywhere in the script.
;In that case, the stored precision of floating point numbers is determined by A_FormatFloat.
;As there is no way for this function to know whether this is the case or not,
;it conservatively uses A_FormatFloat in all cases.
IntervalAdd(a,b){
err:=0.1**(SubStr(A_FormatFloat,3) > 15 ? 15 : SubStr(A_FormatFloat,3))
Return "[" a+b-err ","a+b+err "]"
}
|
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].
|
#C
|
C
|
#include <fenv.h> /* fegetround(), fesetround() */
#include <stdio.h> /* printf() */
/*
* Calculates an interval for a + b.
* interval[0] <= a + b
* a + b <= interval[1]
*/
void
safe_add(volatile double interval[2], volatile double a, volatile double b)
{
#pragma STDC FENV_ACCESS ON
unsigned int orig;
orig = fegetround();
fesetround(FE_DOWNWARD); /* round to -infinity */
interval[0] = a + b;
fesetround(FE_UPWARD); /* round to +infinity */
interval[1] = a + b;
fesetround(orig);
}
int
main()
{
const double nums[][2] = {
{1, 2},
{0.1, 0.2},
{1e100, 1e-100},
{1e308, 1e308},
};
double ival[2];
int i;
for (i = 0; i < sizeof(nums) / sizeof(nums[0]); i++) {
/*
* Calculate nums[i][0] + nums[i][1].
*/
safe_add(ival, nums[i][0], nums[i][1]);
/*
* Print the result. %.17g gives the best output.
* %.16g or plain %g gives not enough digits.
*/
printf("%.17g + %.17g =\n", nums[i][0], nums[i][1]);
printf(" [%.17g, %.17g]\n", ival[0], ival[1]);
printf(" size %.17g\n\n", ival[1] - ival[0]);
}
return 0;
}
|
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.
|
#ALGOL_68
|
ALGOL 68
|
# find and count safe and unsafe primes #
# safe primes are primes p such that ( p - 1 ) / 2 is also prime #
# unsafe primes are primes that are not safe #
PR heap=128M PR # set heap memory size for Algol 68G #
# returns a string representation of n with commas #
PROC commatise = ( INT n )STRING:
BEGIN
STRING result := "";
STRING unformatted = whole( n, 0 );
INT ch count := 0;
FOR c FROM UPB unformatted BY -1 TO LWB unformatted DO
IF ch count <= 2 THEN ch count +:= 1
ELSE ch count := 1; "," +=: result
FI;
unformatted[ c ] +=: result
OD;
result
END # commatise # ;
# sieve values #
CHAR prime = "P"; # unclassified prime #
CHAR safe = "S"; # safe prime #
CHAR unsafe = "U"; # unsafe prime #
CHAR composite = "C"; # non-prime #
# sieve of Eratosthenes: sets s[i] to prime if i is a prime, #
# composite otherwise #
PROC sieve = ( REF[]CHAR s )VOID:
BEGIN
# start with everything flagged as prime #
FOR i TO UPB s DO s[ i ] := prime OD;
# sieve out the non-primes #
s[ 1 ] := composite;
FOR i FROM 2 TO ENTIER sqrt( UPB s ) DO
IF s[ i ] = prime THEN FOR p FROM i * i BY i TO UPB s DO s[ p ] := composite OD FI
OD
END # sieve # ;
INT max number = 10 000 000;
# construct a sieve of primes up to the maximum number #
[ 1 : max number ]CHAR primes;
sieve( primes );
# classify the primes #
# ( p - 1 ) OVER 2 is non-zero for p >= 3, thus we know 2 is unsafe #
primes[ 2 ] := unsafe;
FOR p FROM 3 TO UPB primes DO
IF primes[ p ] = prime THEN
primes[ p ] := IF primes[ ( p - 1 ) OVER 2 ] = composite THEN unsafe ELSE safe FI
FI
OD;
# count the primes of each type #
INT safe1 := 0, safe10 := 0;
INT unsafe1 := 0, unsafe10 := 0;
FOR p FROM LWB primes TO UPB primes DO
IF primes[ p ] = safe THEN
safe10 +:= 1;
IF p < 1 000 000 THEN safe1 +:= 1 FI
ELIF primes[ p ] = unsafe THEN
unsafe10 +:= 1;
IF p < 1 000 000 THEN unsafe1 +:= 1 FI
FI
OD;
INT safe count := 0;
print( ( "first 35 safe primes:", newline ) );
FOR p WHILE safe count < 35 DO IF primes[ p ] = safe THEN print( ( " ", whole( p, 0 ) ) ); safe count +:= 1 FI OD;
print( ( newline ) );
print( ( "safe primes below 1,000,000: ", commatise( safe1 ), newline ) );
print( ( "safe primes below 10,000,000: ", commatise( safe10 ), newline ) );
print( ( "first 40 unsafe primes:", newline ) );
INT unsafe count := 0;
FOR p WHILE unsafe count < 40 DO IF primes[ p ] = unsafe THEN print( ( " ", whole( p, 0 ) ) ); unsafe count +:= 1 FI OD;
print( ( newline ) );
print( ( "unsafe primes below 1,000,000: ", commatise( unsafe1 ), newline ) );
print( ( "unsafe primes below 10,000,000: ", commatise( unsafe10 ), newline ) )
|
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).
|
#D
|
D
|
struct Node(T) {
T data;
Node* L, R;
}
bool sameFringe(T)(Node!T* t1, Node!T* t2) {
T[] scan(Node!T* t) {
if (!t) return [];
return (!t.L && !t.R) ? [t.data] : scan(t.L) ~ scan(t.R);
}
return scan(t1) == scan(t2);
}
void main() {
import std.stdio;
alias N = Node!int;
auto t1 = new N(10, new N(20, new N(30, new N(40), new N(50))));
auto t2 = new N(1, new N(2, new N(3, new N(40), new N(50))));
writeln(sameFringe(t1, t2));
auto t3 = new N(1, new N(2, new N(3, new N(40), new N(51))));
writeln(sameFringe(t1, 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
|
#Mathematica.2FWolfram_Language
|
Mathematica/Wolfram Language
|
Eratosthenes[n_] := Module[{numbers = Range[n]},
Do[If[numbers[[i]] != 0, Do[numbers[[i j]] = 0, {j, 2, n/i}]], {i,
2, Sqrt[n]}];
Select[numbers, # > 1 &]]
Eratosthenes[100]
|
http://rosettacode.org/wiki/Scope_modifiers
|
Scope modifiers
|
Most programming languages offer support for subroutines.
When execution changes between subroutines, different sets of variables and functions ("scopes") are available to the program.
Frequently these sets are defined by the placement of the variable and function declarations ("static scoping" or "lexical scoping").
These sets may also be defined by special modifiers to the variable and function declarations.
Show the different scope modifiers available in your language and briefly explain how they change the scope of their variable or function.
If your language has no scope modifiers, note it.
|
#Racket
|
Racket
|
my $lexical-variable;
our $package-variable;
state $persistent-lexical;
has $.public-attribute;
|
http://rosettacode.org/wiki/Scope_modifiers
|
Scope modifiers
|
Most programming languages offer support for subroutines.
When execution changes between subroutines, different sets of variables and functions ("scopes") are available to the program.
Frequently these sets are defined by the placement of the variable and function declarations ("static scoping" or "lexical scoping").
These sets may also be defined by special modifiers to the variable and function declarations.
Show the different scope modifiers available in your language and briefly explain how they change the scope of their variable or function.
If your language has no scope modifiers, note it.
|
#Raku
|
Raku
|
my $lexical-variable;
our $package-variable;
state $persistent-lexical;
has $.public-attribute;
|
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).
|
#J
|
J
|
I.(=<.)%&5 verb def'4*(y-1)%5'^:5 i.10000
3121
|
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).
|
#Java
|
Java
|
public class Test {
static boolean valid(int n, int nuts) {
for (int k = n; k != 0; k--, nuts -= 1 + nuts / n)
if (nuts % n != 1)
return false;
return nuts != 0 && (nuts % n == 0);
}
public static void main(String[] args) {
int x = 0;
for (int n = 2; n < 10; n++) {
while (!valid(n, x))
x++;
System.out.printf("%d: %d%n", n, x);
}
}
}
|
http://rosettacode.org/wiki/Scope/Function_names_and_labels
|
Scope/Function names and labels
|
Task
Explain or demonstrate the levels of visibility of function names and labels within the language.
See also
Variables for levels of scope relating to visibility of program variables
Scope modifiers for general scope modification facilities
|
#Tcl
|
Tcl
|
doFoo 1 2 3; # Will produce an error
proc doFoo {a b c} {
puts [expr {$a + $b*$c}]
}
doFoo 1 2 3; # Will now print 7 (and will continue to do so until doFoo is renamed or deleted
|
http://rosettacode.org/wiki/Scope/Function_names_and_labels
|
Scope/Function names and labels
|
Task
Explain or demonstrate the levels of visibility of function names and labels within the language.
See also
Variables for levels of scope relating to visibility of program variables
Scope modifiers for general scope modification facilities
|
#UNIX_Shell
|
UNIX Shell
|
#!/bin/sh
multiply 3 4 # This will not work
echo $? # A bogus value was returned because multiply definition has not yet been run.
multiply() {
return `expr $1 \* $2` # The backslash is required to suppress interpolation
}
multiply 3 4 # Ok. It works now.
echo $? # This gives 12
|
http://rosettacode.org/wiki/Scope/Function_names_and_labels
|
Scope/Function names and labels
|
Task
Explain or demonstrate the levels of visibility of function names and labels within the language.
See also
Variables for levels of scope relating to visibility of program variables
Scope modifiers for general scope modification facilities
|
#Wren
|
Wren
|
//func.call() /* invalid, can't call func before its declared */
var func = Fn.new { System.print("func has been called.") }
func.call() // fine
//C.init() /* not OK, as C is null at this point */
class C {
static init() { method() } // fine even though 'method' not yet declared
static method() { System.print("method has been called.") }
}
C.init() // fine
|
http://rosettacode.org/wiki/Scope/Function_names_and_labels
|
Scope/Function names and labels
|
Task
Explain or demonstrate the levels of visibility of function names and labels within the language.
See also
Variables for levels of scope relating to visibility of program variables
Scope modifiers for general scope modification facilities
|
#XPL0
|
XPL0
|
class C{ fcn [private] f{} }
|
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
|
#Clojure
|
Clojure
|
(def records [{:idx 8, :name "Abidjan", :population 4.4}
{:idx 7, :name "Alexandria", :population 4.58}
{:idx 1, :name "Cairo", :population 15.2}
{:idx 9, :name "Casablanca", :population 3.98}
{:idx 6, :name "Dar Es Salaam", :population 4.7}
{:idx 3, :name "Greater Johannesburg", :population 7.55}
{:idx 5, :name "Khartoum-Omdurman", :population 4.98}
{:idx 2, :name "Kinshasa-Brazzaville", :population 11.3}
{:idx 0, :name "Lagos", :population 21.0}
{:idx 4, :name "Mogadishu", :population 5.85}])
(defn city->idx [recs city]
(-> (some #(when (= city (:name %)) %)
recs)
:idx))
(defn rec-with-max-population-below-n [recs limit]
(->> (sort-by :population > recs)
(drop-while (fn [r] (>= (:population r) limit)))
first))
(defn most-populous-city-below-n [recs limit]
(:name (rec-with-max-population-below-n recs limit)))
|
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].
|
#C.23
|
C#
|
using System;
namespace SafeAddition {
class Program {
static float NextUp(float d) {
if (d == 0.0) return float.Epsilon;
if (float.IsNaN(d) || float.IsNegativeInfinity(d) || float.IsPositiveInfinity(d)) return d;
byte[] bytes = BitConverter.GetBytes(d);
int dl = BitConverter.ToInt32(bytes, 0);
dl++;
bytes = BitConverter.GetBytes(dl);
return BitConverter.ToSingle(bytes, 0);
}
static float NextDown(float d) {
if (d == 0.0) return -float.Epsilon;
if (float.IsNaN(d) || float.IsNegativeInfinity(d) || float.IsPositiveInfinity(d)) return d;
byte[] bytes = BitConverter.GetBytes(d);
int dl = BitConverter.ToInt32(bytes, 0);
dl--;
bytes = BitConverter.GetBytes(dl);
return BitConverter.ToSingle(bytes, 0);
}
static Tuple<float, float> SafeAdd(float a, float b) {
return new Tuple<float, float>(NextDown(a + b), NextUp(a + b));
}
static void Main(string[] args) {
float a = 1.20f;
float b = 0.03f;
Console.WriteLine("({0} + {1}) is in the range {2}", a, b, SafeAdd(a, b));
}
}
}
|
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.
|
#AppleScript
|
AppleScript
|
-- Heavy-duty Sieve of Eratosthenes handler.
-- Returns a list containing either just the primes up to a given limit ('crossingsOut' = false) or, as in this task,
-- both the primes and 'missing values' representing the "crossed out" non-primes ('crossingsOut' = true).
on sieveForPrimes given limit:limit, crossingsOut:keepingZaps
if (limit < 1) then return {}
-- Build a list initially containing only 'missing values'. For speed, and to reduce the likelihood of hanging,
-- do this by building sublists of at most 5000 items and concatenating them afterwards.
script o
property sublists : {}
property numberList : {}
end script
set sublistSize to 5000
set mv to missing value -- Use a single 'missing value' instance for economy.
repeat sublistSize times
set end of o's numberList to mv
end repeat
-- Start with a possible < 5000-item sublist.
if (limit mod sublistSize > 0) then set end of o's sublists to items 1 thru (limit mod sublistSize) of o's numberList
-- Then any 5000-item sublists needed.
if (limit ≥ sublistSize) then
set end of o's sublists to o's numberList
repeat (limit div sublistSize - 1) times
set end of o's sublists to o's numberList's items
end repeat
end if
-- Concatenate them more-or-less evenly.
set subListCount to (count o's sublists)
repeat until (subListCount is 1)
set o's numberList to {}
repeat with i from 2 to subListCount by 2
set end of o's numberList to (item (i - 1) of o's sublists) & (item i of o's sublists)
end repeat
if (i < subListCount) then set last item of o's numberList to (end of o's numberList) & (end of o's sublists)
set o's sublists to o's numberList
set subListCount to subListCount div 2
end repeat
set o's numberList to beginning of o's sublists
-- Set the relevant list positions to 2, 3, 5, and numbers which aren't multiples of them.
if (limit > 1) then set item 2 of o's numberList to 2
if (limit > 2) then set item 3 of o's numberList to 3
if (limit > 4) then set item 5 of o's numberList to 5
if (limit < 36) then
set n to -23
else
repeat with n from 7 to (limit - 29) by 30
set item n of o's numberList to n
tell (n + 4) to set item it of o's numberList to it
tell (n + 6) to set item it of o's numberList to it
tell (n + 10) to set item it of o's numberList to it
tell (n + 12) to set item it of o's numberList to it
tell (n + 16) to set item it of o's numberList to it
tell (n + 22) to set item it of o's numberList to it
tell (n + 24) to set item it of o's numberList to it
end repeat
end if
repeat with n from (n + 30) to limit
if ((n mod 2 > 0) and (n mod 3 > 0) and (n mod 5 > 0)) then set item n of o's numberList to n
end repeat
-- "Cross out" inserted numbers which are multiples of others.
set inx to {0, 4, 6, 10, 12, 16, 22, 24}
repeat with n from 7 to ((limit ^ 0.5) div 1) by 30
repeat with inc in inx
tell (n + inc)
if (item it of o's numberList is it) then
repeat with multiple from (it * it) to limit by it
set item multiple of o's numberList to mv
end repeat
end if
end tell
end repeat
end repeat
if (keepingZaps) then return o's numberList
return o's numberList's numbers
end sieveForPrimes
-- Task code:
on doTask()
set {safeQuantity, unsafeQuantity, max1, max2} to {35, 40, 1000000 - 1, 10000000 - 1}
set {safePrimes, unsafePrimes, safeCount1, safeCount2, unsafeCount1, unsafeCount2} to {{}, {}, 0, 0, 0, 0}
-- Get a list of 9,999,999 primes and "crossed out" non-primes! Also one with just the primes.
script o
property primesAndZaps : sieveForPrimes with crossingsOut given limit:max2
property primesOnly : my primesAndZaps's numbers
end script
-- Work through the primes-only list, using the other as an indexable look-up to check the related numbers.
set SophieGermainLimit to (max2 - 1) div 2
repeat with n in o's primesOnly
set n to n's contents
if (n ≤ SophieGermainLimit) then
tell (n * 2 + 1)
if (item it of o's primesAndZaps is it) then
if (safeCount2 < safeQuantity) then set end of safePrimes to it
if (it < max1) then set safeCount1 to safeCount1 + 1
set safeCount2 to safeCount2 + 1
end if
end tell
end if
if ((n is 2) or (item ((n - 1) div 2) of o's primesAndZaps is missing value)) then
if (unsafeCount2 < unsafeQuantity) then set end of unsafePrimes to n
if (n < max1) then set unsafeCount1 to unsafeCount1 + 1
set unsafeCount2 to unsafeCount2 + 1
end if
end repeat
-- Format and output the results.
set output to {}
set astid to AppleScript's text item delimiters
set AppleScript's text item delimiters to ", "
set end of output to "First 35 safe primes:"
set end of output to safePrimes as text
set end of output to "There are " & safeCount1 & " safe primes < 1,000,000 and " & safeCount2 & " < 10,000,000."
set end of output to ""
set end of output to "First 40 unsafe primes:"
set end of output to unsafePrimes as text
set end of output to "There are " & unsafeCount1 & " unsafe primes < 1,000,000 and " & unsafeCount2 & " < 10,000,000."
set AppleScript's text item delimiters to linefeed
set output to output as text
set AppleScript's text item delimiters to astid
return output
end doTask
return doTask()
|
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).
|
#Go
|
Go
|
package main
import "fmt"
type node struct {
int
left, right *node
}
// function returns a channel that yields the leaves of the tree.
// the channel is closed after all leaves are received.
func leaves(t *node) chan int {
ch := make(chan int)
// recursive function to walk tree.
var f func(*node)
f = func(n *node) {
if n == nil {
return
}
// leaves are identified by having no children.
if n.left == nil && n.right == nil {
ch <- n.int
} else {
f(n.left)
f(n.right)
}
}
// goroutine runs concurrently with others.
// it walks the tree then closes the channel.
go func() {
f(t)
close(ch)
}()
return ch
}
func sameFringe(t1, t2 *node) bool {
f1 := leaves(t1)
f2 := leaves(t2)
for l1 := range f1 {
// both trees must yield a leaf, and the leaves must be equal.
if l2, ok := <-f2; !ok || l1 != l2 {
return false
}
}
// there must be nothing left in f2 after consuming all of f1.
_, ok := <-f2
return !ok
}
func main() {
// the different shapes of the trees is shown with indention.
// the leaves are easy to spot by the int: key.
t1 := &node{3,
&node{1,
&node{int: 1},
&node{int: 2}},
&node{8,
&node{int: 5},
&node{int: 13}}}
// 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.
t2 := &node{-8,
&node{-3,
&node{-1,
&node{int: 1},
&node{int: 2}},
&node{int: 5}},
&node{int: 13}}
fmt.Println(sameFringe(t1, t2)) // prints true.
}
|
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
|
#MATLAB_.2F_Octave
|
MATLAB / Octave
|
function P = erato(x) % Sieve of Eratosthenes: returns all primes between 2 and x
P = [0 2:x]; % Create vector with all ints between 2 and x where
% position 1 is hard-coded as 0 since 1 is not a prime.
for n = 2:sqrt(x) % All primes factors lie between 2 and sqrt(x).
if P(n) % If the current value is not 0 (i.e. a prime),
P(n*n:n:x) = 0; % then replace all further multiples of it with 0.
end
end % At this point P is a vector with only primes and zeroes.
P = P(P ~= 0); % Remove all zeroes from P, leaving only the primes.
end
|
http://rosettacode.org/wiki/Scope_modifiers
|
Scope modifiers
|
Most programming languages offer support for subroutines.
When execution changes between subroutines, different sets of variables and functions ("scopes") are available to the program.
Frequently these sets are defined by the placement of the variable and function declarations ("static scoping" or "lexical scoping").
These sets may also be defined by special modifiers to the variable and function declarations.
Show the different scope modifiers available in your language and briefly explain how they change the scope of their variable or function.
If your language has no scope modifiers, note it.
|
#REXX
|
REXX
|
/*REXX program to display scope modifiers (for subroutines/functions). */
a=1/4
b=20
c=3
d=5
call SSN_571 d**4
/* at this point, A is defined and equal to .25 */
/* at this point, B is defined and equal to 40 */
/* at this point, C is defined and equal to 27 */
/* at this point, D is defined and equal to 5 */
/* at this point, FF isn't defined. */
/* at this point, EWE is defined and equal to 'female sheep' */
/* at this point, G is defined and equal to 625 */
exit /*stick a fork in it, we're done.*/
/*─────────────────────────────────────SSN_571 submarine, er, subroutine*/
SSN_571: procedure expose b c ewe g; parse arg g
b = b*2
c = c**3
ff = b+c
ewe = 'female sheep'
d = 55555555
return /*compliments to Jules Verne's Captain Nemo? */
|
http://rosettacode.org/wiki/Scope_modifiers
|
Scope modifiers
|
Most programming languages offer support for subroutines.
When execution changes between subroutines, different sets of variables and functions ("scopes") are available to the program.
Frequently these sets are defined by the placement of the variable and function declarations ("static scoping" or "lexical scoping").
These sets may also be defined by special modifiers to the variable and function declarations.
Show the different scope modifiers available in your language and briefly explain how they change the scope of their variable or function.
If your language has no scope modifiers, note it.
|
#Ruby
|
Ruby
|
class Demo
#public methods here
protected
#protect methods here
private
#private methods
end
|
http://rosettacode.org/wiki/Scope_modifiers
|
Scope modifiers
|
Most programming languages offer support for subroutines.
When execution changes between subroutines, different sets of variables and functions ("scopes") are available to the program.
Frequently these sets are defined by the placement of the variable and function declarations ("static scoping" or "lexical scoping").
These sets may also be defined by special modifiers to the variable and function declarations.
Show the different scope modifiers available in your language and briefly explain how they change the scope of their variable or function.
If your language has no scope modifiers, note it.
|
#Scala
|
Scala
|
set globalVar "This is a global variable"
namespace eval nsA {
variable varInA "This is a variable in nsA"
}
namespace eval nsB {
variable varInB "This is a variable in nsB"
proc showOff {varname} {
set localVar "This is a local variable"
global globalVar
variable varInB
namespace upvar ::nsA varInA varInA
puts "variable $varname holds \"[set $varname]\""
}
}
nsB::showOff globalVar
nsB::showOff varInA
nsB::showOff varInB
nsB::showOff localVar
|
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).
|
#JavaScript
|
JavaScript
|
(function () {
// wakeSplit :: Int -> Int -> Int -> Int
function wakeSplit(intNuts, intSailors, intDepth) {
var nDepth = intDepth !== undefined ? intDepth : intSailors,
portion = Math.floor(intNuts / intSailors),
remain = intNuts % intSailors;
return 0 >= portion || remain !== (nDepth ? 1 : 0) ?
null : nDepth ? wakeSplit(
intNuts - portion - remain, intSailors, nDepth - 1
) : intNuts;
}
// TEST for 5, 6, and 7 intSailors
return [5, 6, 7].map(function (intSailors) {
var intNuts = intSailors;
while (!wakeSplit(intNuts, intSailors)) intNuts += 1;
return intNuts;
});
})();
|
http://rosettacode.org/wiki/Scope/Function_names_and_labels
|
Scope/Function names and labels
|
Task
Explain or demonstrate the levels of visibility of function names and labels within the language.
See also
Variables for levels of scope relating to visibility of program variables
Scope modifiers for general scope modification facilities
|
#zkl
|
zkl
|
class C{ fcn [private] f{} }
|
http://rosettacode.org/wiki/Scope/Function_names_and_labels
|
Scope/Function names and labels
|
Task
Explain or demonstrate the levels of visibility of function names and labels within the language.
See also
Variables for levels of scope relating to visibility of program variables
Scope modifiers for general scope modification facilities
|
#ZX_Spectrum_Basic
|
ZX Spectrum Basic
|
9000 REM The function is immediately visible and usable
9010 DEF FN s(x)=x*x
PRINT FN s(5): REM This will work immediately
GO TO 50: REM This will work immediately
|
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
|
#Common_Lisp
|
Common Lisp
|
(defstruct city
(name nil :type string)
(population nil :type number))
(defparameter *cities*
(list (make-city :name "Lagos" :population 21.0)
(make-city :name "Cairo" :population 15.2)
(make-city :name "Kinshasa-Brazzaville" :population 11.3)
(make-city :name "Greater Johannesburg" :population 7.55)
(make-city :name "Mogadishu" :population 5.85)
(make-city :name "Khartoum-Omdurman" :population 4.98)
(make-city :name "Dar Es Salaam" :population 4.7)
(make-city :name "Alexandria" :population 4.58)
(make-city :name "Abidjan" :population 4.4)
(make-city :name "Casablanca" :population 3.98)))
(defun main ()
(let ((answer1 (position "Dar Es Salaam" *cities* :key #'city-name :test #'string=))
(answer2 (city-name (find-if (lambda (population) (< population 5))
*cities* :key #'city-population)))
(answer3 (city-population (find-if (lambda (name) (char= (char name 0) #\A))
*cities* :key #'city-name))))
(format t "Answer 1: ~A~%" answer1)
(format t "Answer 2: ~A~%" answer2)
(format t "Answer 3: ~A~%" answer3)))
|
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].
|
#C.2B.2B
|
C++
|
#include <iostream>
#include <tuple>
union conv {
int i;
float f;
};
float nextUp(float d) {
if (isnan(d) || d == -INFINITY || d == INFINITY) return d;
if (d == 0.0) return FLT_EPSILON;
conv c;
c.f = d;
c.i++;
return c.f;
}
float nextDown(float d) {
if (isnan(d) || d == -INFINITY || d == INFINITY) return d;
if (d == 0.0) return -FLT_EPSILON;
conv c;
c.f = d;
c.i--;
return c.f;
}
auto safeAdd(float a, float b) {
return std::make_tuple(nextDown(a + b), nextUp(a + b));
}
int main() {
float a = 1.20f;
float b = 0.03f;
auto result = safeAdd(a, b);
printf("(%f + %f) is in the range (%0.16f, %0.16f)\n", a, b, std::get<0>(result), std::get<1>(result));
return 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].
|
#D
|
D
|
import std.traits;
auto safeAdd(T)(T a, T b)
if (isFloatingPoint!T) {
import std.math; // nexDown, nextUp
import std.typecons; // tuple
return tuple!("d", "u")(nextDown(a+b), nextUp(a+b));
}
import std.stdio;
void main() {
auto a = 1.2;
auto b = 0.03;
auto r = safeAdd(a, b);
writefln("(%s + %s) is in the range %0.16f .. %0.16f", a, b, r.d, r.u);
}
|
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.
|
#AWK
|
AWK
|
# syntax: GAWK -f SAFE_PRIMES_AND_UNSAFE_PRIMES.AWK
BEGIN {
for (i=1; i<1E7; i++) {
if (is_prime(i)) {
arr[i] = ""
}
}
# safe:
stop1 = 35 ; stop2 = 1E6 ; stop3 = 1E7
count1 = count2 = count3 = 0
printf("The first %d safe primes:",stop1)
for (i=3; count1<stop1; i+=2) {
if (i in arr && ((i-1)/2 in arr)) {
count1++
printf(" %d",i)
}
}
printf("\n")
for (i=3; i<stop3; i+=2) {
if (i in arr && ((i-1)/2 in arr)) {
count3++
if (i < stop2) {
count2++
}
}
}
printf("Number below %d: %d\n",stop2,count2)
printf("Number below %d: %d\n",stop3,count3)
# unsafe:
stop1 = 40 ; stop2 = 1E6 ; stop3 = 1E7
count1 = count2 = count3 = 1 # since (2-1)/2 is not prime
printf("The first %d unsafe primes: 2",stop1)
for (i=3; count1<stop1; i+=2) {
if (i in arr && !((i-1)/2 in arr)) {
count1++
printf(" %d",i)
}
}
printf("\n")
for (i=3; i<stop3; i+=2) {
if (i in arr && !((i-1)/2 in arr)) {
count3++
if (i < stop2) {
count2++
}
}
}
printf("Number below %d: %d\n",stop2,count2)
printf("Number below %d: %d\n",stop3,count3)
exit(0)
}
function is_prime(n, d) {
d = 5
if (n < 2) { return(0) }
if (n % 2 == 0) { return(n == 2) }
if (n % 3 == 0) { return(n == 3) }
while (d*d <= n) {
if (n % d == 0) { return(0) }
d += 2
if (n % d == 0) { return(0) }
d += 4
}
return(1)
}
|
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).
|
#Haskell
|
Haskell
|
data Tree a
= Leaf a
| Node (Tree a)
(Tree a)
deriving (Show, Eq)
fringe :: Tree a -> [a]
fringe (Leaf x) = [x]
fringe (Node n1 n2) = fringe n1 ++ fringe n2
sameFringe
:: (Eq a)
=> Tree a -> Tree a -> Bool
sameFringe t1 t2 = fringe t1 == fringe t2
main :: IO ()
main = do
let a = Node (Leaf 1) (Node (Leaf 2) (Node (Leaf 3) (Node (Leaf 4) (Leaf 5))))
b = Node (Leaf 1) (Node (Node (Leaf 2) (Leaf 3)) (Node (Leaf 4) (Leaf 5)))
c = Node (Node (Node (Node (Leaf 1) (Leaf 2)) (Leaf 3)) (Leaf 4)) (Leaf 5)
x =
Node
(Leaf 1)
(Node
(Leaf 2)
(Node (Leaf 3) (Node (Leaf 4) (Node (Leaf 5) (Leaf 6)))))
y = Node (Leaf 0) (Node (Node (Leaf 2) (Leaf 3)) (Node (Leaf 4) (Leaf 5)))
z = Node (Leaf 1) (Node (Leaf 2) (Node (Node (Leaf 4) (Leaf 3)) (Leaf 5)))
mapM_ print $ sameFringe a <$> [a, b, c, x, y, 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
|
#Maxima
|
Maxima
|
sieve(n):=block(
[a:makelist(true,n),i:1,j],
a[1]:false,
do (
i:i+1,
unless a[i] do i:i+1,
if i*i>n then return(sublist_indices(a,identity)),
for j from i*i step i while j<=n do a[j]:false
)
)$
|
http://rosettacode.org/wiki/Scope_modifiers
|
Scope modifiers
|
Most programming languages offer support for subroutines.
When execution changes between subroutines, different sets of variables and functions ("scopes") are available to the program.
Frequently these sets are defined by the placement of the variable and function declarations ("static scoping" or "lexical scoping").
These sets may also be defined by special modifiers to the variable and function declarations.
Show the different scope modifiers available in your language and briefly explain how they change the scope of their variable or function.
If your language has no scope modifiers, note it.
|
#Tcl
|
Tcl
|
set globalVar "This is a global variable"
namespace eval nsA {
variable varInA "This is a variable in nsA"
}
namespace eval nsB {
variable varInB "This is a variable in nsB"
proc showOff {varname} {
set localVar "This is a local variable"
global globalVar
variable varInB
namespace upvar ::nsA varInA varInA
puts "variable $varname holds \"[set $varname]\""
}
}
nsB::showOff globalVar
nsB::showOff varInA
nsB::showOff varInB
nsB::showOff localVar
|
http://rosettacode.org/wiki/Scope_modifiers
|
Scope modifiers
|
Most programming languages offer support for subroutines.
When execution changes between subroutines, different sets of variables and functions ("scopes") are available to the program.
Frequently these sets are defined by the placement of the variable and function declarations ("static scoping" or "lexical scoping").
These sets may also be defined by special modifiers to the variable and function declarations.
Show the different scope modifiers available in your language and briefly explain how they change the scope of their variable or function.
If your language has no scope modifiers, note it.
|
#TI-89_BASIC
|
TI-89 BASIC
|
Local x
2 → x
Return x^x
|
http://rosettacode.org/wiki/Scope_modifiers
|
Scope modifiers
|
Most programming languages offer support for subroutines.
When execution changes between subroutines, different sets of variables and functions ("scopes") are available to the program.
Frequently these sets are defined by the placement of the variable and function declarations ("static scoping" or "lexical scoping").
These sets may also be defined by special modifiers to the variable and function declarations.
Show the different scope modifiers available in your language and briefly explain how they change the scope of their variable or function.
If your language has no scope modifiers, note it.
|
#TXR
|
TXR
|
@(maybe)@# perhaps this subclause suceeds or not
@ (block foo)
@ (bind a "a")
@ (accept foo)
@(end)
@(bind b "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).
|
#jq
|
jq
|
def until(cond; next): def _until: if cond then . else (next|_until) end; _until;
|
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).
|
#Julia
|
Julia
|
function validnutsforsailors(sailors, finalpile)
for i in sailors:-1:1
if finalpile % sailors != 1
return false
end
finalpile -= Int(floor(finalpile/sailors) + 1)
end
(finalpile != 0) && (finalpile % sailors == 0)
end
function runsim()
println("Sailors Starting Pile")
for sailors in 2:9
finalcount = 0
while validnutsforsailors(sailors, finalcount) == false
finalcount += 1
end
println("$sailors $finalcount")
end
end
runsim()
|
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
|
#EchoLisp
|
EchoLisp
|
(require 'struct)
(require 'json)
;; importing data
(define cities
#<<
[{"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}]
>>#)
;; define a structure matching data
;; heterogenous slots values
(struct city (name population))
;; convert JSON to EchoLisp instances of structures
(set! cities
(vector-map (lambda(x) (json->struct x struct:city)) (json-import cities)))
;; search by name, case indifferent
(define (city-index name)
(vector-search (lambda(x) (string-ci=? (city-name x) name)) cities))
;; returns first city name such as population < seuil
(define (city-pop seuil)
(define idx (vector-search (lambda(x) (< (city-population x) seuil)) cities))
(if idx
(city-name (vector-ref cities idx))
(cons seuil 'not-found)))
(city-index "Dar Es Salaam") → 6
(city-pop 5) → "Khartoum-Omdurman"
(city-pop -666) → (-666 . not-found)
(city-index "alexandra") → #f
|
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].
|
#E
|
E
|
def makeInterval(a :float64, b :float64) {
require(a <= b)
def interval {
to least() { return a }
to greatest() { return b }
to __printOn(out) {
out.print("[", a, ", ", b, "]")
}
to add(other) {
require(a <=> b)
require(other.least() <=> other.greatest())
def result := a + other.least()
return makeInterval(result.previous(), result.next())
}
}
return interval
}
|
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].
|
#Forth
|
Forth
|
c-library m
s" m" add-lib
\c #include <math.h>
c-function fnextafter nextafter r r -- r
end-c-library
s" MAX-FLOAT" environment? drop fconstant MAX-FLOAT
: fstepdown ( F: r1 -- r2 )
MAX-FLOAT fnegate fnextafter ;
: fstepup ( F: r1 -- r2 )
MAX-FLOAT fnextafter ;
: savef+ ( F: r1 r2 -- r3 r4 ) \ r4 <= r1+r2 <= r3
f+ fdup fstepup fswap fstepdown ;
|
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].
|
#Go
|
Go
|
package main
import (
"fmt"
"math"
)
// type requested by task
type interval struct {
lower, upper float64
}
// a constructor
func stepAway(x float64) interval {
return interval {
math.Nextafter(x, math.Inf(-1)),
math.Nextafter(x, math.Inf(1))}
}
// function requested by task
func safeAdd(a, b float64) interval {
return stepAway(a + b)
}
// example
func main() {
a, b := 1.2, .03
fmt.Println(a, b, safeAdd(a, b))
}
|
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
|
#11l
|
11l
|
V haystack = [‘Zig’, ‘Zag’, ‘Wally’, ‘Ronald’, ‘Bush’, ‘Krusty’, ‘Charlie’, ‘Bush’, ‘Bozo’]
L(needle) (‘Washington’, ‘Bush’)
X.try
print(haystack.index(needle)‘ ’needle)
X.catch ValueError
print(needle‘ is not in haystack’)
|
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.
|
#BASIC256
|
BASIC256
|
arraybase 1
max = 1000000
sc1 = 0: usc1 = 0: sc2 = 0: usc2 = 0
safeprimes$ =""
unsafeprimes$ = ""
redim criba(max)
# False = prime, True = no prime
criba[0] = True
criba[1] = True
for i = 4 to max step 2
criba[i] = 1
next i
for i = 3 to sqr(max) +1 step 2
if criba[i] = False then
for j = i * i to max step i * 2
criba[j] = True
next j
end if
next
usc1 = 1
unsafeprimes$ = "2"
for i = 3 to 3001 step 2
if criba[i] = False then
if criba[i \ 2] = False then
sc1 += 1
if sc1 <= 35 then safeprimes$ += " " + string(i)
else
usc1 += 1
if usc1 <= 40 then unsafeprimes$ += " " + string(i)
end if
end if
next i
for i = 3003 to max \ 10 step 2
if criba[i] = False then
if criba[i \ 2] = False then
sc1 += 1
else
usc1 += 1
end if
end if
next i
sc2 = sc1
usc2 = usc1
for i = max \ 10 + 1 to max step 2
if criba[i] = False then
if criba[i \ 2] = False then
sc2 += 1
else
usc2 += 1
end if
end if
next i
print "the first 35 Safeprimes are: "; safeprimes$
print
print "the first 40 Unsafeprimes are: "; unsafeprimes$
print
print " Safeprimes Unsafeprimes"
print " Below -------------------------"
print max \ 10, sc1, usc1
print max , sc2, usc2
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.
|
#C
|
C
|
#include <stdbool.h>
#include <stdio.h>
int primes[] = {
2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97,
101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199,
211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311, 313, 317, 331
};
#define PCOUNT (sizeof(primes) / sizeof(int))
bool isPrime(int n) {
int i;
if (n < 2) {
return false;
}
for (i = 0; i < PCOUNT; i++) {
if (n == primes[i]) {
return true;
}
if (n % primes[i] == 0) {
return false;
}
if (n < primes[i] * primes[i]) {
return true;
}
}
for (i = primes[PCOUNT - 1] + 2; i * i <= n; i += 2) {
if (n % i == 0) {
return false;
}
}
return true;
}
int main() {
int beg, end;
int i, count;
// safe primes
///////////////////////////////////////////
beg = 2;
end = 1000000;
count = 0;
printf("First 35 safe primes:\n");
for (i = beg; i < end; i++) {
if (isPrime(i) && isPrime((i - 1) / 2)) {
if (count < 35) {
printf("%d ", i);
}
count++;
}
}
printf("\nThere are %d safe primes below %d\n", count, end);
beg = end;
end = end * 10;
for (i = beg; i < end; i++) {
if (isPrime(i) && isPrime((i - 1) / 2)) {
count++;
}
}
printf("There are %d safe primes below %d\n", count, end);
// unsafe primes
///////////////////////////////////////////
beg = 2;
end = 1000000;
count = 0;
printf("\nFirst 40 unsafe primes:\n");
for (i = beg; i < end; i++) {
if (isPrime(i) && !isPrime((i - 1) / 2)) {
if (count < 40) {
printf("%d ", i);
}
count++;
}
}
printf("\nThere are %d unsafe primes below %d\n", count, end);
beg = end;
end = end * 10;
for (i = beg; i < end; i++) {
if (isPrime(i) && !isPrime((i - 1) / 2)) {
count++;
}
}
printf("There are %d unsafe primes below %d\n", count, end);
return 0;
}
|
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).
|
#Icon_and_Unicon
|
Icon and Unicon
|
procedure main()
aTree := [1, [2, [4, [7]], [5]], [3, [6, [8], [9]]]]
bTree := [1, [2, [4, [7]], [5]], [3, [6, [8], [9]]]]
write("aTree and bTree ",(sameFringe(aTree,bTree),"have")|"don't have",
" the same leaves.")
cTree := [1, [2, [4, [7]], [5]], [3, [6, [8]]]]
dTree := [1, [2, [4, [7]], [5]], [3, [6, [8], [9]]]]
write("cTree and dTree ",(sameFringe(cTree,dTree),"have")|"don't have",
" the same leaves.")
end
procedure sameFringe(a,b)
return same{genLeaves(a),genLeaves(b)}
end
procedure same(L)
while n1 := @L[1] do {
n2 := @L[2] | fail
if n1 ~== n2 then fail
}
return not @L[2]
end
procedure genLeaves(t)
suspend (*(node := preorder(t)) == 1, node[1])
end
procedure preorder(L)
if \L then suspend L | preorder(L[2|3])
end
|
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
|
#MAXScript
|
MAXScript
|
fn eratosthenes n =
(
multiples = #()
print 2
for i in 3 to n do
(
if (findItem multiples i) == 0 then
(
print i
for j in (i * i) to n by i do
(
append multiples j
)
)
)
)
eratosthenes 100
|
http://rosettacode.org/wiki/Scope_modifiers
|
Scope modifiers
|
Most programming languages offer support for subroutines.
When execution changes between subroutines, different sets of variables and functions ("scopes") are available to the program.
Frequently these sets are defined by the placement of the variable and function declarations ("static scoping" or "lexical scoping").
These sets may also be defined by special modifiers to the variable and function declarations.
Show the different scope modifiers available in your language and briefly explain how they change the scope of their variable or function.
If your language has no scope modifiers, note it.
|
#Ursala
|
Ursala
|
local_shop = 0
hidden_variable = 3
#library+
this_public_constant = local_shop
a_visible_function = +
#library-
for_local_people = 7
|
http://rosettacode.org/wiki/Scope_modifiers
|
Scope modifiers
|
Most programming languages offer support for subroutines.
When execution changes between subroutines, different sets of variables and functions ("scopes") are available to the program.
Frequently these sets are defined by the placement of the variable and function declarations ("static scoping" or "lexical scoping").
These sets may also be defined by special modifiers to the variable and function declarations.
Show the different scope modifiers available in your language and briefly explain how they change the scope of their variable or function.
If your language has no scope modifiers, note it.
|
#Wren
|
Wren
|
class MyClass {
construct new(a) {
_a = a // creates an instance field _a automatically
}
a { _a } // allow public access to the field
}
var mc = MyClass.new(3)
System.print(mc.a) // fine
System.print(mc._a) // can't access _a directly as its private to the class
|
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).
|
#Kotlin
|
Kotlin
|
// version 1.1.2
fun main(args: Array<String>) {
var coconuts = 11
outer@ for (ns in 2..9) {
val hidden = IntArray(ns)
coconuts = (coconuts / ns) * ns + 1
while (true) {
var nc = coconuts
for (s in 1..ns) {
if (nc % ns == 1) {
hidden[s - 1] = nc / ns
nc -= hidden[s - 1] + 1
if (s == ns && nc % ns == 0) {
println("$ns sailors require a minimum of $coconuts coconuts")
for (t in 1..ns) println("\tSailor $t hides ${hidden[t - 1]}")
println("\tThe monkey gets $ns")
println("\tFinally, each sailor takes ${nc / ns}\n")
continue@outer
}
}
else break
}
coconuts += ns
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.