code
stringlengths 1
46.1k
⌀ | label
class label 1.18k
classes | domain_label
class label 21
classes | index
stringlengths 4
5
|
---|---|---|---|
fp = io.tmpfile() | 312Secure temporary file
| 1lua
| qjsx0 |
global var1 # used outside of procedures
procedure one() # a global procedure (the only kind)
local var2 # used inside of procedures
static var3 # also used inside of procedures
end | 313Scope modifiers
| 0go
| opo8q |
global var1 # used outside of procedures
procedure one() # a global procedure (the only kind)
local var2 # used inside of procedures
static var3 # also used inside of procedures
end | 313Scope modifiers
| 8haskell
| 2f2ll |
use File::Temp qw(tempfile);
$fh = tempfile();
($fh2, $filename) = tempfile();
print "$filename\n";
close $fh;
close $fh2; | 312Secure temporary file
| 2perl
| 2fvlf |
int twice(int x)
{
return 2 * x;
}
int main(void)
{
int x;
printf();
printf();
printf();
if (scanf(, &x) != 1)
return 0;
switch (x % 2) {
default:
printf();
case 0:
printf();
printf(, sqr(x));
break;
case 1:
printf();
goto sayhello;
jumpin:
printf(, x, twice(x));
printf();
sayhello:
greet;
if (x == -1)
goto scram;
break;
}
printf();
if (x != -1) {
x = -1;
goto jumpin;
}
scram:
printf();
return 0;
} | 314Scope/Function names and labels
| 5c
| 5zvuk |
public | 313Scope modifiers
| 9java
| 6063z |
int valid(int n, int nuts)
{
int k;
for (k = n; k; k--, nuts -= 1 + nuts/n)
if (nuts%n != 1) return 0;
return nuts && !(nuts%n);
}
int main(void)
{
int n, x;
for (n = 2; n < 10; n++) {
for (x = 0; !valid(n, x); x++);
printf(, n, x);
}
return 0;
} | 315Sailors, coconuts and a monkey problem
| 5c
| q7exc |
$fh = tmpfile();
fclose($fh);
$filename = tempnam('/tmp', 'prefix');
echo ; | 312Secure temporary file
| 12php
| sh0qs |
julia> function foo(n)
x = 0
for i = 1:n
local x # introduce a loop-local x
x = i
end
x
end
foo (generic function with 1 method)
julia> foo(10)
0 | 313Scope modifiers
| 10javascript
| ldlcf |
null | 313Scope modifiers
| 11kotlin
| dednz |
>>> import tempfile
>>> invisible = tempfile.TemporaryFile()
>>> invisible.name
'<fdopen>'
>>> visible = tempfile.NamedTemporaryFile()
>>> visible.name
'/tmp/tmpZNfc_s'
>>> visible.close()
>>> invisible.close() | 312Secure temporary file
| 3python
| vtu29 |
package main
import (
"fmt"
"runtime"
"ex"
)
func main() { | 314Scope/Function names and labels
| 0go
| 8ks0g |
add3 :: Int -> Int-> Int-> Int
add3 x y z = add2 x y + z
add2 :: Int -> Int -> Int
add2 x y = x + y
main :: putStrLn(show (add3 5 6 5)) | 314Scope/Function names and labels
| 8haskell
| ln9ch |
null | 314Scope/Function names and labels
| 11kotlin
| n1oij |
function erato(n)
if n < 2 then return {} end
local t = {0} | 309Sieve of Eratosthenes
| 1lua
| hl1j8 |
foo = "global" | 313Scope modifiers
| 1lua
| fwfdp |
(defn solves-for? [sailors initial-coconut-count]
(with-local-vars [coconuts initial-coconut-count, hidings 0]
(while (and (> @coconuts sailors) (= (mod @coconuts sailors) 1)
(var-set coconuts (/ (* (dec @coconuts) (dec sailors)) sailors))
(var-set hidings (inc @hidings)))
(and (zero? (mod @coconuts sailors)) (= @hidings sailors))))
(doseq [sailors (range 5 7)]
(let [start (first (filter (partial solves-for? sailors) (range)))]
(println (str sailors " sailors start with " start " coconuts:"))
(with-local-vars [coconuts start]
(doseq [sailor (range sailors)]
(let [hidden (/ (dec @coconuts) sailors)]
(var-set coconuts (/ (* (dec @coconuts) (dec sailors)) sailors))
(println (str "\tSailor " (inc sailor) " hides " hidden " coconuts and gives 1 to the monkey, leaving " @coconuts "."))))
(println
(str "\tIn the morning, each sailor gets another " (/ @coconuts sailors) " coconuts."))
(println "\tThe monkey gets no more.\n")))) | 315Sailors, coconuts and a monkey problem
| 6clojure
| ip0om |
irb(main):001:0> require 'tempfile'
=> true
irb(main):002:0> f = Tempfile.new('foo')
=>
irb(main):003:0> f.path
=>
irb(main):004:0> f.close
=> nil
irb(main):005:0> f.unlink
=> | 312Secure temporary file
| 14ruby
| 534uj |
function foo() print("global") end | 314Scope/Function names and labels
| 1lua
| dainq |
null | 312Secure temporary file
| 15rust
| 46g5u |
import java.io.{File, FileWriter, IOException}
def writeStringToFile(file: File, data: String, appending: Boolean = false) =
using(new FileWriter(file, appending))(_.write(data))
def using[A <: {def close() : Unit}, B](resource: A)(f: A => B): B =
try f(resource) finally resource.close()
try {
val file = File.createTempFile("_rosetta", ".passwd") | 312Secure temporary file
| 16scala
| 79jr9 |
typedef struct {
ucontext_t caller, callee;
char stack[8192];
void *in, *out;
} co_t;
co_t * co_new(void(*f)(), void *data)
{
co_t * c = malloc(sizeof(*c));
getcontext(&c->callee);
c->in = data;
c->callee.uc_stack.ss_sp = c->stack;
c->callee.uc_stack.ss_size = sizeof(c->stack);
c->callee.uc_link = &c->caller;
makecontext(&c->callee, f, 1, (int)c);
return c;
}
void co_del(co_t *c)
{
free(c);
}
inline void
co_yield(co_t *c, void *data)
{
c->out = data;
swapcontext(&c->callee, &c->caller);
}
inline void *
co_collect(co_t *c)
{
c->out = 0;
swapcontext(&c->caller, &c->callee);
return c->out;
}
typedef struct node node;
struct node {
int v;
node *left, *right;
};
node *newnode(int v)
{
node *n = malloc(sizeof(node));
n->left = n->right = 0;
n->v = v;
return n;
}
void tree_insert(node **root, node *n)
{
while (*root) root = ((*root)->v > n->v)
? &(*root)->left
: &(*root)->right;
*root = n;
}
void tree_trav(int x)
{
co_t *c = (co_t *) x;
void trav(node *root) {
if (!root) return;
trav(root->left);
co_yield(c, root);
trav(root->right);
}
trav(c->in);
}
int tree_eq(node *t1, node *t2)
{
co_t *c1 = co_new(tree_trav, t1);
co_t *c2 = co_new(tree_trav, t2);
node *p = 0, *q = 0;
do {
p = co_collect(c1);
q = co_collect(c2);
} while (p && q && (p->v == q->v));
co_del(c1);
co_del(c2);
return !p && !q;
}
int main()
{
int x[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, -1 };
int y[] = { 2, 5, 7, 1, 9, 0, 6, 4, 8, 3, -1 };
int z[] = { 0, 1, 2, 3, 4, 5, 6, 8, 9, -1 };
node *t1 = 0, *t2 = 0, *t3 = 0;
void mktree(int *buf, node **root) {
int i;
for (i = 0; buf[i] >= 0; i++)
tree_insert(root, newnode(buf[i]));
}
mktree(x, &t1);
mktree(y, &t2);
mktree(z, &t3);
printf(, tree_eq(t1, t2) ? : );
printf(, tree_eq(t1, t3) ? : );
return 0;
} | 316Same fringe
| 5c
| 3qdza |
use strict;
$x = 1;
our $y = 2;
print "$y\n";
package Foo;
our $z = 3;
package Bar;
print "$z\n"; | 313Scope modifiers
| 2perl
| jcj7f |
no warnings 'redefine';
sub logger { print shift . ": Dicitur clamantis in deserto." };
logger('A');
HighLander::logger('B');
package HighLander {
logger('C');
sub logger { print shift . ": I have something to say.\n" };
sub down_one_level {
sub logger { print shift . ": I am a man, not a fish.\n" };
sub down_two_levels {
sub logger { print shift . ": There can be only one!\n" };
}
}
logger('D');
}
logger('E');
sub logger {
print shift . ": This thought intentionally left blank.\n"
}; | 314Scope/Function names and labels
| 2perl
| 7mgrh |
(define (foo x)
(define (bar y) (+ x y))
(bar 2))
(foo 1); => 3
(bar 1); => error | 314Scope/Function names and labels
| 3python
| j9r7p |
struct cd {
char *name;
double population;
};
int search_get_index_by_name(const char *name, const struct cd *data, const size_t data_length,
int (*cmp_func)(const void *, const void *))
{
struct cd key = { (char *) name, 0 };
struct cd *match = bsearch(&key, data, data_length,
sizeof(struct cd), cmp_func);
if (match == NULL)
return -1;
else
return ((intptr_t) match - (intptr_t) data) / sizeof(struct cd);
}
double search_get_pop_by_name(const char *name, const struct cd *data, size_t data_length,
int (*cmp_func)(const void *, const void *))
{
struct cd key = { (char *) name, 0 };
struct cd *match = lfind(&key, data, &data_length,
sizeof(struct cd), cmp_func);
if (match == NULL)
return -1;
else
return match->population;
}
char* search_get_pop_threshold(double pop_threshold, const struct cd *data, size_t data_length,
int (*cmp_func)(const void *, const void *))
{
struct cd key = { NULL, pop_threshold };
struct cd *match = lfind(&key, data, &data_length,
sizeof(struct cd), cmp_func);
if (match == NULL)
return NULL;
else
return match->name;
}
int cd_nameChar_cmp(const void *a, const void *b)
{
struct cd *aa = (struct cd *) a;
struct cd *bb = (struct cd *) b;
int i,len = strlen(aa->name);
for(i=0;i<len;i++)
if(bb->name[i]!=aa->name[i])
return -1;
return 0;
}
int cd_name_cmp(const void *a, const void *b)
{
struct cd *aa = (struct cd *) a;
struct cd *bb = (struct cd *) b;
return strcmp(bb->name, aa->name);
}
int cd_pop_cmp(const void *a, const void *b)
{
struct cd *aa = (struct cd *) a;
struct cd *bb = (struct cd *) b;
return bb->population >= aa->population;
}
int main(void)
{
const struct cd citydata[] = {
{ , 21 },
{ , 15.2 },
{ , 11.3 },
{ , 7.55 },
{ , 5.85 },
{ , 4.98 },
{ , 4.7 },
{ , 4.58 },
{ , 4.4 },
{ , 3.98 }
};
const size_t citydata_length = LEN(citydata);
printf(, search_get_index_by_name(, citydata, citydata_length, cd_name_cmp));
printf(, search_get_pop_threshold(5, citydata, citydata_length, cd_pop_cmp));
printf(, search_get_pop_by_name(, citydata, citydata_length, cd_nameChar_cmp));
return 0;
} | 317Search a list of records
| 5c
| ryvg7 |
package main
import "fmt"
func main() {
coconuts := 11
outer:
for ns := 2; ns < 10; ns++ {
hidden := make([]int, ns)
coconuts = (coconuts/ns)*ns + 1
for {
nc := coconuts
for s := 1; s <= ns; s++ {
if nc%ns == 1 {
hidden[s-1] = nc / ns
nc -= hidden[s-1] + 1
if s == ns && nc%ns == 0 {
fmt.Println(ns, "sailors require a minimum of", coconuts, "coconuts")
for t := 1; t <= ns; t++ {
fmt.Println("\tSailor", t, "hides", hidden[t-1])
}
fmt.Println("\tThe monkey gets", ns)
fmt.Println("\tFinally, each sailor takes", nc/ns, "\b\n")
continue outer
}
} else {
break
}
}
coconuts += ns
}
}
} | 315Sailors, coconuts and a monkey problem
| 0go
| 2d9l7 |
def welcome(name)
puts
end
puts
$name = STDIN.gets
welcome($name)
return | 314Scope/Function names and labels
| 14ruby
| kljhg |
(defn fringe-seq [branch? children content tree]
(letfn [(walk [node]
(lazy-seq
(if (branch? node)
(if (empty? (children node))
(list (content node))
(mapcat walk (children node)))
(list node))))]
(walk tree))) | 316Same fringe
| 6clojure
| ci69b |
>>> x=
>>> def outerfunc():
x =
def scoped_local():
x =
return + x
print(scoped_local())
def scoped_nonlocal():
nonlocal x
return + x
print(scoped_nonlocal())
def scoped_global():
global x
return + x
print(scoped_global())
def scoped_notdefinedlocally():
return + x
print(scoped_notdefinedlocally())
>>> outerfunc()
scoped_local scope gives x = scope local
scoped_nonlocal scope gives x = From scope at outerfunc
scoped_global scope gives x = From global scope
scoped_notdefinedlocally scope gives x = From global scope
>>> | 313Scope modifiers
| 3python
| hlhjw |
X <- "global x"
f <- function() {
x <- "local x"
print(x)
}
f()
print(x) | 313Scope modifiers
| 13r
| gyg47 |
import Control.Monad ((>=>))
import Data.Maybe (mapMaybe)
import System.Environment (getArgs)
tryFor :: Int -> Int -> Maybe Int
tryFor s = foldr (>=>) pure $ replicate s step
where
step n
| n `mod` (s - 1) == 0 = Just $ n * s `div` (s - 1) + 1
| otherwise = Nothing
main :: IO ()
main = do
args <- getArgs
let n =
case args of
[] -> 5
s:_ -> read s
a = head . mapMaybe (tryFor n) $ [n,2 * n ..]
print a | 315Sailors, coconuts and a monkey problem
| 8haskell
| a5b1g |
object ScopeFunction extends App {
val c = new C()
val d = new D()
val n = 1
def a() = println("calling a")
trait E {
def m() = println("calling m")
}
a() | 314Scope/Function names and labels
| 16scala
| a5p1n |
void
safe_add(volatile double interval[2], volatile double a, volatile double b)
{
unsigned int orig;
orig = fegetround();
fesetround(FE_DOWNWARD);
interval[0] = a + b;
fesetround(FE_UPWARD);
interval[1] = a + b;
fesetround(orig);
}
int
main()
{
const double nums[][2] = {
{1, 2},
{0.1, 0.2},
{1e100, 1e-100},
{1e308, 1e308},
};
double ival[2];
int i;
for (i = 0; i < sizeof(nums) / sizeof(nums[0]); i++) {
safe_add(ival, nums[i][0], nums[i][1]);
printf(, nums[i][0], nums[i][1]);
printf(, ival[0], ival[1]);
printf(, ival[1] - ival[0]);
}
return 0;
} | 318Safe addition
| 5c
| 8ke04 |
public class Test {
static boolean valid(int n, int nuts) {
for (int k = n; k != 0; k--, nuts -= 1 + nuts / n)
if (nuts % n != 1)
return false;
return nuts != 0 && (nuts % n == 0);
}
public static void main(String[] args) {
int x = 0;
for (int n = 2; n < 10; n++) {
while (!valid(n, x))
x++;
System.out.printf("%d:%d%n", n, x);
}
}
} | 315Sailors, coconuts and a monkey problem
| 9java
| j9g7c |
(def records [{:idx 8,:name "Abidjan", :population 4.4}
{:idx 7,:name "Alexandria", :population 4.58}
{:idx 1,:name "Cairo", :population 15.2}
{:idx 9,:name "Casablanca", :population 3.98}
{:idx 6,:name "Dar Es Salaam", :population 4.7}
{:idx 3,:name "Greater Johannesburg",:population 7.55}
{:idx 5,:name "Khartoum-Omdurman", :population 4.98}
{:idx 2,:name "Kinshasa-Brazzaville",:population 11.3}
{:idx 0,:name "Lagos", :population 21.0}
{:idx 4,:name "Mogadishu", :population 5.85}])
(defn city->idx [recs city]
(-> (some #(when (= city (:name %)) %)
recs)
:idx))
(defn rec-with-max-population-below-n [recs limit]
(->> (sort-by:population > recs)
(drop-while (fn [r] (>= (:population r) limit)))
first))
(defn most-populous-city-below-n [recs limit]
(:name (rec-with-max-population-below-n recs limit))) | 317Search a list of records
| 6clojure
| b2rkz |
package main
import "fmt"
type node struct {
int
left, right *node
} | 316Same fringe
| 0go
| b27kh |
class Demo
protected
private
end | 313Scope modifiers
| 14ruby
| bvbkq |
set globalVar "This is a global variable"
namespace eval nsA {
variable varInA "This is a variable in nsA"
}
namespace eval nsB {
variable varInB "This is a variable in nsB"
proc showOff {varname} {
set localVar "This is a local variable"
global globalVar
variable varInB
namespace upvar::nsA varInA varInA
puts "variable $varname holds \"[set $varname]\""
}
}
nsB::showOff globalVar
nsB::showOff varInA
nsB::showOff varInB
nsB::showOff localVar | 313Scope modifiers
| 16scala
| egeab |
(function () { | 315Sailors, coconuts and a monkey problem
| 10javascript
| 1ukp7 |
data Tree a
= Leaf a
| Node (Tree a)
(Tree a)
deriving (Show, Eq)
fringe :: Tree a -> [a]
fringe (Leaf x) = [x]
fringe (Node n1 n2) = fringe n1 ++ fringe n2
sameFringe
:: (Eq a)
=> Tree a -> Tree a -> Bool
sameFringe t1 t2 = fringe t1 == fringe t2
main :: IO ()
main = do
let a = Node (Leaf 1) (Node (Leaf 2) (Node (Leaf 3) (Node (Leaf 4) (Leaf 5))))
b = Node (Leaf 1) (Node (Node (Leaf 2) (Leaf 3)) (Node (Leaf 4) (Leaf 5)))
c = Node (Node (Node (Node (Leaf 1) (Leaf 2)) (Leaf 3)) (Leaf 4)) (Leaf 5)
x =
Node
(Leaf 1)
(Node
(Leaf 2)
(Node (Leaf 3) (Node (Leaf 4) (Node (Leaf 5) (Leaf 6)))))
y = Node (Leaf 0) (Node (Node (Leaf 2) (Leaf 3)) (Node (Leaf 4) (Leaf 5)))
z = Node (Leaf 1) (Node (Leaf 2) (Node (Node (Leaf 4) (Leaf 3)) (Leaf 5)))
mapM_ print $ sameFringe a <$> [a, b, c, x, y, z] | 316Same fringe
| 8haskell
| da8n4 |
package main
import (
"fmt"
"math"
) | 318Safe addition
| 0go
| 5z9ul |
int primes[] = {
2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97,
101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199,
211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311, 313, 317, 331
};
bool isPrime(int n) {
int i;
if (n < 2) {
return false;
}
for (i = 0; i < PCOUNT; i++) {
if (n == primes[i]) {
return true;
}
if (n % primes[i] == 0) {
return false;
}
if (n < primes[i] * primes[i]) {
return true;
}
}
for (i = primes[PCOUNT - 1] + 2; i * i <= n; i += 2) {
if (n % i == 0) {
return false;
}
}
return true;
}
int main() {
int beg, end;
int i, count;
beg = 2;
end = 1000000;
count = 0;
printf();
for (i = beg; i < end; i++) {
if (isPrime(i) && isPrime((i - 1) / 2)) {
if (count < 35) {
printf(, i);
}
count++;
}
}
printf(, count, end);
beg = end;
end = end * 10;
for (i = beg; i < end; i++) {
if (isPrime(i) && isPrime((i - 1) / 2)) {
count++;
}
}
printf(, count, end);
beg = 2;
end = 1000000;
count = 0;
printf();
for (i = beg; i < end; i++) {
if (isPrime(i) && !isPrime((i - 1) / 2)) {
if (count < 40) {
printf(, i);
}
count++;
}
}
printf(, count, end);
beg = end;
end = end * 10;
for (i = beg; i < end; i++) {
if (isPrime(i) && !isPrime((i - 1) / 2)) {
count++;
}
}
printf(, count, end);
return 0;
} | 319Safe primes and unsafe primes
| 5c
| sjpq5 |
null | 315Sailors, coconuts and a monkey problem
| 11kotlin
| 5z2ua |
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[]{stepDown(a + b), stepUp(a + b)};
}
public static void main(String[] args) {
double a = 1.2;
double b = 0.03;
double[] result = safeAdd(a, b);
System.out.printf("(%.2f +%.2f) is in the range%.16f..%.16f", a, b, result[0], result[1]);
}
} | 318Safe addition
| 9java
| b2gk3 |
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 SimpleNode<T> left;
public SimpleNode<T> right;
public SimpleNode(T data)
{ this(data, null, null); }
public SimpleNode(T data, SimpleNode<T> left, SimpleNode<T> right)
{
this.data = data;
this.left = left;
this.right = right;
}
public Node<T> getLeft()
{ return left; }
public Node<T> getRight()
{ return right; }
public boolean isLeaf()
{ return ((left == null) && (right == null)); }
public T getData()
{ return data; }
public SimpleNode<T> addToTree(T data)
{
int cmp = data.compareTo(this.data);
if (cmp == 0)
throw new IllegalArgumentException("Same data!");
if (cmp < 0)
{
if (left == null)
return (left = new SimpleNode<T>(data));
return left.addToTree(data);
}
if (right == null)
return (right = new SimpleNode<T>(data));
return right.addToTree(data);
}
}
public static <T extends Comparable<? super T>> boolean areLeavesSame(Node<T> node1, Node<T> node2)
{
Stack<Node<T>> stack1 = new Stack<Node<T>>();
Stack<Node<T>> stack2 = new Stack<Node<T>>();
stack1.push(node1);
stack2.push(node2); | 316Same fringe
| 9java
| sjeq0 |
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) do
x = x + 1
end
print(n..": "..x)
end | 315Sailors, coconuts and a monkey problem
| 1lua
| 43v5c |
null | 318Safe addition
| 11kotlin
| ry2go |
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); | 318Safe addition
| 2perl
| dasnw |
local type, insert, remove = type, table.insert, table.remove
None = {} | 316Same fringe
| 1lua
| e4bac |
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
factors2 := []int{2}
factors3 := []int{3}
var sum1, sum2, sum3 int = 0, 2, 3
var countF, countD, countT int
for n := 2; countT < 1 || countD < 30 || countF < 30; n++ {
factors1 = factors2
factors2 = factors3
factors3 = rcu.PrimeFactors(n + 2)
sum1 = sum2
sum2 = sum3
sum3 = rcu.SumInts(factors3)
if countF < 30 && sum1 == sum2 {
resF = append(resF, n)
countF++
}
if sum1 == sum2 && sum2 == sum3 {
resT = append(resT, n)
countT++
}
if countD < 30 {
factors4 := make([]int, len(factors1))
copy(factors4, factors1)
factors5 := make([]int, len(factors2))
copy(factors5, factors2)
factors4 = prune(factors4)
factors5 = prune(factors5)
if rcu.SumInts(factors4) == rcu.SumInts(factors5) {
resD = append(resD, n)
countD++
}
}
}
fmt.Println("First 30 Ruth-Aaron numbers (factors):")
fmt.Println(resF)
fmt.Println("\nFirst 30 Ruth-Aaron numbers (divisors):")
fmt.Println(resD)
fmt.Println("\nFirst Ruth-Aaron triple (factors):")
fmt.Println(resT[0])
resT = resT[:0]
factors1 = factors1[:0]
factors2 = factors2[:1]
factors2[0] = 2
factors3 = factors3[:1]
factors3[0] = 3
countT = 0
for n := 2; countT < 1; n++ {
factors1 = factors2
factors2 = factors3
factors3 = prune(rcu.PrimeFactors(n + 2))
sum1 = sum2
sum2 = sum3
sum3 = rcu.SumInts(factors3)
if sum1 == sum2 && sum2 == sum3 {
resT = append(resT, n)
countT++
}
}
fmt.Println("\nFirst Ruth-Aaron triple (divisors):")
fmt.Println(resT[0])
} | 320Ruth-Aaron numbers
| 0go
| 43m52 |
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;
$nuts -= (1 + int $nuts/$sailors);
}
push @shares, int $nuts/$sailors;
return @shares if !($nuts % $sailors);
}
sub check {
my($sailors, $coconuts) = @_;
my @suffix = ('th', 'st', 'nd', 'rd', ('th') x 6, ('th') x 10);
my @piles = is_valid($sailors, $coconuts);
if (@piles) {
print "\nSailors $sailors: Coconuts $coconuts:\n";
for my $k (0..-1 + $
print $k+1 . $suffix[$k+1] . " takes " . $piles[$k] . ", gives 1 to the monkey.\n"
}
print "The next morning, each sailor takes " . $piles[-1] . "\nwith none left over for the monkey.\n";
return 1
}
return 0
}
sub coconuts {
my($sailors) = @_;
if ($sailors % 2 == 0 ) { ($sailors ** $sailors - 1) * ($sailors - 1) }
else { $sailors ** $sailors - $sailors + 1 }
} | 315Sailors, coconuts and a monkey problem
| 2perl
| obs8x |
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},
{"Dar Es Salaam", 4.7},
{"Alexandria", 4.58},
{"Abidjan", 4.4},
{"Casablanca", 3.98},
}
func find(cond func(*element) bool) int {
for i := range list {
if cond(&list[i]) {
return i
}
}
return -1
}
func main() {
fmt.Println(find(func(e *element) bool {
return e.name == "Dar Es Salaam"
}))
i := find(func(e *element) bool {
return e.population < 5
})
if i < 0 {
fmt.Println("*** not found ***")
} else {
fmt.Println(list[i].name)
}
i = find(func(e *element) bool {
return strings.HasPrefix(e.name, "A")
})
if i < 0 {
fmt.Println("*** not found ***")
} else {
fmt.Println(list[i].population)
}
} | 317Search a list of records
| 0go
| n1si1 |
>>> 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 | 318Safe addition
| 3python
| fe0de |
import qualified Data.Set as S
import Data.List.Split ( chunksOf )
divisors :: Int -> [Int]
divisors n = [d | d <- [2 .. n] , mod n d == 0]
primeFactors :: Int -> [Int]
primeFactors n = snd $ until ( (== 1) . fst ) step (n , [] )
where
step :: (Int , [Int] ) -> (Int , [Int] )
step (n , li) = ( div n h , li ++ [h] )
where
h :: Int
h = head $ divisors n
primeDivisors :: Int -> [Int]
primeDivisors n = S.toList $ S.fromList $ primeFactors n
solution :: (Int -> [Int] ) -> [Int]
solution f = snd $ until ( (== 30 ) . length . snd ) step ([2 , 3] , [] )
where
step :: ([Int] , [Int] ) -> ([Int] , [Int])
step ( neighbours , ranums ) = ( map ( + 1 ) neighbours , if (sum $ f
$ head neighbours ) == (sum $ f $ last neighbours) then
ranums ++ [ head neighbours ] else ranums )
formatNumber :: Int -> String -> String
formatNumber width num
|width > l = replicate ( width -l ) ' ' ++ num
|width == l = num
|width < l = num
where
l = length num
main :: IO ( )
main = do
let ruth_aaron_pairs = solution primeFactors
maxlen = length $ show $ last ruth_aaron_pairs
numberlines = chunksOf 8 $ map show ruth_aaron_pairs
ruth_aaron_divisors = solution primeDivisors
maxlen2 = length $ show $ last ruth_aaron_divisors
numberlines2 = chunksOf 8 $ map show ruth_aaron_divisors
putStrLn "First 30 Ruth-Aaaron numbers ( factors ):"
mapM_ (\nlin -> putStrLn $ foldl1 ( ++ ) $ map (\st -> formatNumber (maxlen + 2) st )
nlin ) numberlines
putStrLn " "
putStrLn "First 30 Ruth-Aaron numbers( divisors ):"
mapM_ (\nlin -> putStrLn $ foldl1 ( ++ ) $ map (\st -> formatNumber (maxlen2 + 2) st )
nlin ) numberlines2 | 320Ruth-Aaron numbers
| 8haskell
| q7kx9 |
import Data.List (findIndex, find)
data City = City
{ name :: String
, population :: Float
} deriving (Read, Show)
cityName :: City -> String
cityName (City x _) = x
cityPop :: City -> Float
cityPop (City _ x) = x
mbCityName :: Maybe City -> Maybe String
mbCityName (Just x) = Just (cityName x)
mbCityName _ = Nothing
mbCityPop :: Maybe City -> Maybe Float
mbCityPop (Just x) = Just (cityPop x)
mbCityPop _ = Nothing
mets :: [City]
mets =
[ City
{ name = "Lagos"
, population = 21.0
}
, City
{ name = "Cairo"
, population = 15.2
}
, City
{ name = "Kinshasa-Brazzaville"
, population = 11.3
}
, City
{ name = "Greater Johannesburg"
, population = 7.55
}
, City
{ name = "Mogadishu"
, population = 5.85
}
, City
{ name = "Khartoum-Omdurman"
, population = 4.98
}
, City
{ name = "Dar Es Salaam"
, population = 4.7
}
, City
{ name = "Alexandria"
, population = 4.58
}
, City
{ name = "Abidjan"
, population = 4.4
}
, City
{ name = "Casablanca"
, population = 3.98
}
]
main :: IO ()
main = do
mbPrint $ findIndex (("Dar Es Salaam" ==) . cityName) mets
mbPrint $ mbCityName $ find ((< 5.0) . cityPop) mets
mbPrint $ mbCityPop $ find (("A" ==) . take 1 . cityName) mets
mbPrint
:: Show a
=> Maybe a -> IO ()
mbPrint (Just x) = print x
mbPrint x = print x | 317Search a list of records
| 8haskell
| ut9v2 |
package main
import "fmt"
func sieve(limit uint64) []bool {
limit++ | 319Safe primes and unsafe primes
| 0go
| vf62m |
use strict;
my @trees = (
[ 'd', [ 'c', [ 'a', 'b', ], ], ],
[ [ 'd', 'c' ], [ 'a', 'b' ] ],
[ [ [ 'd', 'c', ], 'a', ], 'b', ],
[ [ [ [ [ [ 'a' ], 'b' ], 'c', ], 'd', ], 'e', ], 'f' ],
);
for my $tree_idx (1 .. $
print "tree[",$tree_idx-1,"] vs tree[$tree_idx]: ",
cmp_fringe($trees[$tree_idx-1], $trees[$tree_idx]), "\n";
}
sub cmp_fringe {
my $ti1 = get_tree_iterator(shift);
my $ti2 = get_tree_iterator(shift);
while (1) {
my ($L, $R) = ($ti1->(), $ti2->());
next if defined($L) and defined($R) and $L eq $R;
return "Same" if !defined($L) and !defined($R);
return "Different";
}
}
sub get_tree_iterator {
my @rtrees = (shift);
my $tree;
return sub {
$tree = pop @rtrees;
($tree, $rtrees[@rtrees]) = @$tree while ref $tree;
return $tree;
}
} | 316Same fringe
| 2perl
| 9o3mn |
def monkey_coconuts(sailors=5):
nuts = sailors
while True:
n0, wakes = nuts, []
for sailor in range(sailors + 1):
portion, remainder = divmod(n0, sailors)
wakes.append((n0, portion, remainder))
if portion <= 0 or remainder != (1 if sailor != sailors else 0):
nuts += 1
break
n0 = n0 - portion - remainder
else:
break
return nuts, wakes
if __name__ == :
for sailors in [5, 6]:
nuts, wake_stats = monkey_coconuts(sailors)
print(% (sailors, nuts))
print(,
',\n '.join(repr(ws) for ws in wake_stats)) | 315Sailors, coconuts and a monkey problem
| 3python
| ip0of |
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.function.Consumer;
import java.util.function.Predicate;
class City implements Comparable<City> {
private final String name;
private final double population;
City(String name, double population) {
this.name = name;
this.population = population;
}
public String getName() {
return this.name;
}
public double getPopulation() {
return this.population;
}
@Override
public int compareTo(City o) { | 317Search a list of records
| 9java
| m8tym |
require 'bigdecimal'
require 'bigdecimal/util'
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)
BigDecimal.mode(rm, orig)
low..high
end
[[, ],
[, ],
[, ],
[, ],
].each { |a, b| puts } | 318Safe addition
| 14ruby
| zxotw |
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"($a%.2f + $b%.2f) is in the range ${result.head}%.16f .. ${result.last}%.16f")
} | 318Safe addition
| 16scala
| m8fyc |
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 (<10000000) safe)
printf "First 40 unsafe primes:%s\n" (show $ take 40 unsafe)
printf "There are%d unsafe primes below 100,000.\n" (length $ takeWhile (<1000000) unsafe)
printf "There are%d unsafe primes below 10,000,000.\n\n" (length $ takeWhile (<10000000) unsafe)
where safe = filter (\n -> isPrime ((n-1) `div` 2)) primes
unsafe = filter (\n -> not (isPrime((n-1) `div` 2))) primes | 319Safe primes and unsafe primes
| 8haskell
| e4jai |
coconutsProblem <- function(sailorCount)
{
stopifnot(sailorCount > 1)
initalCoconutCount <- sailorCount
repeat
{
initalCoconutCount <- initalCoconutCount + 1
coconutCount <- initalCoconutCount
for(i in seq_len(sailorCount))
{
if(coconutCount %% sailorCount != 1) break
coconutCount <- (coconutCount - 1) * (sailorCount - 1)/sailorCount
if(i == sailorCount && coconutCount > 0 && coconutCount %% sailorCount == 0) return(initalCoconutCount)
}
}
}
print(data.frame("Sailors" = 2:8, "Coconuts" = sapply(2:8, coconutsProblem))) | 315Sailors, coconuts and a monkey problem
| 13r
| sjwqy |
(function () {
'use strict'; | 317Search a list of records
| 10javascript
| vfm25 |
let a = 1.2
let b = 0.03
print("\(a) + \(b) is in the range \((a + b).nextDown)...\((a + b).nextUp)") | 318Safe addition
| 17swift
| tw8fl |
use strict;
use warnings;
use ntheory qw( factor vecsum );
use List::AllUtils qw( uniq );
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" =~ s/.{60}\K /\n/gr;
$n = 1;
@answers = ();
while( @answers < 30 )
{
vecsum(uniq factor($n)) == vecsum(uniq factor($n+1)) and push @answers, $n;
$n++;
}
print "divisors:\n\n@answers\n" =~ s/.{60}\K /\n/gr; | 320Ruth-Aaron numbers
| 2perl
| feqd7 |
public class SafePrimes {
public static void main(String... args) { | 319Safe primes and unsafe primes
| 9java
| hcujm |
try:
from itertools import zip_longest as izip_longest
except:
from itertools import izip_longest
def fringe(tree):
for node1 in tree:
if isinstance(node1, tuple):
for node2 in fringe(node1):
yield node2
else:
yield node1
def same_fringe(tree1, tree2):
return all(node1 == node2 for node1, node2 in
izip_longest(fringe(tree1), fringe(tree2)))
if __name__ == '__main__':
a = 1, 2, 3, 4, 5, 6, 7, 8
b = 1, (( 2, 3 ), (4, (5, ((6, 7), 8))))
c = (((1, 2), 3), 4), 5, 6, 7, 8
x = 1, 2, 3, 4, 5, 6, 7, 8, 9
y = 0, 2, 3, 4, 5, 6, 7, 8
z = 1, 2, (4, 3), 5, 6, 7, 8
assert same_fringe(a, a)
assert same_fringe(a, b)
assert same_fringe(a, c)
assert not same_fringe(a, x)
assert not same_fringe(a, y)
assert not same_fringe(a, z) | 316Same fringe
| 3python
| ci69q |
null | 317Search a list of records
| 11kotlin
| twof0 |
null | 319Safe primes and unsafe primes
| 11kotlin
| 43957 |
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
(sailor+1).times do
div, mod = n.divmod(sailor)
puts
n -= 1 + div
end
end | 315Sailors, coconuts and a monkey problem
| 14ruby
| daons |
object Sailors extends App {
var x = 0
private def valid(n: Int, _nuts: Int): Boolean = {
var nuts = _nuts
for (k <- n until 0 by -1) {
if (nuts % n != 1) return false
nuts -= 1 + nuts / n
}
nuts != 0 && (nuts % n == 0)
}
for (nSailors <- 2 until 10) {
while (!valid(nSailors, x)) x += 1
println(f"$nSailors%d: $x%d")
}
} | 315Sailors, coconuts and a monkey problem
| 16scala
| 3qfzy |
package main
import (
"fmt"
"bitbucket.org/binet/go-eval/pkg/eval"
"go/token"
)
func main() {
w := eval.NewWorld();
fset := token.NewFileSet();
code, err := w.Compile(fset, "1 + 2")
if err != nil {
fmt.Println("Compile error");
return
}
val, err := code.Run();
if err != nil {
fmt.Println("Run time error");
return;
}
fmt.Println("Return value:", val) | 321Runtime evaluation
| 0go
| y0o64 |
[2011, 2016, 2022, 2033, 2039, 2044, 2050, 2061, 2067, 2072, 2078, 2089, 2095, 2101, 2107, 2112, 2118] | 321Runtime evaluation
| 7groovy
| fexdn |
null | 319Safe primes and unsafe primes
| 1lua
| g6c4j |
null | 317Search a list of records
| 1lua
| zxity |
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.lang.reflect.InvocationTargetException;
import java.net.URI;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import javax.tools.FileObject;
import javax.tools.ForwardingJavaFileManager;
import javax.tools.JavaCompiler;
import javax.tools.JavaFileObject;
import javax.tools.SimpleJavaFileObject;
import javax.tools.StandardJavaFileManager;
import javax.tools.StandardLocation;
import javax.tools.ToolProvider;
public class Evaluator{
public static void main(String[] args){
new Evaluator().eval(
"SayHello",
"public class SayHello{public void speak(){System.out.println(\"Hello world\");}}",
"speak"
);
}
void eval(String className, String classCode, String methodName){
Map<String, ByteArrayOutputStream> classCache = new HashMap<>();
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
if ( null == compiler )
throw new RuntimeException("Could not get a compiler.");
StandardJavaFileManager sfm = compiler.getStandardFileManager(null, null, null);
ForwardingJavaFileManager<StandardJavaFileManager> fjfm = new ForwardingJavaFileManager<StandardJavaFileManager>(sfm){
@Override
public JavaFileObject getJavaFileForOutput(Location location, String className, JavaFileObject.Kind kind, FileObject sibling)
throws IOException{
if (StandardLocation.CLASS_OUTPUT == location && JavaFileObject.Kind.CLASS == kind)
return new SimpleJavaFileObject(URI.create("mem: | 321Runtime evaluation
| 9java
| 5z6uf |
var foo = eval('{value: 42}');
eval('var bar = "Hello, world!";');
typeof foo; | 321Runtime evaluation
| 10javascript
| j9l7n |
use ntheory qw(forprimes is_prime);
my $upto = 1e7;
my %class = ( safe => [], unsafe => [2] );
forprimes {
push @{$class{ is_prime(($_-1)>>1) ? 'safe' : 'unsafe' }}, $_;
} 3, $upto;
for (['safe', 35], ['unsafe', 40]) {
my($type, $quantity) = @$_;
print "The first $quantity $type primes are:\n";
print join(" ", map { comma($class{$type}->[$_-1]) } 1..$quantity), "\n";
for my $q ($upto/10, $upto) {
my $n = scalar(grep { $_ <= $q } @{$class{$type}});
printf "The number of $type primes up to%s:%s\n", comma($q), comma($n);
}
}
sub comma {
(my $s = reverse shift) =~ s/(.{3})/$1,/g;
$s =~ s/,(-?)$/$1/;
$s = reverse $s;
} | 319Safe primes and unsafe primes
| 2perl
| ipwo3 |
$ 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 | 321Runtime evaluation
| 11kotlin
| cid98 |
(def ^:dynamic x nil)
(defn eval-with-x [program a b]
(- (binding [x b] (eval program))
(binding [x a] (eval program)))) | 322Runtime evaluation/In an environment
| 6clojure
| m8oyq |
const char *haystack[] = {
, , , , , , ,
, , , NULL
};
int search_needle(const char *needle, const char **hs)
{
int i = 0;
while( hs[i] != NULL ) {
if ( strcmp(hs[i], needle) == 0 ) return i;
i++;
}
return -1;
}
int search_last_needle(const char *needle, const char **hs)
{
int i, last=0;
i = last = search_needle(needle, hs);
if ( last < 0 ) return -1;
while( hs[++i] != NULL ) {
if ( strcmp(needle, hs[i]) == 0 ) {
last = i;
}
}
return last;
}
int main()
{
printf(, search_needle(, haystack));
if ( search_needle(, haystack) == -1 )
printf();
printf(, search_needle(, haystack));
printf(, search_last_needle(, haystack));
return 0;
} | 323Search a list
| 5c
| 2ddlo |
f = loadstring(s) | 321Runtime evaluation
| 1lua
| lnfck |
use feature 'say';
use List::Util qw(first);
my @cities = (
{ name => 'Lagos', population => 21.0 },
{ name => 'Cairo', population => 15.2 },
{ name => 'Kinshasa-Brazzaville', population => 11.3 },
{ name => 'Greater Johannesburg', population => 7.55 },
{ name => 'Mogadishu', population => 5.85 },
{ name => 'Khartoum-Omdurman', population => 4.98 },
{ name => 'Dar Es Salaam', population => 4.7 },
{ name => 'Alexandria', population => 4.58 },
{ name => 'Abidjan', population => 4.4 },
{ name => 'Casablanca', population => 3.98 },
);
my $index1 = first { $cities[$_]{name} eq 'Dar Es Salaam' } 0..$
say $index1;
my $record2 = first { $_->{population} < 5 } @cities;
say $record2->{name};
my $record3 = first { $_->{name} =~ /^A/ } @cities;
say $record3->{population}; | 317Search a list of records
| 2perl
| klghc |
primes =[]
sp =[]
usp=[]
n = 10000000
if 2<n:
primes.append(2)
for i in range(3,n+1,2):
for j in primes:
if(j>i/2) or (j==primes[-1]):
primes.append(i)
if((i-1)/2) in primes:
sp.append(i)
break
else:
usp.append(i)
break
if (i%j==0):
break
print('First 35 safe primes are:\n' , sp[:35])
print('There are '+str(len(sp[:1000000]))+' safe primes below 1,000,000')
print('There are '+str(len(sp))+' safe primes below 10,000,000')
print('First 40 unsafe primes:\n',usp[:40])
print('There are '+str(len(usp[:1000000]))+' unsafe primes below 1,000,000')
print('There are '+str(len(usp))+' safe primes below 10,000,000') | 319Safe primes and unsafe primes
| 3python
| n1xiz |
<?php
$data_array = [
['name' => 'Lagos', 'population' => 21.0],
['name' => 'Cairo', 'population' => 15.2],
['name' => 'Kinshasa-Brazzaville', 'population' => 11.3],
['name' => 'Greater Johannesburg', 'population' => 7.55],
['name' => 'Mogadishu', 'population' => 5.85],
['name' => 'Khartoum-Omdurman', 'population' => 4.98],
['name' => 'Dar Es Salaam', 'population' => 4.7],
['name' => 'Alexandria', 'population' => 4.58],
['name' => 'Abidjan', 'population' => 4.4],
['name' => 'Casablanca', 'population' => 3.98],
];
$found=0;
$search_name = 'Dar Es Salaam';
echo $search_name\;
$index = array_search($search_name, array_column($data_array, 'name'));
$population = $data_array[$index]['population'];
echo ;
$search_val = 5;
echo ;
foreach ($data_array as $index => $row) {
if ($row['population'] < $search_val) {
$name = $row['name'];
echo ;
break;
}
}
$search_term = 'A';
echo $search_term\;
foreach ($data_array as $index => $row) {
if (strpos($row['name'], $search_term) === 0) {
echo ;
break;
}
}
echo ;
Output:
Find the (zero-based) index of the first city in the list whose name is - 6
Answer 1: Index: [6] Population for Dar Es Salaam is 4.7 Million
Find the name of the first city in this list whose population is less than 5 million - Khartoum-Omdurman
Answer 2: Index [5] Population for Khartoum-Omdurman is 4.98 Million
Find the population of the first city in this list whose name starts with the letter - 4.58
Answer 3: Index: [7] Population for Alexandria is 4.58 Million
Done... | 317Search a list of records
| 12php
| 3qnzq |
int main(void)
{
mpz_t n, d, e, pt, ct;
mpz_init(pt);
mpz_init(ct);
mpz_init_set_str(n, , 10);
mpz_init_set_str(e, , 10);
mpz_init_set_str(d, , 10);
const char *plaintext = ;
mpz_import(pt, strlen(plaintext), 1, 1, 0, 0, plaintext);
if (mpz_cmp(pt, n) > 0)
abort();
mpz_powm(ct, pt, e, n);
gmp_printf(, ct);
mpz_powm(pt, ct, d, n);
gmp_printf(, pt);
char buffer[64];
mpz_export(buffer, NULL, 1, 1, 0, 0, pt);
printf(, buffer);
mpz_clears(pt, ct, n, e, d, NULL);
return 0;
} | 324RSA code
| 5c
| pv2by |
sub sieve {
my $n = shift;
my @composite;
for my $i (2 .. int(sqrt($n))) {
if (!$composite[$i]) {
for (my $j = $i*$i; $j <= $n; $j += $i) {
$composite[$j] = 1;
}
}
}
my @primes;
for my $i (2 .. $n) {
$composite[$i] || push @primes, $i;
}
@primes;
} | 309Sieve of Eratosthenes
| 2perl
| txyfg |
(let [haystack ["Zig" "Zag" "Wally" "Ronald" "Bush" "Krusty" "Charlie" "Bush" "Bozo"]]
(let [idx (.indexOf haystack "Zig")]
(if (neg? idx)
(throw (Error. "item not found."))
idx))) | 323Search a list
| 6clojure
| g664f |
my ($a, $b) = (-5, 7);
$ans = eval 'abs($a * $b)'; | 321Runtime evaluation
| 2perl
| xrjw8 |
require
class Integer
def safe_prime?
((self-1)/2).prime?
end
end
def format_parts(n)
partitions = Prime.each(n).partition(&:safe_prime?).map(&:count)
% partitions
end
puts
p Prime.each.lazy.select(&:safe_prime?).take(35).to_a
puts format_parts(1_000_000),
puts
p Prime.each.lazy.reject(&:safe_prime?).take(40).to_a
puts format_parts(10_000_000) | 319Safe primes and unsafe primes
| 14ruby
| fesdr |
package main
import (
"bitbucket.org/binet/go-eval/pkg/eval"
"fmt"
"go/parser"
"go/token"
)
func main() { | 322Runtime evaluation/In an environment
| 0go
| hcljq |
cities = [
{ : , : 21.0 },
{ : , : 15.2 },
{ : , : 11.3 },
{ : , : 7.55 },
{ : , : 5.85 },
{ : , : 4.98 },
{ : , : 4.7 },
{ : , : 4.58 },
{ : , : 4.4 },
{ : , : 3.98 }
]
def first(query):
return next(query, None)
print(
first(index for index, city in enumerate(cities)
if city['name'] == ),
first(city['name'] for city in cities if city['population'] < 5),
first(city['population'] for city in cities if city['name'][0] == 'A'),
sep='\n') | 317Search a list of records
| 3python
| b2rkr |
<?php
$code = 'echo ';
eval($code);
$code = 'return ';
print eval($code); | 321Runtime evaluation
| 12php
| 2dtl4 |
fn is_prime(n: i32) -> bool {
for i in 2..n {
if i * i > n {
return true;
}
if n% i == 0 {
return false;
}
}
n > 1
}
fn is_safe_prime(n: i32) -> bool {
is_prime(n) && is_prime((n - 1) / 2)
}
fn is_unsafe_prime(n: i32) -> bool {
is_prime(n) &&!is_prime((n - 1) / 2)
}
fn next_prime(n: i32) -> i32 {
for i in (n+1).. {
if is_prime(i) {
return i;
}
}
0
}
fn main() {
let mut safe = 0;
let mut unsf = 0;
let mut p = 2;
print!("first 35 safe primes: ");
while safe < 35 {
if is_safe_prime(p) {
safe += 1;
print!("{} ", p);
}
p = next_prime(p);
}
println!("");
p = 2;
print!("first 35 unsafe primes: ");
while unsf < 35 {
if is_unsafe_prime(p) {
unsf += 1;
print!("{} ", p);
}
p = next_prime(p);
}
println!("");
p = 2;
safe = 0;
unsf = 0;
while p < 1000000 {
if is_safe_prime(p) {
safe += 1;
} else {
unsf += 1;
}
p = next_prime(p);
}
println!("safe primes below 1,000,000: {}", safe);
println!("unsafe primes below 1,000,000: {}", unsf);
while p < 10000000 {
if is_safe_prime(p) {
safe += 1;
} else {
unsf += 1;
}
p = next_prime(p);
}
println!("safe primes below 10,000,000: {}", safe);
println!("unsafe primes below 10,000,000: {}", unsf);
} | 319Safe primes and unsafe primes
| 15rust
| tw0fd |
def cruncher = { x1, x2, program ->
Eval.x(x1, program) - Eval.x(x2, program)
} | 322Runtime evaluation/In an environment
| 7groovy
| 4365f |
>>> exec '''
x = sum([1,2,3,4])
print x
'''
10 | 321Runtime evaluation
| 3python
| q7hxi |
import java.io.File;
import java.lang.reflect.Method;
import java.net.URI;
import java.util.Arrays;
import javax.tools.JavaCompiler;
import javax.tools.SimpleJavaFileObject;
import javax.tools.ToolProvider;
public class Eval {
private static final String CLASS_NAME = "TempPleaseDeleteMe";
private static class StringCompiler
extends SimpleJavaFileObject {
final String m_sourceCode;
private StringCompiler( final String sourceCode ) {
super( URI.create( "string: | 322Runtime evaluation/In an environment
| 9java
| xr7wy |
function iprimes_upto($limit)
{
for ($i = 2; $i < $limit; $i++)
{
$primes[$i] = true;
}
for ($n = 2; $n < $limit; $n++)
{
if ($primes[$n])
{
for ($i = $n*$n; $i < $limit; $i += $n)
{
$primes[$i] = false;
}
}
}
return $primes;
}
echo wordwrap(
'Primes less or equal than 1000 are: ' . PHP_EOL .
implode(' ', array_keys(iprimes_upto(1000), true, true)),
100
); | 309Sieve of Eratosthenes
| 12php
| k2ahv |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.