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... | #jq | jq | def first(s): [s][0]; |
http://rosettacode.org/wiki/Safe_addition | Safe addition | Implementation of interval arithmetic and more generally fuzzy number arithmetic require operations that yield safe upper and lower bounds of the exact result.
For example, for an addition, it is the operations +↑ and +↓ defined as: a +↓ b ≤ a + b ≤ a +↑ b.
Additionally it is desired that the widt... | #Wren | Wren | /* safe_addition.wren */
class Interval {
construct new(lower, upper) {
if (lower.type != Num || upper.type != Num) {
Fiber.abort("Arguments must be numbers.")
}
_lower = lower
_upper = upper
}
lower { _lower }
upper { _upper }
static stepAway(x) { new... |
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... | #Phix | Phix | with javascript_semantics
procedure ruth_aaron(bool d, integer n=30, l=2, i=1)
string fd = iff(d?"divisors":"factors"),
ns = iff(n=1?"":sprintf(" %d",n)),
ss = iff(n=1?"":"s"),
nt = iff(l=2?"number":"triple")
printf(1,"First%s Ruth-Aaron %s%s (%s):\n",{ns,nt,ss,fd})
integer ... |
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 ... | #AWK | AWK | #! /usr/bin/awk -f
BEGIN {
# create the array, using the word as index...
words="Zig Zag Wally Ronald Bush Krusty Charlie Bush Bozo";
split(words, haystack_byorder, " ");
j=0;
for(idx in haystack_byorder) {
haystack[haystack_byorder[idx]] = j;
j++;
}
# now check for needle (we know it is t... |
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... | #Elena | Elena | import extensions'scripting;
public program()
{
lscript.interpret("system'console.writeLine(""Hello World"")");
} |
http://rosettacode.org/wiki/Runtime_evaluation | Runtime evaluation | Task
Demonstrate a language's ability for programs to execute code written in the language provided at runtime.
Show what kind of program fragments are permitted (e.g. expressions vs. statements), and how to get values in and out (e.g. environments, arguments, return values), if applicable what lexical/static environ... | #Elixir | Elixir | iex(1)> Code.eval_string("x + 4 * Enum.sum([1,2,3,4])", [x: 17])
{57, [x: 17]}
iex(2)> Code.eval_string("c = a + b", [a: 1, b: 2])
{3, [a: 1, b: 2, c: 3]}
iex(3)> Code.eval_string("a = a + b", [a: 1, b: 2])
{3, [a: 3, b: 2]} |
http://rosettacode.org/wiki/Runtime_evaluation | Runtime evaluation | Task
Demonstrate a language's ability for programs to execute code written in the language provided at runtime.
Show what kind of program fragments are permitted (e.g. expressions vs. statements), and how to get values in and out (e.g. environments, arguments, return values), if applicable what lexical/static environ... | #Erlang | Erlang | 1> {ok, Tokens, _} = erl_scan:string("X + 4 * lists:sum([1,2,3,4]).").
...
2> {ok, [Form]} = erl_parse:parse_exprs(Tokens).
...
3> Bindings = erl_eval:add_binding('X', 17, erl_eval:new_bindings()).
[{'X',17}]
4> {value, Value, _} = erl_eval:expr(Form, Bindings).
{value,57,[{'X',17}]}
5> Value.
57
|
http://rosettacode.org/wiki/Safe_primes_and_unsafe_primes | Safe primes and unsafe primes | Definitions
A safe prime is a prime p and where (p-1)/2 is also prime.
The corresponding prime (p-1)/2 is known as a Sophie Germain prime.
An unsafe prime is a prime p and where (p-1)/2 isn't a prime.
An unsafe prime is a prime that isn't a safe prime.
Task
... | #jq | jq |
def is_prime:
. as $n
| if ($n < 2) then false
elif ($n % 2 == 0) then $n == 2
elif ($n % 3 == 0) then $n == 3
elif ($n % 5 == 0) then $n == 5
elif ($n % 7 == 0) then $n == 7
elif ($n % 11 == 0) then $n == 11
elif ($n % 13 == 0) then $n == 13
elif ($n % 17 == 0) then $n == ... |
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
... | #Julia | Julia | using Primes, Formatting
function parseprimelist()
primelist = primes(2, 10000000)
safeprimes = Vector{Int64}()
unsafeprimes = Vector{Int64}()
for p in primelist
if isprime(div(p - 1, 2))
push!(safeprimes, p)
else
push!(unsafeprimes, p)
end
end
p... |
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... | #Racket | Racket |
#lang racket
(module same-fringe lazy
(provide same-fringe?)
(define (same-fringe? t1 t2)
(! (equal? (flatten t1) (flatten t2))))
(define (flatten tree)
(if (list? tree)
(apply append (map flatten tree))
(list tree))))
(require 'same-fringe)
(module+ test
(require rackunit)
(check-... |
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... | #Raku | Raku | sub fringe ($tree) {
multi sub fringey (Pair $node) { fringey $_ for $node.kv; }
multi sub fringey ( Any $leaf) { take $leaf; }
gather fringey $tree;
}
sub samefringe ($a, $b) { fringe($a) eqv fringe($b) }
# Testing:
my $a = 1 => 2 => 3 => 4 => 5 => 6 => 7 => 8;
my $b = 1 => (( 2 => 3 ) => (4 => (5 ... |
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... | #Nial | Nial | primes is sublist [ each (2 = sum eachright (0 = mod) [pass,count]), pass ] rest count
|
http://rosettacode.org/wiki/Sailors,_coconuts_and_a_monkey_problem | Sailors, coconuts and a monkey problem | Five sailors are shipwrecked on an island and collect a large pile of coconuts during the day.
That night the first sailor wakes up and decides to take his first share early so tries to divide the pile of coconuts equally into five piles but finds that there is one coconut left over, so he tosses it to a monkey and th... | #REXX | REXX | /*REXX program solves a riddle of 5 sailors, a pile of coconuts, and a monkey. */
parse arg L H .; if L=='' then L= 5 /*L not specified? Then use default.*/
if H=='' then H= 6 /*H " " " " default.*/
... |
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... | #Ring | Ring |
# Project : Sailors, coconuts and a monkey problem
scm(5)
scm(6)
func scm(sailors)
sm1 = sailors-1
if sm1 = 0
m = sailors
else
for n=sailors to 1000000000 step sailors
m = n
for j=1 to sailors
if m... |
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... | #Julia | Julia | using DataFrames
dataset = DataFrame(name=["Lagos", "Cairo", "Kinshasa-Brazzaville", "Greater Johannesburg", "Mogadishu",
"Khartoum-Omdurman", "Dar Es Salaam", "Alexandria", "Abidjan", "Casablanca"],
population=[21.0, 15.2, 11.3, 7.55, 5.85, 4.98, 4.7, 4.58, 4.4, 3.98])
... |
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... | #Kotlin | Kotlin | // version 1.1.2
class City(val name: String, val pop: Double)
val cities = listOf(
City("Lagos", 21.0),
City("Cairo", 15.2),
City("Kinshasa-Brazzaville", 11.3),
City("Greater Johannesburg", 7.55),
City("Mogadishu", 5.85),
City("Khartoum-Omdurman", 4.98),
City("Dar Es Salaam", 4.7),
... |
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... | #Quackery | Quackery | [ behead dup dip nested rot
witheach
[ tuck != if
[ dup dip
[ nested join ] ] ]
drop ] is -duplicates ( [ --> [ )
[ primefactors -duplicates ] is primedivisors ( n --> n )
[ 0 swap witheach + ] is sum ( [ --> n )
[ [] t... |
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... | #Raku | Raku | use Prime::Factor;
my @pf = lazy (^∞).hyper(:1000batch).map: *.&prime-factors.sum;
my @upf = lazy (^∞).hyper(:1000batch).map: *.&prime-factors.unique.sum;
# Task: < 1 second
put "First 30 Ruth-Aaron numbers (Factors):\n" ~
(1..∞).grep( { @pf[$_] == @pf[$_ + 1] } )[^30];
put "\nFirst 30 Ruth-Aaron numbers (Diviso... |
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 ... | #BASIC | BASIC | DATA foo, bar, baz, quux, quuux, quuuux, bazola, ztesch, foo, bar, thud, grunt
DATA foo, bar, bletch, foo, bar, fum, fred, jim, sheila, barney, flarp, zxc
DATA spqr, wombat, shme, foo, bar, baz, bongo, spam, eggs, snork, foo, bar
DATA zot, blarg, wibble, toto, titi, tata, tutu, pippo, pluto, paperino, aap
DATA noot, mi... |
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... | #Factor | Factor | IN: scratchpad "\"Hello, World!\" print" ( -- ) eval
Hello, World!
IN: scratchpad 4 5 "+" ( a b -- c ) eval
9
|
http://rosettacode.org/wiki/Runtime_evaluation | Runtime evaluation | Task
Demonstrate a language's ability for programs to execute code written in the language provided at runtime.
Show what kind of program fragments are permitted (e.g. expressions vs. statements), and how to get values in and out (e.g. environments, arguments, return values), if applicable what lexical/static environ... | #Forth | Forth | s" variable foo 1e fatan 4e f*" evaluate
f. \ 3.14159...
1 foo ! |
http://rosettacode.org/wiki/Runtime_evaluation | Runtime evaluation | Task
Demonstrate a language's ability for programs to execute code written in the language provided at runtime.
Show what kind of program fragments are permitted (e.g. expressions vs. statements), and how to get values in and out (e.g. environments, arguments, return values), if applicable what lexical/static environ... | #Frink | Frink |
eval["length = 1234 feet + 2 inches"]
|
http://rosettacode.org/wiki/Safe_primes_and_unsafe_primes | Safe primes and unsafe primes | Definitions
A safe prime is a prime p and where (p-1)/2 is also prime.
The corresponding prime (p-1)/2 is known as a Sophie Germain prime.
An unsafe prime is a prime p and where (p-1)/2 isn't a prime.
An unsafe prime is a prime that isn't a safe prime.
Task
... | #Kotlin | Kotlin | // Version 1.2.70
fun sieve(limit: Int): BooleanArray {
// True denotes composite, false denotes prime.
val c = BooleanArray(limit + 1) // all false by default
c[0] = true
c[1] = true
// apart from 2 all even numbers are of course composite
for (i in 4..limit step 2) c[i] = true
var p = 3 ... |
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... | #REXX | REXX | /* REXX ***************************************************************
* Same Fringe
* 1 A A
* / \ / \ / \
* / \ / \ / \
* / \ / \ / \
* 2 3 B ... |
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... | #Nim | Nim | from math import sqrt
iterator primesUpto(limit: int): int =
let sqrtLimit = int(sqrt(float64(limit)))
var composites = newSeq[bool](limit + 1)
for n in 2 .. sqrtLimit: # cull to square root of limit
if not composites[n]: # if prime -> cull its composites
for c in countup(n * n, limit, n): # start at ... |
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... | #Ruby | Ruby | def valid?(sailor, nuts)
sailor.times do
return false if (nuts % sailor) != 1
nuts -= 1 + nuts / sailor
end
nuts > 0 and nuts % sailor == 0
end
[5,6].each do |sailor|
n = sailor
n += 1 until valid?(sailor, n)
puts "\n#{sailor} sailors => #{n} coconuts"
(sailor+1).times do
div, mod = n.divmod... |
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... | #Scala | Scala | object Sailors extends App {
var x = 0
private def valid(n: Int, _nuts: Int): Boolean = {
var nuts = _nuts
for (k <- n until 0 by -1) {
if (nuts % n != 1) return false
nuts -= 1 + nuts / n
}
nuts != 0 && (nuts % n == 0)
}
for (nSailors <- 2 until 10) {
while (!valid(nSailors,... |
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... | #Lingo | Lingo | on findFirstRecord (data, condition)
cnt = data.count
repeat with i = 1 to cnt
record = data[i]
if value(condition) then return [#index:i-1, #record:record]
end repeat
end |
http://rosettacode.org/wiki/Ruth-Aaron_numbers | Ruth-Aaron numbers | A Ruth–Aaron pair consists of two consecutive integers (e.g., 714 and 715) for which the sums of the prime divisors of each integer are equal. So called because 714 is Babe Ruth's lifetime home run record; Hank Aaron's 715th home run broke this record and 714 and 715 have the same prime divisor sum.
A Ruth–Aaron tri... | #Sidef | Sidef | say "First 30 Ruth-Aaron numbers (factors):"
say 30.by {|n| (sopfr(n) == sopfr(n+1)) && (n > 0) }.join(' ')
say "\nFirst 30 Ruth-Aaron numbers (divisors):"
say 30.by {|n| ( sopf(n) == sopf(n+1)) && (n > 0) }.join(' ') |
http://rosettacode.org/wiki/Ruth-Aaron_numbers | Ruth-Aaron numbers | A Ruth–Aaron pair consists of two consecutive integers (e.g., 714 and 715) for which the sums of the prime divisors of each integer are equal. So called because 714 is Babe Ruth's lifetime home run record; Hank Aaron's 715th home run broke this record and 714 and 715 have the same prime divisor sum.
A Ruth–Aaron tri... | #Wren | Wren | import "./math" for Int, Nums
import "./seq" for Lst
import "./fmt" for Fmt
var resF = []
var resD = []
var resT = [] // factors only
var n = 2
var factors1 = []
var factors2 = [2]
var factors3 = [3]
var sum1 = 0
var sum2 = 2
var sum3 = 3
var countF = 0
var countD = 0
var countT = 0
while (countT < 1 || countD < 30 |... |
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 ... | #Batch_File | Batch File | @echo off
setlocal enabledelayedexpansion
%==Sample list==%
set "data=foo, bar, baz, quux, quuux, quuuux, bazola, ztesch, foo, bar, thud, grunt"
set "data=%data% foo, bar, bletch, foo, bar, fum, fred, jim, sheila, barney, flarp, zxc"
set "data=%data% spqr, wombat, shme, foo, bar, baz, bongo, spam, eggs, snork, foo, ... |
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... | #Go | Go | package main
import (
"fmt"
"bitbucket.org/binet/go-eval/pkg/eval"
"go/token"
)
func main() {
w := eval.NewWorld();
fset := token.NewFileSet();
code, err := w.Compile(fset, "1 + 2")
if err != nil {
fmt.Println("Compile error");
return
}
val, err := code.Run();
if err != nil {
fmt.Println("Run time... |
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... | #Groovy | Groovy | [2011, 2016, 2022, 2033, 2039, 2044, 2050, 2061, 2067, 2072, 2078, 2089, 2095, 2101, 2107, 2112, 2118] |
http://rosettacode.org/wiki/Runtime_evaluation | Runtime evaluation | Task
Demonstrate a language's ability for programs to execute code written in the language provided at runtime.
Show what kind of program fragments are permitted (e.g. expressions vs. statements), and how to get values in and out (e.g. environments, arguments, return values), if applicable what lexical/static environ... | #GW-BASIC | GW-BASIC | 10 LINE INPUT "Type an expression: ",A$
20 OPEN "CHAIN.TMP" FOR OUTPUT AS #1
30 PRINT #1, "70 LET Y=("+A$+")"
40 CLOSE #1
50 CHAIN MERGE "CHAIN.TMP",60,ALL
60 FOR X=0 TO 5
70 REM
80 PRINT X,Y
90 NEXT X
100 GOTO 10 |
http://rosettacode.org/wiki/Safe_primes_and_unsafe_primes | Safe primes and unsafe primes | Definitions
A safe prime is a prime p and where (p-1)/2 is also prime.
The corresponding prime (p-1)/2 is known as a Sophie Germain prime.
An unsafe prime is a prime p and where (p-1)/2 isn't a prime.
An unsafe prime is a prime that isn't a safe prime.
Task
... | #Ksh | Ksh |
#!/bin/ksh
# Safe primes and unsafe primes
# # Variables:
#
integer safecnt=0 safedisp=35 safecnt1M=0
integer unsacnt=0 unsadisp=40 unsacnt1M=0
typeset -a safeprime unsafeprime
# # Functions:
#
# # Function _isprime(n) return 1 for prime, 0 for not prime
#
function _isprime {
typeset _n ; integer _n=$1
type... |
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
... | #Lua | Lua | -- FUNCS:
local function T(t) return setmetatable(t, {__index=table}) end
table.filter = function(t,f) local s=T{} for _,v in ipairs(t) do if f(v) then s[#s+1]=v end end return s end
table.map = function(t,f,...) local s=T{} for _,v in ipairs(t) do s[#s+1]=f(v,...) end return s end
table.firstn = function(t,n) local s=... |
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... | #Scheme | Scheme | ; binary tree helpers from "Structure and Interpretation of Computer Programs" 2.3.3
(define (entry tree) (car tree))
(define (left-branch tree) (cadr tree))
(define (right-branch tree) (caddr tree))
(define (make-tree entry left right)
(list entry left right))
; returns a list of leftmost nodes from each level of ... |
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... | #Niue | Niue | [ dup 2 < ] '<2 ;
[ 1 + 'count ; [ <2 [ , ] when ] count times ] 'fill-stack ;
0 'n ; 0 'v ;
[ .clr 0 'n ; 0 'v ; ] 'reset ;
[ len 1 - n - at 'v ; ] 'set-base ;
[ n 1 + 'n ; ] 'incr-n ;
[ mod 0 = ] 'is-factor ;
[ dup * ] 'sqr ;
[ set-base
v sqr 2 at > not
[ [ dup v = not swap v is-factor and ] remove-if incr... |
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... | #Sidef | Sidef | func coconuts(sailors, monkeys=1) {
if ((sailors < 2) || (monkeys < 1) || (sailors <= monkeys)) {
return 0
}
var blue_cocos = sailors-1
var pow_bc = blue_cocos**sailors
var x_cocos = pow_bc
while ((x_cocos-blue_cocos)%sailors || ((x_cocos-blue_cocos)/sailors < 1)) {
x_cocos += po... |
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... | #Lua | Lua | -- Dataset declaration
local cityPops = {
{name = "Lagos", population = 21.0},
{name = "Cairo", population = 15.2},
{name = "Kinshasa-Brazzaville", population = 11.3},
{name = "Greater Johannesburg", population = 7.55},
{name = "Mogadishu", population = 5.85},
{name = "Khartoum-Omdurman", popula... |
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... | #XPL0 | XPL0 | func DivSum(N, AllDiv); \Return sum of divisors
int N, AllDiv; \all divisors vs. only prime divisors
int F, F0, S, Q;
[F:= 2; F0:= 0; S:= 0;
repeat Q:= N/F;
if rem(0) = 0 then
[if AllDiv then S:= S+F
else if F # F0 then
[S:= S+F; F0:= F];
N:= Q;
... |
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 ... | #BBC_BASIC | BBC BASIC | DIM haystack$(27)
haystack$() = "alpha","bravo","charlie","delta","echo","foxtrot","golf", \
\ "hotel","india","juliet","kilo","lima","mike","needle", \
\ "november","oscar","papa","quebec","romeo","sierra","tango", \
\ "needle","uniform","victor"... |
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... | #Harbour | Harbour |
Procedure Main()
local bAdd := {|Label,n1,n2| Qout( Label ), QQout( n1 + n2 )}
Eval( bAdd, "5+5 = ", 5, 5 )
Eval( bAdd, "5-5 = ", 5, -5 )
return
Upon execution you see:
5+5 = 10
5-5 = 0
|
http://rosettacode.org/wiki/Runtime_evaluation | Runtime evaluation | Task
Demonstrate a language's ability for programs to execute code written in the language provided at runtime.
Show what kind of program fragments are permitted (e.g. expressions vs. statements), and how to get values in and out (e.g. environments, arguments, return values), if applicable what lexical/static environ... | #HicEst | HicEst | value = XEQ( " temp = 1 + 2 + 3 ") ! value is assigned 6
! temp is undefined outside XEQ, if it was not defined before.
XEQ(" WRITE(Messagebox) 'Hello World !' ")
OPEN(FIle="my_file.txt")
READ(FIle="my_file.txt", Row=6) string
XEQ( string ) ! executes row 6 of my_file.txt |
http://rosettacode.org/wiki/Runtime_evaluation | Runtime evaluation | Task
Demonstrate a language's ability for programs to execute code written in the language provided at runtime.
Show what kind of program fragments are permitted (e.g. expressions vs. statements), and how to get values in and out (e.g. environments, arguments, return values), if applicable what lexical/static environ... | #J | J | ". 'a =: +/ 1 2 3' NB. execute a string to sum 1, 2 and 3 and assign to noun a |
http://rosettacode.org/wiki/Safe_primes_and_unsafe_primes | Safe primes and unsafe primes | Definitions
A safe prime is a prime p and where (p-1)/2 is also prime.
The corresponding prime (p-1)/2 is known as a Sophie Germain prime.
An unsafe prime is a prime p and where (p-1)/2 isn't a prime.
An unsafe prime is a prime that isn't a safe prime.
Task
... | #Maple | Maple | showSafePrimes := proc(n::posint)
local prime_list, k;
prime_list := [5];
for k to n - 1 do
prime_list := [op(prime_list), NumberTheory:-NextSafePrime(prime_list[-1])];
end do;
return prime_list;
end proc;
showUnsafePrimes := proc(n::posint)
local prime_num, k;
prime_num := [2];
for k to n-1 do
prime_num :... |
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
... | #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | ClearAll[SafePrimeQ, UnsafePrimeQ]
SafePrimeQ[n_Integer] := PrimeQ[n] \[And] PrimeQ[(n - 1)/2]
UnsafePrimeQ[n_Integer] := PrimeQ[n] \[And] ! PrimeQ[(n - 1)/2]
res = {};
i = 1;
While[Length[res] < 35,
test = SafePrimeQ[Prime[i]];
If[test, AppendTo[res, Prime[i]]];
i++
]
res
Count[Range[PrimePi[10^6]], _?(Prime /... |
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... | #Sidef | Sidef | var trees = [
# 0..2 are same
[ 'd', [ 'c', [ 'a', 'b', ], ], ],
[ [ 'd', 'c' ], [ 'a', 'b' ] ],
[ [ [ 'd', 'c', ], 'a', ], 'b', ],
# and this one's different!
[ [ [ [ [ [ 'a' ], 'b' ], 'c', ], 'd', ], 'e', ], 'f' ],
]
func get_tree_iterator(*rtrees) {
var tree
func {
tree = rt... |
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... | #Oberon-2 | Oberon-2 | MODULE Primes;
IMPORT Out, Math;
CONST N = 1000;
VAR a: ARRAY N OF BOOLEAN;
i, j, m: INTEGER;
BEGIN
(* Set all elements of a to TRUE. *)
FOR i := 1 TO N - 1 DO
a[i] := TRUE;
END;
(* Compute square root of N and convert back to INTEGER. *)
m := ENTIER(Math.Sqrt(N));
FOR... |
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... | #Tcl | Tcl | proc assert {expr {msg ""}} { ;# for "static" assertions that throw nice errors
if {![uplevel 1 [list expr $expr]]} {
if {$msg eq ""} {
catch {set msg "{[uplevel 1 [list subst -noc $expr]]}"}
}
throw {ASSERT ERROR} "{$expr} $msg"
}
}
proc divmod {a b} {
list [expr {$... |
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... | #Ksh | Ksh |
#!/bin/ksh
# Search a list of records
# # Variables:
#
json='{ "name": "Lagos", "population": 21.0 },
{ "name": "Cairo", "population": 15.2 },
{ "name": "Kinshasa-Brazzaville", "population": 11.3 },
{ "name": "Greater Johannesburg", "population": 7.55 },
{ "name": "Mogad... |
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... | #Maple | Maple | rec := [table(["name"="Lagos","population"=21.0]),
table(["name"="Cairo","population"=15.2]),
table(["name"="Kinshasa-Brazzaville","population"=11.3]),
table(["name"="Greater Johannesburg","population"=7.55]),
table(["name"="Mogadishu","population"=5.85]),
table(["name"="Khartoum-Omdurman"... |
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 ... | #BQN | BQN | list ← ⟨"Zig", "Zag", "Wally", "Ronald", "Bush", "Krusty", "Charlie", "Bush", "Boz", "Zag"⟩
IndexOf ← {
("Error: '" ∾𝕩∾ "' Not found in list") ! (≠𝕨)≠ind ← ⊑𝕨⊐⋈𝕩
ind
}
•Show list ⊐ "Wally"‿"Hi" # intended
•Show list IndexOf "Wally"
list IndexOf "Hi" |
http://rosettacode.org/wiki/Runtime_evaluation | Runtime evaluation | Task
Demonstrate a language's ability for programs to execute code written in the language provided at runtime.
Show what kind of program fragments are permitted (e.g. expressions vs. statements), and how to get values in and out (e.g. environments, arguments, return values), if applicable what lexical/static environ... | #Java | Java | import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.lang.reflect.InvocationTargetException;
import java.net.URI;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import javax.tools.FileObject;
import javax.tools.Fo... |
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
... | #Nim | Nim | import sequtils, strutils
const N = 10_000_000
# Erathostene's Sieve. Only odd values are represented. False value means prime.
var sieve: array[N div 2 + 1, bool]
sieve[0] = true # 1 is not prime.
for i in 1..sieve.high:
if not sieve[i]:
let n = 2 * i + 1
for k in countup(n * n, N, 2 * n):
siev... |
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
... | #Pascal | Pascal | program Sophie;
{ Find and count Sophie Germain primes }
{ uses unit mp_prime out of mparith of Wolfgang Ehrhardt
* http://wolfgang-ehrhardt.de/misc_en.html#mparith
http://wolfgang-ehrhardt.de/mp_intro.html }
{$APPTYPE CONSOLE}
uses
mp_prime,sysutils;
var
pS0,pS1:TSieve;
procedure SafeOrNoSavePrimeOut(totCnt:Na... |
http://rosettacode.org/wiki/Runtime_evaluation/In_an_environment | Runtime evaluation/In an environment | x
x
x
Do so in a way which:
does not involve string manipulation of the input source code
is plausibly extensible to a runtime-chosen set of bindings rather than just x
does not make x a global variable
or note that these are impossible.
See also
For more general examples and language-specific details, see... | #ALGOL_68 | ALGOL 68 | PROC eval_with_x = (STRING code, INT a, b)STRING:
(INT x=a; evaluate(code) ) + (INT x=b; evaluate(code));
print((eval_with_x("2 ** x", 3, 5), new line)) |
http://rosettacode.org/wiki/Same_fringe | Same fringe | Write a routine that will compare the leaves ("fringe") of two binary trees to determine whether they are the same list of leaves when visited left-to-right. The structure or balance of the trees does not matter; only the number, order, and value of the leaves is important.
Any solution is allowed here, but many compu... | #Tcl | Tcl | package require Tcl 8.6
package require struct::tree
# A wrapper round a coroutine for iterating over the leaves of a tree in order
proc leafiterator {tree} {
coroutine coro[incr ::coroutines] apply {tree {
yield [info coroutine]
$tree walk [$tree rootname] node {
if {[$tree isleaf $node]} {
yield $node
... |
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... | #OCaml | OCaml | let sieve n =
let is_prime = Array.create n true in
let limit = truncate(sqrt (float (n - 1))) in
for i = 2 to limit do
if is_prime.(i) then
let j = ref (i*i) in
while !j < n do
is_prime.(!j) <- false;
j := !j + i;
done
done;
is_prime.(0) <- false;
is_prime.(1) <- false... |
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... | #uBasic.2F4tH | uBasic/4tH | For n = 2 To 7
t = 0
For x = 1 Step 1 While t = 0
t = FUNC(_Total(n,x))
Next
Print n;": ";t;Tab(12); x - 1
Next
End
_Total Param(2)
Local(1)
b@ = b@ * a@
a@ = a@ - 1
For c@ = 0 To a@
If b@ % a@ Then
b@ = 0
Break
EndIf
b@ = b@ + 1 + b@ / a@
Next
Return (b@) |
http://rosettacode.org/wiki/Sailors,_coconuts_and_a_monkey_problem | Sailors, coconuts and a monkey problem | Five sailors are shipwrecked on an island and collect a large pile of coconuts during the day.
That night the first sailor wakes up and decides to take his first share early so tries to divide the pile of coconuts equally into five piles but finds that there is one coconut left over, so he tosses it to a monkey and th... | #VBA | VBA | Option Explicit
Public Sub coconuts()
Dim sailors As Integer
Dim share As Long
Dim finalshare As Integer
Dim minimum As Long, pile As Long
Dim i As Long, j As Integer
Debug.Print "Sailors", "Pile", "Final share"
For sailors = 2 To 6
i = 1
Do While True
pile = i
... |
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... | #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | data = Dataset[{
<|"name" -> "Lagos", "population" -> 21.|>,
<|"name" -> "Cairo", "population" -> 15.2|>,
<|"name" -> "Kinshasa-Brazzaville", "population" -> 11.3|>,
<|"name" -> "Greater Johannesburg", "population" -> 7.55|>,
<|"name" -> "Mogadishu", "population" -> 5.85|>,
<|"name" -> "Khartoum-Omdurm... |
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 ... | #Bracmat | Bracmat | ( return the largest index to a needle that has multiple
occurrences in the haystack and print the needle
: ?list
& ( !list:? haystack [?index ?
& out$("The word 'haystack' occurs at 1-based index" !index)
| out$"The word 'haystack' does not occur"
)
& ( !list
: ? %@?needle ? !needle ?
:... |
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... | #JavaScript | JavaScript |
var foo = eval('{value: 42}');
eval('var bar = "Hello, world!";');
typeof foo; // 'object'
typeof bar; // 'string'
|
http://rosettacode.org/wiki/Runtime_evaluation | Runtime evaluation | Task
Demonstrate a language's ability for programs to execute code written in the language provided at runtime.
Show what kind of program fragments are permitted (e.g. expressions vs. statements), and how to get values in and out (e.g. environments, arguments, return values), if applicable what lexical/static environ... | #Jsish | Jsish | /* Runtime evaluation, in Jsish */
var foo = eval('{value: 42}');
eval('var bar = "Hello, world!";');
;typeof foo;
;foo.value;
;typeof bar;
;bar;
/*
=!EXPECTSTART!=
typeof foo ==> object
foo.value ==> 42
typeof bar ==> string
bar ==> Hello, world!
=!EXPECTEND!=
*/ |
http://rosettacode.org/wiki/Safe_primes_and_unsafe_primes | Safe primes and unsafe primes | Definitions
A safe prime is a prime p and where (p-1)/2 is also prime.
The corresponding prime (p-1)/2 is known as a Sophie Germain prime.
An unsafe prime is a prime p and where (p-1)/2 isn't a prime.
An unsafe prime is a prime that isn't a safe prime.
Task
... | #Perl | Perl | use ntheory qw(forprimes is_prime);
my $upto = 1e7;
my %class = ( safe => [], unsafe => [2] );
forprimes {
push @{$class{ is_prime(($_-1)>>1) ? 'safe' : 'unsafe' }}, $_;
} 3, $upto;
for (['safe', 35], ['unsafe', 40]) {
my($type, $quantity) = @$_;
print "The first $quantity $type primes are:\n";
p... |
http://rosettacode.org/wiki/Runtime_evaluation/In_an_environment | Runtime evaluation/In an environment | x
x
x
Do so in a way which:
does not involve string manipulation of the input source code
is plausibly extensible to a runtime-chosen set of bindings rather than just x
does not make x a global variable
or note that these are impossible.
See also
For more general examples and language-specific details, see... | #AppleScript | AppleScript |
on task_with_x(pgrm, x1, x2)
local rslt1, rslt2
set rslt1 to run script pgrm with parameters {x1}
set rslt2 to run script pgrm with parameters {x2}
rslt2 - rslt1
end task_with_x
|
http://rosettacode.org/wiki/Runtime_evaluation/In_an_environment | Runtime evaluation/In an environment | x
x
x
Do so in a way which:
does not involve string manipulation of the input source code
is plausibly extensible to a runtime-chosen set of bindings rather than just x
does not make x a global variable
or note that these are impossible.
See also
For more general examples and language-specific details, see... | #AutoHotkey | AutoHotkey | msgbox % first := evalWithX("x + 4", 5)
msgbox % second := evalWithX("x + 4", 6)
msgbox % second - first
return
evalWithX(expression, xvalue)
{
global script
script =
(
expression(){
x = %xvalue% ; := would need quotes
return %expression%
}
)
renameFunction("expression", "") ; remove any previous exp... |
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... | #Wren | Wren | import "/dynamic" for Struct
var Node = Struct.create("Node", ["key", "left", "right"])
// 'leaves' returns a fiber that yields the leaves of the tree
// until all leaves have been received.
var leaves = Fn.new { |t|
// recursive function to walk tree
var f
f = Fn.new { |n|
if (!n) return
... |
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... | #Oforth | Oforth | : eratosthenes(n)
| i j |
ListBuffer newSize(n) dup add(null) seqFrom(2, n) over addAll
2 n sqrt asInteger for: i [
dup at(i) ifNotNull: [ i sq n i step: j [ dup put(j, null) ] ]
]
filter(#notNull) ; |
http://rosettacode.org/wiki/Sailors,_coconuts_and_a_monkey_problem | Sailors, coconuts and a monkey problem | Five sailors are shipwrecked on an island and collect a large pile of coconuts during the day.
That night the first sailor wakes up and decides to take his first share early so tries to divide the pile of coconuts equally into five piles but finds that there is one coconut left over, so he tosses it to a monkey and th... | #Wren | Wren | var coconuts = 11
for (ns in 2..9) {
var hidden = List.filled(ns, 0)
coconuts = (coconuts/ns).floor * ns + 1
while (true) {
var nc = coconuts
var outer = false
for (s in 1..ns) {
if (nc%ns == 1) {
hidden[s-1] = (nc/ns).floor
nc = nc - hidde... |
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... | #Nim | Nim | template findIt(data, pred: untyped): int =
## Return the index of the first element in "data" satisfying
## the predicate "pred" or -1 if no such element is found.
var result = -1
for i, it {.inject.} in data.pairs:
if pred:
result = i
break
result
when isMainModule:
import strutils
... |
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 ... | #Burlesque | Burlesque | blsq ) {"Zig" "Zag" "Wally" "Bush" "Ronald" "Bush"}"Bush"Fi
3 |
http://rosettacode.org/wiki/Runtime_evaluation | Runtime evaluation | Task
Demonstrate a language's ability for programs to execute code written in the language provided at runtime.
Show what kind of program fragments are permitted (e.g. expressions vs. statements), and how to get values in and out (e.g. environments, arguments, return values), if applicable what lexical/static environ... | #Julia | Julia | include("myfile.jl") |
http://rosettacode.org/wiki/Runtime_evaluation | Runtime evaluation | Task
Demonstrate a language's ability for programs to execute code written in the language provided at runtime.
Show what kind of program fragments are permitted (e.g. expressions vs. statements), and how to get values in and out (e.g. environments, arguments, return values), if applicable what lexical/static environ... | #Kotlin | Kotlin | $ kotlinc
Welcome to Kotlin version 1.2.31 (JRE 1.8.0_162-8u162-b12-0ubuntu0.16.04.2-b12)
Type :help for help, :quit for quit
>>> 20 + 22
42
>>> 5 * Math.sqrt(81.0)
45.0
>>> fun triple(x: Int) = x * 3
>>> triple(16)
48
>>> :quit
|
http://rosettacode.org/wiki/Runtime_evaluation | Runtime evaluation | Task
Demonstrate a language's ability for programs to execute code written in the language provided at runtime.
Show what kind of program fragments are permitted (e.g. expressions vs. statements), and how to get values in and out (e.g. environments, arguments, return values), if applicable what lexical/static environ... | #Lasso | Lasso | //code, fragment name, autocollect, inplaintext
local(mycode = "'Hello world, it is '+date")
sourcefile('['+#mycode+']','arbritraty_name', true, true)->invoke
'\r'
var(x = 100)
local(mycode = "Outside Lasso\r['Hello world, var x is '+var(x)]")
// autocollect (3rd param): return any output generated
// inplaintext... |
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
... | #Phix | Phix | with javascript_semantics
sequence safe = {}, unsafe = {}
function filter_range(integer lo, hi)
while true do
integer p = get_prime(lo)
if p>hi then return lo end if
if p>2 and is_prime((p-1)/2) then
safe &= p
else
unsafe &= p
end if
lo += 1
... |
http://rosettacode.org/wiki/Runtime_evaluation/In_an_environment | Runtime evaluation/In an environment | x
x
x
Do so in a way which:
does not involve string manipulation of the input source code
is plausibly extensible to a runtime-chosen set of bindings rather than just x
does not make x a global variable
or note that these are impossible.
See also
For more general examples and language-specific details, see... | #BBC_BASIC | BBC BASIC | expression$ = "x^2 - 7"
one = FN_eval_with_x(expression$, 1.2)
two = FN_eval_with_x(expression$, 3.4)
PRINT two - one
END
DEF FN_eval_with_x(expr$, x)
= EVAL(expr$) |
http://rosettacode.org/wiki/Runtime_evaluation/In_an_environment | Runtime evaluation/In an environment | x
x
x
Do so in a way which:
does not involve string manipulation of the input source code
is plausibly extensible to a runtime-chosen set of bindings rather than just x
does not make x a global variable
or note that these are impossible.
See also
For more general examples and language-specific details, see... | #Bracmat | Bracmat | ( ( eval-with-x
= code a b argument
. !arg:((=?code),?a,?b,?argument)
& (!b:?x&!code$!argument)
+ -1*(!a:?x&!code$!argument)
)
& out$(eval-with-x$((='(.$x^!arg)),3,5,2))
& out$(eval-with-x$((='(.$x^!arg)),12,13,2))
); |
http://rosettacode.org/wiki/Runtime_evaluation/In_an_environment | Runtime evaluation/In an environment | x
x
x
Do so in a way which:
does not involve string manipulation of the input source code
is plausibly extensible to a runtime-chosen set of bindings rather than just x
does not make x a global variable
or note that these are impossible.
See also
For more general examples and language-specific details, see... | #Clojure | Clojure | (def ^:dynamic x nil)
(defn eval-with-x [program a b]
(- (binding [x b] (eval program))
(binding [x a] (eval program)))) |
http://rosettacode.org/wiki/Same_fringe | Same fringe | Write a routine that will compare the leaves ("fringe") of two binary trees to determine whether they are the same list of leaves when visited left-to-right. The structure or balance of the trees does not matter; only the number, order, and value of the leaves is important.
Any solution is allowed here, but many compu... | #zkl | zkl | var G=Utils.Generator;
//Tree: (node,left,right) or (leaf) or (node,left) ...
aTree := T(1, T(2, T(4, T(7)), T(5)), T(3, T(6, T(8), T(9))));
bTree := aTree;
println("aTree and bTree ",sameFringe(aTree,bTree) and "have" or "don't have",
" the same leaves.");
cTree := T(1, T(2, T(4, T(7)), T(5)), T(3, T(6, T(8)... |
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... | #Ol | Ol |
(define all (iota 999 2))
(print
(let main ((left '()) (right all))
(if (null? right)
(reverse left)
(unless (car right)
(main left (cdr right))
(let loop ((l '()) (r right) (n 0) (every (car right)))
(if (null? r)
(let ((l (reverse... |
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... | #Yabasic | Yabasic | coconuts = 11
for ns = 2 to 9
dim hidden(ns)
coconuts = int(coconuts / ns) * ns + 1
do
nc = coconuts
for s = 1 to ns+1
if mod(nc, ns) = 1 then
hidden(s-1) = int(nc / ns)
nc = nc - (hidden(s-1) + 1)
if s = ns and not mod(nc, ns) th... |
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... | #zkl | zkl | fcn monkey_coconuts(sailors=5){
nuts,wakes:=sailors,List();
while(True){
n0:=nuts; wakes.clear();
foreach sailor in (sailors + 1){
portion, remainder := n0.divr(sailors);
wakes.append(T(n0, portion, remainder));
if(portion <= 0 or remainder != (sailor != sailors).toInt()){
nuts += 1;... |
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... | #OCaml | OCaml |
#load "str.cma"
(* We are going to use literally a list of records as said in the title of the
* task. *)
(* First: Definition of the record type. *)
type city = {
name : string;
population : float
}
(* Second: The actual list of records containing the data. *)
let cities = [
{ name = "Lagos"; ... |
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 ... | #C | C | #include <stdio.h>
#include <string.h>
const char *haystack[] = {
"Zig", "Zag", "Wally", "Ronald", "Bush", "Krusty", "Charlie",
"Bush", "Boz", "Zag", NULL
};
int search_needle(const char *needle, const char **hs)
{
int i = 0;
while( hs[i] != NULL ) {
if ( strcmp(hs[i], needle) == 0 ) return i;
i++;
... |
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... | #Liberty_BASIC | Liberty BASIC |
'Dimension a numerical and string array
Dim myArray(5)
Dim myStringArray$(5)
'Fill both arrays with the appropriate data
For i = 0 To 5
myArray(i) = i
myStringArray$(i) = "String - " + str$(i)
Next i
'Set two variables with the names of each array
numArrayName$ = "myArray"
strArrayName$ = "myStringArray"
... |
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... | #Lua | Lua | f = loadstring(s) -- load a string as a function. Returns a function.
one = loadstring"return 1" -- one() returns 1
two = loadstring"return ..." -- two() returns the arguments passed to it |
http://rosettacode.org/wiki/Safe_primes_and_unsafe_primes | Safe primes and unsafe primes | Definitions
A safe prime is a prime p and where (p-1)/2 is also prime.
The corresponding prime (p-1)/2 is known as a Sophie Germain prime.
An unsafe prime is a prime p and where (p-1)/2 isn't a prime.
An unsafe prime is a prime that isn't a safe prime.
Task
... | #PureBasic | PureBasic | #MAX=10000000
Global Dim P.b(#MAX) : FillMemory(@P(),#MAX,1,#PB_Byte)
Global NewList Primes.i()
Global NewList SaveP.i()
Global NewList UnSaveP.i()
For n=2 To Sqr(#MAX)+1 : If P(n) : m=n*n : While m<=#MAX : P(m)=0 : m+n : Wend : EndIf : Next
For i=2 To #MAX : If p(i) : AddElement(Primes()) : Primes()=i : EndIf : Next... |
http://rosettacode.org/wiki/Runtime_evaluation/In_an_environment | Runtime evaluation/In an environment | x
x
x
Do so in a way which:
does not involve string manipulation of the input source code
is plausibly extensible to a runtime-chosen set of bindings rather than just x
does not make x a global variable
or note that these are impossible.
See also
For more general examples and language-specific details, see... | #Common_Lisp | Common Lisp | (defun eval-with-x (program a b)
(let ((at-a (eval `(let ((x ',a)) ,program)))
(at-b (eval `(let ((x ',b)) ,program))))
(- at-b at-a))) |
http://rosettacode.org/wiki/Runtime_evaluation/In_an_environment | Runtime evaluation/In an environment | x
x
x
Do so in a way which:
does not involve string manipulation of the input source code
is plausibly extensible to a runtime-chosen set of bindings rather than just x
does not make x a global variable
or note that these are impossible.
See also
For more general examples and language-specific details, see... | #D.C3.A9j.C3.A0_Vu | Déjà Vu | local fib n:
if <= n 1:
n
else:
+ fib - n 1 fib - n 2
local :code !compile-string dup "-- fib x" #one less than the xth fibonacci number
!run-blob-in { :fib @fib :x 4 } code
!run-blob-in { :fib @fib :x 6 } code
!. - |
http://rosettacode.org/wiki/RSA_code | RSA code | Given an RSA key (n,e,d), construct a program to encrypt and decrypt plaintext messages strings.
Background
RSA code is used to encode secret messages. It is named after Ron Rivest, Adi Shamir, and Leonard Adleman who published it at MIT in 1977. The advantage of this type of encryption is that you can distribute the... | #11l | 11l | V n = BigInt(‘9516311845790656153499716760847001433441357’)
V e = BigInt(65537)
V d = BigInt(‘5617843187844953170308463622230283376298685’)
V txt = ‘Rosetta Code’
print(‘Plain text: ’txt)
V txtN = txt.reduce(BigInt(0), (a, b) -> a * 256 + b.code)
print(‘Plain text as a number: ’txtN)
V enc = pow(txt... |
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... | #Oz | Oz | declare
fun {Sieve N}
S = {Array.new 2 N true}
M = {Float.toInt {Sqrt {Int.toFloat N}}}
in
for I in 2..M do
if S.I then
for J in I*I..N;I do
S.J := false
end
end
end
S
end
fun {Primes N}
S = {Sieve N}
in
for I in 2..N collect:C do
if S.I then {C I} end
... |
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... | #Perl | Perl | use feature 'say';
use List::Util qw(first);
my @cities = (
{ name => 'Lagos', population => 21.0 },
{ name => 'Cairo', population => 15.2 },
{ name => 'Kinshasa-Brazzaville', population => 11.3 },
{ name => 'Greater Johannesburg', population => 7.55 },
{ name => 'Mogadishu... |
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 ... | #C.23 | C# | using System;
using System.Collections.Generic;
class Program {
static void Main(string[] args) {
List<string> haystack = new List<string>() { "Zig", "Zag", "Wally", "Ronald", "Bush", "Krusty", "Charlie", "Bush", "Bozo" };
foreach (string needle in new string[] { "Washington", "Bush" }) {
... |
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... | #M2000_Interpreter | M2000 Interpreter |
Module checkit {
Module dummy {
i++
Print Number
}
\\ using Stack New { } we open a new stack for values, and old one connected back at the end
\\ using block For This {} we erase any new definition, so we erase i (which Local make a new one)
a$={
Stac... |
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... | #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | Print[ToExpression["1 + 1"]];
Print[ToExpression["Print[\"Hello, world!\"]; 10!"]];
x = 5;
Print[ToExpression["x!"]];
Print[ToExpression["Module[{x = 8}, x!]"]];
Print[MemoryConstrained[ToExpression["Range[5]"], 10000, {}]];
Print[MemoryConstrained[ToExpression["Range[10^5]"], 10000, {}]];
Print[TimeConstrained[ToExpre... |
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... | #MATLAB | MATLAB | function testEval
fprintf('Expressions:\n')
x = eval('5+10^2')
eval('y = (x-100).*[1 2 3]')
eval('z = strcat(''my'', '' string'')')
try
w eval(' = 45')
catch
fprintf('Runtime error: interpretation of w is a function\n\n')
end
% eval('v') = 5
% Invalid at compile-time ... |
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
... | #Python | Python |
primes =[]
sp =[]
usp=[]
n = 10000000
if 2<n:
primes.append(2)
for i in range(3,n+1,2):
for j in primes:
if(j>i/2) or (j==primes[-1]):
primes.append(i)
if((i-1)/2) in primes:
sp.append(i)
break
else:
usp.append(i)
... |
http://rosettacode.org/wiki/Runtime_evaluation/In_an_environment | Runtime evaluation/In an environment | x
x
x
Do so in a way which:
does not involve string manipulation of the input source code
is plausibly extensible to a runtime-chosen set of bindings rather than just x
does not make x a global variable
or note that these are impossible.
See also
For more general examples and language-specific details, see... | #E | E | # Constructing an environment has to be done by way of evaluation
#for historical reasons which will hopefully be entirely eliminated soon.
def bindX(value) {
def [resolver, env] := e` # bind x and capture its resolver and the
def x # resulting environment
`.evalToPair(safeScope)
resol... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.