task_url stringlengths 30 116 | task_name stringlengths 2 86 | task_description stringlengths 0 14.4k | language_url stringlengths 2 53 | language_name stringlengths 1 52 | code stringlengths 0 61.9k |
|---|---|---|---|---|---|
http://rosettacode.org/wiki/Search_a_list_of_records | Search a list of records | Many programming languages provide convenient ways to look for a known value in a simple list of strings or numbers.
But what if the elements of the list are themselves compound records/objects/data-structures, and the search condition is more complex than a simple equality test?
Task[edit]
Write a function/method/et... | #Elena | Elena | import extensions;
import system'routines;
public program()
{
var dataset := new object[]
{
new { Name = "Lagos"; Population = 21.0r; },
new { Name = "Cairo"; Population = 15.2r; },
new { Name = "Kinshasa-Brazzaville"; Population = 11.3r; },
new { Name = "Greater Johannesbur... |
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 widt... | #Hare | Hare | use fmt;
use math;
type interval = struct {a: f64, b: f64};
export fn main() void = {
const a: [_](f64, f64) = [
(1.0f64, 2.0f64),
(0.1f64, 0.2f64),
(1e100f64, 1e-100f64),
(1e308f64, 1e308f64)];
for (let i = 0z; i < len(a); i += 1) {
let res = safe_add(a[i].0, a[i].1);
fmt::printfln("{} + {} is with... |
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 widt... | #J | J | err =. 2^ 53-~ 2 <.@^. | NB. get the size of one-half unit in the last place
safeadd =. + (-,+) +&err
0j15": 1.14 safeadd 2000.0 NB. print with 15 digits after the decimal
2001.139999999999873 2001.140000000000327 |
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 widt... | #Java | Java | public class SafeAddition {
private static double stepDown(double d) {
return Math.nextAfter(d, Double.NEGATIVE_INFINITY);
}
private static double stepUp(double d) {
return Math.nextUp(d);
}
private static double[] safeAdd(double a, double b) {
return new double[]{stepDow... |
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 ... | #ACL2 | ACL2 | (defun index-of-r (e xs i)
(cond ((endp xs) nil)
((equal e (first xs)) i)
(t (index-of-r e (rest xs) (1+ i)))))
(defun index-of (e xs)
(index-of-r e xs 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
... | #C.23 | C# | using static System.Console;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
public static class SafePrimes
{
public static void Main() {
HashSet<int> primes = Primes(10_000_000).ToHashSet();
WriteLine("First 35 safe primes:");
WriteLine(string.... |
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 compu... | #J | J | sameFringe=: -:&([: ; <S: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 compu... | #Java | Java | import java.util.*;
class SameFringe
{
public interface Node<T extends Comparable<? super T>>
{
Node<T> getLeft();
Node<T> getRight();
boolean isLeaf();
T getData();
}
public static class SimpleNode<T extends Comparable<? super T>> implements Node<T>
{
private final T data;
public ... |
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... | #Mercury | Mercury | :- module sieve.
:- interface.
:- import_module io.
:- pred main(io::di, io::uo) is det.
:- implementation.
:- import_module bool, array, int.
main(!IO) :-
sieve(50, Sieve),
dump_primes(2, size(Sieve), Sieve, !IO).
:- pred dump_primes(int, int, array(bool), io, io).
:- mode dump_primes(in, in, array_di, di,... |
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 th... | #Lua | Lua | function valid(n,nuts)
local k = n
local i = 0
while k ~= 0 do
if (nuts % n) ~= 1 then
return false
end
k = k - 1
nuts = nuts - 1 - math.floor(nuts / n)
end
return nuts ~= 0 and (nuts % n == 0)
end
for n=2, 9 do
local x = 0
while not valid(n, x) ... |
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/et... | #Elixir | Elixir | cities = [
[name: "Lagos", population: 21.0 ],
[name: "Cairo", population: 15.2 ],
[name: "Kinshasa-Brazzaville", population: 11.3 ],
[name: "Greater Johannesburg", population: 7.55],
[name: "Mogadishu", population: 5.85],
[name: "Khartoum-Omdurman", popul... |
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 widt... | #Julia | Julia |
julia> using IntervalArithmetic
julia> n = 2.0
2.0
julia> @interval 2n/3 + 1
[2.33333, 2.33334]
julia> showall(ans)
Interval(2.333333333333333, 2.3333333333333335)
julia> a = @interval(0.1, 0.3)
[0.0999999, 0.300001]
julia> b = @interval(0.3, 0.6)
[0.299999, 0.600001]
julia> a + b
[0.399999, 0.900001]
|
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 widt... | #Kotlin | Kotlin | // version 1.1.2
fun stepDown(d: Double) = Math.nextAfter(d, Double.NEGATIVE_INFINITY)
fun stepUp(d: Double) = Math.nextUp(d)
fun safeAdd(a: Double, b: Double) = stepDown(a + b).rangeTo(stepUp(a + b))
fun main(args: Array<String>) {
val a = 1.2
val b = 0.03
println("($a + $b) is in the range ${safe... |
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 widt... | #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | import fenv, strutils
proc `++`(a, b: float): tuple[lower, upper: float] =
let
a {.volatile.} = a
b {.volatile.} = b
orig = fegetround()
discard fesetround FE_DOWNWARD
result.lower = a + b
discard fesetround FE_UPWARD
result.upper = a + b
discard fesetround orig
proc ff(a: float): string = a... |
http://rosettacode.org/wiki/Ruth-Aaron_numbers | Ruth-Aaron numbers | A Ruth–Aaron pair consists of two consecutive integers (e.g., 714 and 715) for which the sums of the prime divisors of each integer are equal. So called because 714 is Babe Ruth's lifetime home run record; Hank Aaron's 715th home run broke this record and 714 and 715 have the same prime divisor sum.
A Ruth–Aaron tri... | #ALGOL_68 | ALGOL 68 | BEGIN # find Ruth-Aaron pairs - pairs of consecutive integers where the sum #
# of the prime factors or divisors are equal #
INT max number = 99 000 000; # max number we will consider #
# construct a sieve of primes up to max number #
[ 1 : max number ]BOOL prime;
prime[ 1... |
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 ... | #Action.21 | Action! | DEFINE PTR="CARD"
INT FUNC Search(PTR ARRAY texts INT count CHAR ARRAY text)
INT i
FOR i=0 TO count-1
DO
IF SCompare(texts(i),text)=0 THEN
RETURN (i)
FI
OD
RETURN (-1)
PROC Test(PTR ARRAY texts INT count CHAR ARRAY text)
INT index
index=Search(texts,count,text)
IF index=-1 THEN
P... |
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
... | #C.2B.2B | C++ | #include <algorithm>
#include <iostream>
#include <iterator>
#include <locale>
#include <vector>
#include "prime_sieve.hpp"
const int limit1 = 1000000;
const int limit2 = 10000000;
class prime_info {
public:
explicit prime_info(int max) : max_print(max) {}
void add_prime(int prime);
void print(std::ostr... |
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 compu... | #jq | jq | (t|flatten) == (s|flatten) |
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 compu... | #Julia | Julia |
using Lazy
"""
Input a tree for display as a fringed structure.
"""
function fringe(tree)
fringey(node::Pair) = [fringey(i) for i in node]
fringey(leaf::Int) = leaf
fringey(tree)
end
"""
equalsfringe() uses a reduction to a lazy 1D list via
getleaflist() for its "equality" of fringes
""... |
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... | #Microsoft_Small_Basic | Microsoft Small Basic |
TextWindow.Write("Enter number to search to: ")
limit = TextWindow.ReadNumber()
For n = 2 To limit
flags[n] = 0
EndFor
For n = 2 To math.SquareRoot(limit)
If flags[n] = 0 Then
For K = n * n To limit Step n
flags[K] = 1
EndFor
EndIf
EndFor
' Display the primes
If limit >= 2 Then
TextWindow.Write... |
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 th... | #Mathematica_.2F_Wolfram_Language | Mathematica / Wolfram Language | ClearAll[SequenceOk]
SequenceOk[n_, k_] := Module[{m = n, q, r, valid = True},
Do[
{q, r} = QuotientRemainder[m, k];
If[r != 1,
valid = False;
Break[];
];
m -= q + 1
,
{k}
];
If[Mod[m, k] != 0,
valid = False
];
valid
]
i = 1;
While[! SequenceOk[i, 5], i++]
i
i = 1;
While[! ... |
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 th... | #Modula-2 | Modula-2 | MODULE Coconuts;
FROM FormatString IMPORT FormatString;
FROM Terminal IMPORT WriteString,WriteLn,ReadChar;
CONST MAX_SAILORS = 9;
PROCEDURE Scenario(coconuts,ns : INTEGER);
VAR
buf : ARRAY[0..63] OF CHAR;
hidden : ARRAY[0..MAX_SAILORS-1] OF INTEGER;
nc,s,t : INTEGER;
BEGIN
IF ns>MAX_SAILORS THEN RET... |
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/et... | #Factor | Factor | USING: accessors io kernel math prettyprint sequences ;
IN: rosetta-code.search-list
TUPLE: city name pop ;
CONSTANT: data {
T{ city f "Lagos" 21.0 }
T{ city f "Cairo" 15.2 }
T{ city f "Kinshasa-Brazzaville" 11.3 }
T{ city f "Greater Johannesburg" 7.55 }
T{ city f "Mogadishu" 5.85 }
T{ city ... |
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 widt... | #Nim | Nim | import fenv, strutils
proc `++`(a, b: float): tuple[lower, upper: float] =
let
a {.volatile.} = a
b {.volatile.} = b
orig = fegetround()
discard fesetround FE_DOWNWARD
result.lower = a + b
discard fesetround FE_UPWARD
result.upper = a + b
discard fesetround orig
proc ff(a: float): string = a... |
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 widt... | #Perl | Perl | use strict;
use warnings;
use Data::IEEE754::Tools <nextUp nextDown>;
sub safe_add {
my($a,$b) = @_;
my $c = $a + $b;
return $c, nextDown($c), nextUp($c)
}
printf "%.17f (%.17f, %.17f)\n", safe_add (1/9,1/7); |
http://rosettacode.org/wiki/Ruth-Aaron_numbers | Ruth-Aaron numbers | A Ruth–Aaron pair consists of two consecutive integers (e.g., 714 and 715) for which the sums of the prime divisors of each integer are equal. So called because 714 is Babe Ruth's lifetime home run record; Hank Aaron's 715th home run broke this record and 714 and 715 have the same prime divisor sum.
A Ruth–Aaron tri... | #C.2B.2B | C++ | #include <iomanip>
#include <iostream>
int prime_factor_sum(int n) {
int sum = 0;
for (; (n & 1) == 0; n >>= 1)
sum += 2;
for (int p = 3, sq = 9; sq <= n; p += 2) {
for (; n % p == 0; n /= p)
sum += p;
sq += (p + 1) << 2;
}
if (n > 1)
sum += n;
retur... |
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 ... | #ActionScript | ActionScript | var list:Vector.<String> = Vector.<String>(["Zig", "Zag", "Wally", "Ronald", "Bush", "Krusty", "Charlie", "Bush", "Boz", "Zag"]);
function lowIndex(listToSearch:Vector.<String>, searchString:String):int
{
var index:int = listToSearch.indexOf(searchString);
if(index == -1)
throw new Error("String not found: " + sear... |
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
... | #CLU | CLU | isqrt = proc (s: int) returns (int)
x0: int := s/2
if x0=0 then return(s) end
x1: int := (x0 + s/x0)/2
while x1 < x0 do
x0 := x1
x1 := (x0 + s/x0)/2
end
return(x0)
end isqrt
sieve = proc (n: int) returns (array[bool])
prime: array[bool] := array[bool]$fill(0,n+1,true)
p... |
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
... | #D | D | import std.stdio;
immutable 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, 2... |
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 compu... | #Lua | Lua | local type, insert, remove = type, table.insert, table.remove
None = {} -- a unique object for a truncated branch (i.e. empty subtree)
function isbranch(node) return type(node) == 'table' and #node == 2 end
function left(node) return node[1] end
function right(node) return node[2] end
function fringeiter(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... | #Modula-2 | Modula-2 | MODULE Erato;
FROM InOut IMPORT WriteCard, WriteLn;
FROM MathLib IMPORT sqrt;
CONST Max = 100;
VAR prime: ARRAY [2..Max] OF BOOLEAN;
i: CARDINAL;
PROCEDURE Sieve;
VAR i, j, sqmax: CARDINAL;
BEGIN
sqmax := TRUNC(sqrt(FLOAT(Max)));
FOR i := 2 TO Max DO prime[i] := TRUE; END;
FOR i := 2 TO sqm... |
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 th... | #Nim | Nim | import strformat
var coconuts = 11
for ns in 2..9:
var hidden = newSeq[int](ns)
coconuts = (coconuts div ns) * ns + 1
block Search:
while true:
var nc = coconuts
for sailor in 1..ns:
if nc mod ns == 1:
hidden[sailor-1] = nc div ns
dec nc, hidden[sailor-1] + 1
... |
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 th... | #Objeck | Objeck |
class Program {
function : Total(n : Int, nuts : Int) ~ Int {
k := 0;
for(nuts *= n; k < n; k++;) {
if(nuts % (n-1) <> 0) { return 0; };
nuts += nuts / (n-1) + 1;
};
return nuts;
}
function : Main(args : String[]) ~ Nil {
for(n := 2; n < 10; n++;) {
x := 0; t := 0;
... |
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/et... | #Fortran | Fortran | MODULE SEMPERNOVIS !Keep it together.
TYPE CITYSTAT !Define a compound data type.
CHARACTER*28 NAME !Long enough?
REAL POPULATION !Accurate enough.
END TYPE CITYSTAT !Just two parts, but different types.
TYPE(CITYSTAT) CITY(10) !Righto, I'll have some.
DATA CITY/ !S... |
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 widt... | #Phix | Phix | include builtins\VM\pFPU.e -- :%down53 etc
function safe_add(atom a, atom b)
atom low,high
-- NB: be sure to restore the usual/default rounding!
#ilASM{
[32]
lea esi,[a]
call :%pLoadFlt
lea esi,[b]
call :%pLoadFlt
fld st0
call :%... |
http://rosettacode.org/wiki/Ruth-Aaron_numbers | Ruth-Aaron numbers | A Ruth–Aaron pair consists of two consecutive integers (e.g., 714 and 715) for which the sums of the prime divisors of each integer are equal. So called because 714 is Babe Ruth's lifetime home run record; Hank Aaron's 715th home run broke this record and 714 and 715 have the same prime divisor sum.
A Ruth–Aaron tri... | #Factor | Factor | USING: assocs.extras grouping io kernel lists lists.lazy math
math.primes.factors prettyprint ranges sequences ;
: pair-same? ( ... n quot: ( ... m -- ... n ) -- ... ? )
[ dup 1 + ] dip same? ; inline
: RA-f? ( n -- ? ) [ factors sum ] pair-same? ;
: RA-d? ( n -- ? ) [ group-factors sum-keys ] pair-same? ;
: fi... |
http://rosettacode.org/wiki/Ruth-Aaron_numbers | Ruth-Aaron numbers | A Ruth–Aaron pair consists of two consecutive integers (e.g., 714 and 715) for which the sums of the prime divisors of each integer are equal. So called because 714 is Babe Ruth's lifetime home run record; Hank Aaron's 715th home run broke this record and 714 and 715 have the same prime divisor sum.
A Ruth–Aaron tri... | #Go | Go | package main
import (
"fmt"
"rcu"
)
func prune(a []int) []int {
prev := a[0]
b := []int{prev}
for i := 1; i < len(a); i++ {
if a[i] != prev {
b = append(b, a[i])
prev = a[i]
}
}
return b
}
func main() {
var resF, resD, resT, factors1 []int
... |
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 ... | #Ada | Ada | with Ada.Strings.Unbounded; use Ada.Strings.Unbounded;
with Ada.Text_IO; use Ada.Text_IO;
procedure Test_List_Index is
Not_In : exception;
type List is array (Positive range <>) of Unbounded_String;
function Index (Haystack : List; Needle : String) return Positive is
begin
for Index ... |
http://rosettacode.org/wiki/Runtime_evaluation | Runtime evaluation | Task
Demonstrate a language's ability for programs to execute code written in the language provided at runtime.
Show what kind of program fragments are permitted (e.g. expressions vs. statements), and how to get values in and out (e.g. environments, arguments, return values), if applicable what lexical/static environ... | #6502_Assembly | 6502 Assembly | ;Init Routine
*=$0801
db $0E,$08,$0A,$00,$9E,$20,$28,$32,$30,$36,$34,$29,$00,$00,$00
*=$0810 ;Start at $0810
LDA #$A9 ;opcode for LDA immediate
STA smc_test
LDA #'A'
STA smc_test+1
lda #$20 ;opcode for JSR
STA smc_test+2
lda #<CHROUT
STA smc_test+3
lda #>CHROUT
STA smc_test+4
smc_test:
n... |
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
... | #F.23 | F# |
pCache |> Seq.filter(fun n->isPrime((n-1)/2)) |> Seq.take 35 |> Seq.iter (printf "%d ")
|
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 compu... | #Nim | Nim | import random, sequtils, strutils
type Node = ref object
value: int
left, right: Node
proc add(tree: var Node; value: int) =
## Add a node to a tree (or subtree), insuring values are in increasing order.
if tree.isNil:
tree = Node(value: value)
elif value <= tree.value:
tree.left.add value
els... |
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... | #Modula-3 | Modula-3 | MODULE Eratosthenes EXPORTS Main;
IMPORT IO;
FROM Math IMPORT sqrt;
CONST
LastNum = 1000;
ListPrimes = TRUE;
VAR
a: ARRAY[2..LastNum] OF BOOLEAN;
VAR
n := LastNum - 2 + 1;
BEGIN
(* set up *)
FOR i := FIRST(a) TO LAST(a) DO
a[i] := TRUE;
END;
(* declare a variable local to a block ... |
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 th... | #Perl | Perl | use bigint;
for $sailors (1..15) { check( $sailors, coconuts( 0+$sailors ) ) }
sub is_valid {
my($sailors, $nuts) = @_;
return 0, 0 if $sailors == 1 and $nuts == 1;
my @shares;
for (1..$sailors) {
return () unless ($nuts % $sailors) == 1;
push @shares, int ($nuts-1)/$sailors;
... |
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/et... | #Go | Go | package main
import (
"fmt"
"strings"
)
type element struct {
name string
population float64
}
var list = []element{
{"Lagos", 21},
{"Cairo", 15.2},
{"Kinshasa-Brazzaville", 11.3},
{"Greater Johannesburg", 7.55},
{"Mogadishu", 5.85},
{"Khartoum-Omdurman", 4.98},
{... |
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 widt... | #PicoLisp | PicoLisp | >>> sum([.1, .1, .1, .1, .1, .1, .1, .1, .1, .1])
0.9999999999999999
>>> from math import fsum
>>> fsum([.1, .1, .1, .1, .1, .1, .1, .1, .1, .1])
1.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 widt... | #Python | Python | >>> sum([.1, .1, .1, .1, .1, .1, .1, .1, .1, .1])
0.9999999999999999
>>> from math import fsum
>>> fsum([.1, .1, .1, .1, .1, .1, .1, .1, .1, .1])
1.0 |
http://rosettacode.org/wiki/Ruth-Aaron_numbers | Ruth-Aaron numbers | A Ruth–Aaron pair consists of two consecutive integers (e.g., 714 and 715) for which the sums of the prime divisors of each integer are equal. So called because 714 is Babe Ruth's lifetime home run record; Hank Aaron's 715th home run broke this record and 714 and 715 have the same prime divisor sum.
A Ruth–Aaron tri... | #Haskell | Haskell | import qualified Data.Set as S
import Data.List.Split ( chunksOf )
divisors :: Int -> [Int]
divisors n = [d | d <- [2 .. n] , mod n d == 0]
--for obvious theoretical reasons the smallest divisor of a number bare 1
--must be prime
primeFactors :: Int -> [Int]
primeFactors n = snd $ until ( (== 1) . fst ) step (n , [... |
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 ... | #Aime | Aime | void
search(list l, text s)
{
integer i;
i = 0;
while (i < ~l) {
if (l[i] == s) {
break;
}
i += 1;
}
o_(s, " is ", i == ~l ? "not in the haystack" : "at " + itoa(i), "\n");
}
integer
main(void)
{
list l;
l = l_effect("Zig", "Zag", "Wally", "Ronald"... |
http://rosettacode.org/wiki/Runtime_evaluation | Runtime evaluation | Task
Demonstrate a language's ability for programs to execute code written in the language provided at runtime.
Show what kind of program fragments are permitted (e.g. expressions vs. statements), and how to get values in and out (e.g. environments, arguments, return values), if applicable what lexical/static environ... | #ALGOL_68 | ALGOL 68 | print(evaluate("4.0*arctan(1.0)")) |
http://rosettacode.org/wiki/Runtime_evaluation | Runtime evaluation | Task
Demonstrate a language's ability for programs to execute code written in the language provided at runtime.
Show what kind of program fragments are permitted (e.g. expressions vs. statements), and how to get values in and out (e.g. environments, arguments, return values), if applicable what lexical/static environ... | #Arturo | Arturo | a: {print ["The result is:" 2+3]}
do a
userCode: input "Give me some code: "
do userCode |
http://rosettacode.org/wiki/Runtime_evaluation | Runtime evaluation | Task
Demonstrate a language's ability for programs to execute code written in the language provided at runtime.
Show what kind of program fragments are permitted (e.g. expressions vs. statements), and how to get values in and out (e.g. environments, arguments, return values), if applicable what lexical/static environ... | #AutoHotkey | AutoHotkey | ; requires AutoHotkey_H or AutoHotkey.dll
msgbox % eval("3 + 4")
msgbox % eval("4 + 4")
return
eval(expression)
{
global script
script =
(
expression(){
return %expression%
}
)
renameFunction("expression", "") ; remove any previous expressions
gosub load ; cannot use addScript inside a function yet
exp ... |
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
... | #Factor | Factor | USING: fry interpolate kernel literals math math.primes
sequences tools.memory.private ;
IN: rosetta-code.safe-primes
CONSTANT: primes $[ 10,000,000 primes-upto ]
: safe/unsafe ( -- safe unsafe )
primes [ 1 - 2/ prime? ] partition ;
: count< ( seq n -- str ) '[ _ < ] count commas ;
: seq>commas ( seq -- str... |
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
... | #FreeBASIC | FreeBASIC | ' version 19-01-2019
' compile with: fbc -s console
Const As UInteger max = 10000000
Dim As UInteger i, j, sc1, usc1, sc2, usc2
Dim As String safeprimes, unsafeprimes
Dim As UByte sieve()
ReDim sieve(max)
' 0 = prime, 1 = no prime
sieve(0) = 1 : sieve(1) = 1
For i = 4 To max Step 2
sieve(i) = 1
Next
For i = 3... |
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 compu... | #OCaml | OCaml | type 'a btree = Leaf of 'a | BTree of ('a btree * 'a btree)
let rec next = function
| [] -> None
| h :: t -> match h with
| Leaf x -> Some (x,t)
| BTree(a,b) -> next (a::b::t)
let samefringe t1 t2 =
let rec aux s1 s2 = match (next s1, next s2) with
| None, None -> true
| None, _ | _, None -> 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... | #MUMPS | MUMPS | ERATO1(HI)
;performs the Sieve of Erotosethenes up to the number passed in.
;This version sets an array containing the primes
SET HI=HI\1
KILL ERATO1 ;Don't make it new - we want it to remain after we quit the function
NEW I,J,P
FOR I=2:1:(HI**.5)\1 FOR J=I*I:I:HI SET P(J)=1
FOR I=2:1:HI S:'$DATA(P(I)) ERATO1(I)... |
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 th... | #Phix | Phix | procedure solve(integer sailors)
integer m, sm1 = sailors-1
if sm1=0 then -- edge condition for solve(1) [ avoid /0 ]
m = sailors
else
for n=sailors to 1_000_000_000 by sailors do -- morning pile divisible by #sailors
m = n
for j=1 to sailors do -- see ... |
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/et... | #Haskell | Haskell | import Data.List (findIndex, find)
data City = City
{ name :: String
, population :: Float
} deriving (Read, Show)
-- CITY PROPERTIES ------------------------------------------------------------
cityName :: City -> String
cityName (City x _) = x
cityPop :: City -> Float
cityPop (City _ x) = x
mbCityName :... |
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 widt... | #Racket | Racket |
#lang racket
;; 1. Racket has exact unlimited integers and fractions, which can be
;; used to perform exact operations. For example, given an inexact
;; flonum, we can convert it to an exact fraction and work with that:
(define (exact+ x y)
(+ (inexact->exact x) (inexact->exact y)))
;; (A variant of this w... |
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 widt... | #Raku | Raku | say "Floating points: (Nums)";
say "Error: " ~ (2**-53).Num;
sub infix:<±+> (Num $a, Num $b) {
my \ε = (2**-53).Num;
$a - ε + $b, $a + ε + $b,
}
printf "%4.16f .. %4.16f\n", (1.14e0 ±+ 2e3);
say "\nRationals:";
say ".1 + .2 is exactly equal to .3: ", .1 + .2 === .3;
say "\nLarge denominators require e... |
http://rosettacode.org/wiki/Ruth-Aaron_numbers | Ruth-Aaron numbers | A Ruth–Aaron pair consists of two consecutive integers (e.g., 714 and 715) for which the sums of the prime divisors of each integer are equal. So called because 714 is Babe Ruth's lifetime home run record; Hank Aaron's 715th home run broke this record and 714 and 715 have the same prime divisor sum.
A Ruth–Aaron tri... | #J | J | NB. using factors
30{.1 2+/~I. 2 =/\ +/@q: 1+i.100000
5 6
8 9
15 16
77 78
125 126
714 715
948 949
1330 1331
1520 1521
1862 1863
2491 2492
3248 3249
4185 4186
4191 4192
5405 5406
5560 5561
5959 5960
6867 6868
8280 8281
8463 8464
10647 10648
12351 12... |
http://rosettacode.org/wiki/Ruth-Aaron_numbers | Ruth-Aaron numbers | A Ruth–Aaron pair consists of two consecutive integers (e.g., 714 and 715) for which the sums of the prime divisors of each integer are equal. So called because 714 is Babe Ruth's lifetime home run record; Hank Aaron's 715th home run broke this record and 714 and 715 have the same prime divisor sum.
A Ruth–Aaron tri... | #Julia | Julia | using Lazy
using Primes
sumprimedivisors(n) = sum([p[1] for p in factor(n)])
ruthaaron(n) = sumprimedivisors(n) == sumprimedivisors(n + 1)
ruthaarontriple(n) = sumprimedivisors(n) == sumprimedivisors(n + 1) ==
sumprimedivisors(n + 2)
sumprimefactors(n) = sum([p[1] * p[2] for p in factor(n)])
ruthaaronfactors(n) ... |
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 ... | #ALGOL_68 | ALGOL 68 | FORMAT hay stack := $c("Zig","Zag","Wally","Ronald","Bush","Krusty","Charlie","Bush","Bozo")$;
FILE needle exception; STRING ref needle;
associate(needle exception, ref needle);
PROC index = (FORMAT haystack, REF STRING needle)INT:(
INT out;
ref needle := needle;
getf(needle exception,(haystack, out));... |
http://rosettacode.org/wiki/Runtime_evaluation | Runtime evaluation | Task
Demonstrate a language's ability for programs to execute code written in the language provided at runtime.
Show what kind of program fragments are permitted (e.g. expressions vs. statements), and how to get values in and out (e.g. environments, arguments, return values), if applicable what lexical/static environ... | #BASIC | BASIC | 100 DEF PROC graph f$
110 LOCAL x,y
120 PLOT 0,90
130 FOR x = -2 TO 2 STEP 0.02
140 LET y = VAL(f$)
150 DRAW TO x*50+100, y*50+90
160 NEXT x
170 END PROC
|
http://rosettacode.org/wiki/Runtime_evaluation | Runtime evaluation | Task
Demonstrate a language's ability for programs to execute code written in the language provided at runtime.
Show what kind of program fragments are permitted (e.g. expressions vs. statements), and how to get values in and out (e.g. environments, arguments, return values), if applicable what lexical/static environ... | #BBC_BASIC | BBC BASIC | expr$ = "PI^2 + 1"
PRINT EVAL(expr$) |
http://rosettacode.org/wiki/Runtime_evaluation | Runtime evaluation | Task
Demonstrate a language's ability for programs to execute code written in the language provided at runtime.
Show what kind of program fragments are permitted (e.g. expressions vs. statements), and how to get values in and out (e.g. environments, arguments, return values), if applicable what lexical/static environ... | #Burlesque | Burlesque |
blsq ) {5 5 .+}e!
10
|
http://rosettacode.org/wiki/Safe_primes_and_unsafe_primes | Safe primes and unsafe primes | Definitions
A safe prime is a prime p and where (p-1)/2 is also prime.
The corresponding prime (p-1)/2 is known as a Sophie Germain prime.
An unsafe prime is a prime p and where (p-1)/2 isn't a prime.
An unsafe prime is a prime that isn't a safe prime.
Task
... | #Frink | Frink |
safePrimes[end=undef] := select[primes[5,end], {|p| isPrime[(p-1)/2] }]
unsafePrimes[end=undef] := select[primes[2,end], {|p| p<5 or isPrime[(p-1)/2] }]
println["First 35 safe primes: " + first[safePrimes[], 35]]
println["Safe primes below 1,000,000: " + length[safePrimes[1_000_000]]]
println["Safe primes below 1... |
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
... | #Go | Go | package main
import "fmt"
func sieve(limit uint64) []bool {
limit++
// True denotes composite, false denotes prime.
c := make([]bool, limit) // all false by default
c[0] = true
c[1] = true
// apart from 2 all even numbers are of course composite
for i := uint64(4); i < limit; i += 2 {
... |
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 compu... | #Perl | Perl |
#!/usr/bin/perl
use strict;
my @trees = (
# 0..2 are same
[ 'd', [ 'c', [ 'a', 'b', ], ], ],
[ [ 'd', 'c' ], [ 'a', 'b' ] ],
[ [ [ 'd', 'c', ], 'a', ], 'b', ],
# and this one's different!
[ [ [ [ [ [ 'a' ], 'b' ], 'c', ], 'd', ], 'e', ], 'f' ],
);
for my $tree_idx (1 .. $#trees) {
prin... |
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... | #Neko | Neko | /* The Computer Language Shootout
http://shootout.alioth.debian.org/
contributed by Nicolas Cannasse
*/
fmt = function(i) {
var s = $string(i);
while( $ssize(s) < 8 )
s = " "+s;
return s;
}
nsieve = function(m) {
var a = $amake(m);
var count = 0;
v... |
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 th... | #Picat | Picat | main ?=>
between(2,9,N), % N: number of sailors
once s(N),
fail.
main => true.
s(N) =>
next_candidate(N+1,N,C), % C: original number of coconuts
divide(N,N,C,Cr), % Cr: remainder
printf("%d: original = %d, remainder = %d, final share = %d\n",N,C,Cr,Cr div N).
next_candid... |
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 th... | #Python | Python | def monkey_coconuts(sailors=5):
"Parameterised the number of sailors using an inner loop including the last mornings case"
nuts = sailors
while True:
n0, wakes = nuts, []
for sailor in range(sailors + 1):
portion, remainder = divmod(n0, sailors)
wakes.append((n0, ... |
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/et... | #J | J | colnumeric=: 0&".&.>@{`[`]}
data=: 1 colnumeric |: fixcsv 0 :0
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
) |
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/et... | #Java | Java | import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.function.Consumer;
import java.util.function.Predicate;
/**
* Represent a City and it's population.
* City-Objects do have a natural ordering, they are ordered by their poulation (descending)
*/
class City implements Com... |
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 widt... | #REXX | REXX | numeric digits 1000 /*defines precision to be 1,000 decimal digits. */
y=digits() /*sets Y to existing number of decimal digits.*/
numeric digits y + y%10 /*increase the (numeric) decimal digits by 10%.*/ |
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 widt... | #Ruby | Ruby | require 'bigdecimal'
require 'bigdecimal/util' # String#to_d
def safe_add(a, b, prec)
a, b = a.to_d, b.to_d
rm = BigDecimal::ROUND_MODE
orig = BigDecimal.mode(rm)
BigDecimal.mode(rm, BigDecimal::ROUND_FLOOR)
low = a.add(b, prec)
BigDecimal.mode(rm, BigDecimal::ROUND_CEILING)
high = a.add(b, prec)
... |
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 widt... | #Scala | Scala | object SafeAddition extends App {
val (a, b) = (1.2, 0.03)
val result = safeAdd(a, b)
private def safeAdd(a: Double, b: Double) = Seq(stepDown(a + b), stepUp(a + b))
private def stepDown(d: Double) = Math.nextAfter(d, Double.NegativeInfinity)
private def stepUp(d: Double) = Math.nextUp(d)
println(f"... |
http://rosettacode.org/wiki/Ruth-Aaron_numbers | Ruth-Aaron numbers | A Ruth–Aaron pair consists of two consecutive integers (e.g., 714 and 715) for which the sums of the prime divisors of each integer are equal. So called because 714 is Babe Ruth's lifetime home run record; Hank Aaron's 715th home run broke this record and 714 and 715 have the same prime divisor sum.
A Ruth–Aaron tri... | #Pascal | Pascal | program RuthAaronNumb;
// gets factors of consecutive integers fast
// limited to 1.2e11
{$IFDEF FPC}
{$MODE DELPHI} {$OPTIMIZATION ON,ALL} {$COPERATORS ON}
{$ELSE}
{$APPTYPE CONSOLE}
{$ENDIF}
uses
sysutils,
strutils //Numb2USA
{$IFDEF WINDOWS},Windows{$ENDIF}
;
//###########################################... |
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 ... | #Arturo | Arturo | haystack: [Zig Zag Wally Ronald Bush Krusty Charlie Bush Bozo]
loop [Bush Washington] 'needle [
i: index haystack needle
if? empty? i -> panic ~"|needle| is not in haystack"
else -> print [i needle]
] |
http://rosettacode.org/wiki/Runtime_evaluation | Runtime evaluation | Task
Demonstrate a language's ability for programs to execute code written in the language provided at runtime.
Show what kind of program fragments are permitted (e.g. expressions vs. statements), and how to get values in and out (e.g. environments, arguments, return values), if applicable what lexical/static environ... | #Cach.C3.A9_ObjectScript | Caché ObjectScript | USER>Set cmd="Write ""Hello, World!"""
USER>Xecute cmd
Hello, World!
USER>Set fnc="(num1, num2) Set res=num1+num2 Quit res"
USER>Write $Xecute(fnc, 2, 3)
5
|
http://rosettacode.org/wiki/Runtime_evaluation | Runtime evaluation | Task
Demonstrate a language's ability for programs to execute code written in the language provided at runtime.
Show what kind of program fragments are permitted (e.g. expressions vs. statements), and how to get values in and out (e.g. environments, arguments, return values), if applicable what lexical/static environ... | #Common_Lisp | Common Lisp | (eval '(+ 4 5)) ; returns 9 |
http://rosettacode.org/wiki/Runtime_evaluation | Runtime evaluation | Task
Demonstrate a language's ability for programs to execute code written in the language provided at runtime.
Show what kind of program fragments are permitted (e.g. expressions vs. statements), and how to get values in and out (e.g. environments, arguments, return values), if applicable what lexical/static environ... | #D.C3.A9j.C3.A0_Vu | Déjà Vu | !run-blob !compile-string "(fake filename)" "!print \qHello world\q" |
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
... | #Haskell | Haskell |
import Text.Printf (printf)
import Data.Numbers.Primes (isPrime, primes)
main = do
printf "First 35 safe primes: %s\n" (show $ take 35 safe)
printf "There are %d safe primes below 100,000.\n" (length $ takeWhile (<1000000) safe)
printf "There are %d safe primes below 10,000,000.\n\n" (length $ takeWhile (<10... |
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 compu... | #Phix | Phix | --
-- demo\rosetta\Same_Fringe.exw
-- ============================
--
-- In some cases it may help to replace the single res with a table, such
-- that if you have concurrent task pairs {1,2} and {3,4} with a table of
-- result indexes ridx = {1,1,2,2}, then each updates res[ridx[tidx]]. In
-- other words if extend... |
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... | #NetRexx | NetRexx | /* NetRexx */
options replace format comments java crossref savelog symbols binary
parse arg loWatermark hiWatermark .
if loWatermark = '' | loWatermark = '.' then loWatermark = 1
if hiWatermark = '' | hiWatermark = '.' then hiWatermark = 200
do
if \loWatermark.datatype('w') | \hiWatermark.datatype('w') then -
... |
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 th... | #R | R | coconutsProblem <- function(sailorCount)
{
stopifnot(sailorCount > 1) #Problem makes no sense otherwise
initalCoconutCount <- sailorCount
repeat
{
initalCoconutCount <- initalCoconutCount + 1
coconutCount <- initalCoconutCount
for(i in seq_len(sailorCount))
{
if(coconutCount %% sailorCount... |
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 th... | #Racket | Racket | #lang racket
(define (wake-and-split nuts sailors depth wakes)
(define-values (portion remainder) (quotient/remainder nuts sailors))
(define monkey (if (zero? depth) 0 1))
(define new-wakes (cons (list nuts portion remainder) wakes))
(and (positive? portion)
(= remainder monkey)
(if (zero? depth... |
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/et... | #JavaScript | JavaScript | (function () {
'use strict';
// find :: (a -> Bool) -> [a] -> Maybe a
function find(f, xs) {
for (var i = 0, lng = xs.length; i < lng; i++) {
if (f(xs[i])) return xs[i];
}
return undefined;
}
// findIndex :: (a -> Bool) -> [a] -> Maybe Int
function findInd... |
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 widt... | #Swift | Swift | let a = 1.2
let b = 0.03
print("\(a) + \(b) is in the range \((a + b).nextDown)...\((a + b).nextUp)") |
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 widt... | #Tcl | Tcl | package require critcl
package provide stepaway 1.0
critcl::ccode {
#include <math.h>
#include <float.h>
}
critcl::cproc stepup {double value} double {
return nextafter(value, DBL_MAX);
}
critcl::cproc stepdown {double value} double {
return nextafter(value, -DBL_MAX);
} |
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 widt... | #Transd | Transd | #lang transd
MainModule : {
a: 1.2,
b: 0.03,
safeAdd: (λ d Double() e Double()
(ret [(decr (+ d e)), (incr (+ d e))])),
_start: (λ
(lout "(+ " a " " b ") is in the range: " prec: 20 (safeAdd a b))
)
} |
http://rosettacode.org/wiki/Ruth-Aaron_numbers | Ruth-Aaron numbers | A Ruth–Aaron pair consists of two consecutive integers (e.g., 714 and 715) for which the sums of the prime divisors of each integer are equal. So called because 714 is Babe Ruth's lifetime home run record; Hank Aaron's 715th home run broke this record and 714 and 715 have the same prime divisor sum.
A Ruth–Aaron tri... | #Perl | Perl | #!/usr/bin/perl
use strict;
use warnings;
use ntheory qw( factor vecsum );
use List::AllUtils qw( uniq );
#use Data::Dump 'dd'; dd factor(6); exit;
my $n = 1;
my @answers;
while( @answers < 30 )
{
vecsum(factor($n)) == vecsum(factor($n+1)) and push @answers, $n;
$n++;
}
print "factors:\n\n@answers\n\n" =~... |
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 ... | #AutoHotkey | AutoHotkey | haystack = Zig Zag Wally Ronald Bush Krusty Charlie Bush Bozo
needle = bush, washington
Loop, Parse, needle, `,
{
If InStr(haystack, A_LoopField)
MsgBox, % A_LoopField
Else
MsgBox % A_LoopField . " not in haystack"
} |
http://rosettacode.org/wiki/Runtime_evaluation | Runtime evaluation | Task
Demonstrate a language's ability for programs to execute code written in the language provided at runtime.
Show what kind of program fragments are permitted (e.g. expressions vs. statements), and how to get values in and out (e.g. environments, arguments, return values), if applicable what lexical/static environ... | #E | E | ? e`1 + 1`.eval(safeScope)
# value: 2 |
http://rosettacode.org/wiki/Runtime_evaluation | Runtime evaluation | Task
Demonstrate a language's ability for programs to execute code written in the language provided at runtime.
Show what kind of program fragments are permitted (e.g. expressions vs. statements), and how to get values in and out (e.g. environments, arguments, return values), if applicable what lexical/static environ... | #EchoLisp | EchoLisp |
(eval (list * 6 7))
→ 42
(eval '(* 6 7)) ;; quoted argument
→ 42
(eval (read-from-string "(* 6 7)"))
→ 42
|
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
... | #J | J | NB. play around a bit to get primes less than ten million
p:inv 10000000
664579
p:664579
10000019
PRIMES =: p:i.664579
10 {. PRIMES
2 3 5 7 11 13 17 19 23 29
{: PRIMES
9999991
primeQ =: 1&p:
safeQ =: primeQ@:-:@:<:
Filter =: (#~`)(`:6)
SAFE =: safeQ Filter PRIMES
NB. first thirty... |
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
... | #Java | Java | public class SafePrimes {
public static void main(String... args) {
// Use Sieve of Eratosthenes to find primes
int SIEVE_SIZE = 10_000_000;
boolean[] isComposite = new boolean[SIEVE_SIZE];
// It's really a flag indicating non-prime, but composite usually applies
isComposite[... |
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 compu... | #PicoLisp | PicoLisp | (de nextLeaf (Rt Tree)
(co Rt
(recur (Tree)
(when Tree
(recurse (cadr Tree))
(yield (car Tree))
(recurse (cddr Tree)) ) ) ) )
(de cmpTrees (Tree1 Tree2)
(prog1
(use (Node1 Node2)
(loop
(setq
Node1 (nextLeaf "rt1" Tree1)... |
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 compu... | #Python | Python | try:
from itertools import zip_longest as izip_longest # Python 3.x
except:
from itertools import izip_longest # Python 2.6+
def fringe(tree):
"""Yield tree members L-to-R depth first,
as if stored in a binary tree"""
for node1 in tree:
if isinstance(node1, tuple):
... |
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... | #newLISP | newLISP | (set 'upper-bound 1000)
; The initial sieve is a list of all the numbers starting at 2.
(set 'sieve (sequence 2 upper-bound))
; Keep working until the list is empty.
(while sieve
; The first number in the list is always prime
(set 'new-prime (sieve 0))
(println new-prime)
; Filter the list leaving only the ... |
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 th... | #Raku | Raku | my @ones = flat 'th', 'st', 'nd', 'rd', 'th' xx 6;
my @teens = 'th' xx 10;
my @suffix = lazy flat (@ones, @teens, @ones xx 8) xx *;
# brute force the first six
for 1 .. 6 -> $sailors { for $sailors .. * -> $coconuts { last if check( $sailors, $coconuts ) } }
# finesse 7 through 15
for 7 .. 15 -> $sailors { next if ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.