code stringlengths 1 46.1k ⌀ | label class label 1.18k
classes | domain_label class label 21
classes | index stringlengths 4 5 |
|---|---|---|---|
use warnings;
use strict;
use feature qw{ say };
use JSON::PP;
use Time::Piece;
use constant {
NAME => 0,
CATEGORY => 1,
DATE => 2,
DB => 'simple-db',
};
my $operation = shift // "";
my %dispatch = (
n => \&add_new,
l => \&print_latest,
L => \&print_latest_for_categories,
... | 279Simple database | 2perl | op08x |
$ echo 'main() {printf();}' | gcc -w -x c -; ./a.out | 282Shell one-liner | 5c | 8bw04 |
$ clj-env-dir -e "(defn add2 [x] (inc (inc x))) (add2 40)"
#'user/add2
42 | 282Shell one-liner | 6clojure | fw8dm |
>>> import time
>>> time.asctime(time.gmtime(0))
'Thu Jan 1 00:00:00 1970'
>>> | 277Show the epoch | 3python | h2kjw |
> epoch <- 0
> class(epoch) <- class(Sys.time())
> format(epoch, "%Y-%m-%d%H:%M:%S%Z")
[1] "1970-01-01 00:00:00 UTC" | 277Show the epoch | 13r | gmr47 |
package main
import "fmt"
type point struct{ x, y float64 }
func shoelace(pts []point) float64 {
sum := 0.
p0 := pts[len(pts)-1]
for _, p1 := range pts {
sum += p0.y*p1.x - p0.x*p1.y
p0 = p1
}
return sum / 2
}
func main() {
fmt.Println(shoelace([]point{{3, 4}, {5, 11}, {12, 8... | 281Shoelace formula for polygonal area | 0go | na0i1 |
irb(main):001:0> Time.at(0).utc
=> 1970-01-01 00:00:00 UTC | 277Show the epoch | 14ruby | bupkq |
extern crate time;
use time::{at_utc, Timespec};
fn main() {
let epoch = at_utc(Timespec::new(0, 0));
println!("{}", epoch.asctime());
} | 277Show the epoch | 15rust | p51bu |
import java.util.{Date, TimeZone, Locale}
import java.text.DateFormat
val df=DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG, Locale.ENGLISH)
df.setTimeZone(TimeZone.getTimeZone("UTC"))
println(df.format(new Date(0))) | 277Show the epoch | 16scala | erwab |
import Data.Bifunctor (bimap)
shoelace :: [(Double, Double)] -> Double
shoelace =
let calcSums ((x, y), (a, b)) = bimap (x * b +) (a * y +)
in (/ 2)
. abs
. uncurry (-)
. foldr calcSums (0, 0)
. (<*>) zip (tail . cycle)
main :: IO ()
main =
print $
shoelace [(3, 4), (5... | 281Shoelace formula for polygonal area | 8haskell | uzcv2 |
'''\
Simple database for: http:
'''
import argparse
from argparse import Namespace
import datetime
import shlex
def parse_args():
'Set up, parse, and return arguments'
parser = argparse.ArgumentParser(epilog=globals()['__doc__'])
parser.add_argument('command', choices='add pl plc pa'.split(),
... | 279Simple database | 3python | i18of |
int main()
{
int i, j, dim, d;
int depth = 3;
for (i = 0, dim = 1; i < depth; i++, dim *= 3);
for (i = 0; i < dim; i++) {
for (j = 0; j < dim; j++) {
for (d = dim / 3; d; d /= 3)
if ((i % (d * 3)) / d == 1 && (j % (d * 3)) / d == 1)
break;
printf(d ? : );
}
printf();
}
return 0;
} | 283Sierpinski carpet | 5c | sh1q5 |
import java.util.List;
public class ShoelaceFormula {
private static class Point {
int x, y;
Point(int x, int y) {
this.x = x;
this.y = y;
}
@Override
public String toString() {
return String.format("(%d,%d)", x, y);
}
}
... | 281Shoelace formula for polygonal area | 9java | mozym |
(() => {
"use strict"; | 281Shoelace formula for polygonal area | 10javascript | vt925 |
echo 'package main;func main(){println("hlowrld")}'>/tmp/h.go;go run /tmp/h.go | 282Shell one-liner | 0go | 53cul |
package main
import (
"fmt"
"strings"
"unicode/utf8"
)
var order = 4
var grain = "*"
func main() {
t := []string{grain + strings.Repeat(" ", utf8.RuneCountInString(grain))}
for ; order > 0; order-- {
sp := strings.Repeat(" ", utf8.RuneCountInString(t[0])/2)
top := make([]string, l... | 278Sierpinski triangle | 0go | 8p80g |
(ns example
(:require [clojure.contrib.math:as math]))
(defn in-carpet? [x y]
(loop [x x, y y]
(cond
(or (zero? x) (zero? y)) true
(and (= 1 (mod x 3)) (= 1 (mod y 3))) false
:else (recur (quot x 3) (quot y 3)))))
(defn carpet [n]
(apply str
... | 283Sierpinski carpet | 6clojure | naqik |
null | 281Shoelace formula for polygonal area | 11kotlin | txif0 |
$ groovysh -q "println 'Hello'"
Hello | 282Shell one-liner | 7groovy | cn39i |
$ ghc -e 'putStrLn "Hello"'
Hello | 282Shell one-liner | 8haskell | x7pw4 |
$ echo 'public class X{public static void main(String[]args){' \
> 'System.out.println("Hello Java!");}}' >X.java
$ javac X.java && java X | 282Shell one-liner | 9java | bvrk3 |
bool a(bool in)
{
printf();
return in;
}
bool b(bool in)
{
printf();
return in;
}
do { \
x = a(X) O b(Y); \
printf(
} while(false);
int main()
{
bool x;
TEST(false, true, &&);
TEST(true, false, ||);
TEST(true, false, &&);
TEST(false, false, ||);
return 0;
} | 284Short-circuit evaluation | 5c | ope80 |
require 'date'
require 'json'
require 'securerandom'
class SimpleDatabase
def initialize(dbname, *fields)
@dbname = dbname
@filename = @dbname +
@fields = fields
@maxl = @fields.collect {|f| f.length}.max
@data = {
'fields' => fields,
'items' => {},
'history' => [],
'tags... | 279Simple database | 14ruby | deins |
def stPoints;
stPoints = { order, base=[0,0] ->
def right = [base[0], base[1]+2**order]
def up = [base[0]+2**(order-1), base[1]+2**(order-1)]
(order == 0) \
? [base]
: (stPoints(order-1, base) + stPoints(order-1, right) + stPoints(order-1, up))
}
def stGrid = { order ->
def h = 2**order
... | 278Sierpinski triangle | 7groovy | w7wel |
function shoeArea(ps)
local function det2(i,j)
return ps[i][1]*ps[j][2]-ps[j][1]*ps[i][2]
end
local sum = #ps>2 and det2(#ps,1) or 0
for i=1,#ps-1 do sum = sum + det2(i,i+1)end
return math.abs(0.5 * sum)
end | 281Shoelace formula for polygonal area | 1lua | zqnty |
$ js -e 'print("hello")'
hello | 282Shell one-liner | 10javascript | wrbe2 |
sierpinski 0 = ["*"]
sierpinski n = map ((space ++) . (++ space)) down ++
map (unwords . replicate 2) down
where down = sierpinski (n - 1)
space = replicate (2 ^ (n - 1)) ' '
main = mapM_ putStrLn $ sierpinski 4 | 278Sierpinski triangle | 8haskell | lflch |
echo 'fun main(args: Array<String>) = println("Hello Kotlin!")' >X.kt;kotlinc X.kt -include-runtime -d X.jar && java -jar X.jar | 282Shell one-liner | 11kotlin | rmvgo |
guchar* sha256_merkle_tree(FILE* in, size_t block_size) {
gchar* buffer = g_malloc(block_size);
GPtrArray* hashes = g_ptr_array_new_with_free_func(g_free);
gssize digest_length = g_checksum_type_get_length(G_CHECKSUM_SHA256);
GChecksum* checksum = g_checksum_new(G_CHECKSUM_SHA256);
size_t bytes;
... | 285SHA-256 Merkle tree | 5c | 15gpj |
object SimpleDatabase extends App {
type Entry = Array[String]
def asTSV(e: Entry) = e mkString "\t"
def fromTSV(s: String) = s split "\t"
val header = asTSV(Array("TIMESTAMP", "DESCRIPTION", "CATEGORY", "OTHER"))
def read(filename: String) = try {
scala.io.Source.fromFile(filename).getLines.drop(1).map(... | 279Simple database | 16scala | 3stzy |
lua -e 'print "Hello World!"' | 282Shell one-liner | 1lua | 79uru |
(letfn [(a [bool] (print "(a)") bool)
(b [bool] (print "(b)") bool)]
(doseq [i [true false] j [true false]]
(print i "OR" j "= ")
(println (or (a i) (b j)))
(print i "AND" j " = ")
(println (and (a i) (b j))))) | 284Short-circuit evaluation | 6clojure | tx0fv |
use strict;
use warnings;
use feature 'say';
sub area_by_shoelace {
my $area;
our @p;
$
$area += $p[$_][0] * $p[($_+1)%@p][1] for 0 .. @p-1;
$area -= $p[$_][1] * $p[($_+1)%@p][0] for 0 .. @p-1;
return abs $area/2;
}
my @poly = ( [3,4], [5,11], [12,8], [9,5], [5,6] );
say area_by_shoelace( [... | 281Shoelace formula for polygonal area | 2perl | k2rhc |
typedef unsigned char bool;
void sieve(bool *c, int limit) {
int i, p = 3, p2;
c[0] = TRUE;
c[1] = TRUE;
for (;;) {
p2 = p * p;
if (p2 >= limit) {
break;
}
for (i = p2; i < limit; i += 2*p) {
c[i] = TRUE;
}
for (;;) {
... | 286Sexy primes | 5c | txqf4 |
package main
import (
"crypto/sha256"
"fmt"
"io"
"log"
"os"
)
func main() {
const blockSize = 1024
f, err := os.Open("title.png")
if err != nil {
log.Fatal(err)
}
defer f.Close()
var hashes [][]byte
buffer := make([]byte, blockSize)
h := sha256.New()
fo... | 285SHA-256 Merkle tree | 0go | y8i64 |
>>> def area_by_shoelace(x, y):
return abs( sum(i * j for i, j in zip(x, y[1:] + y[:1]))
-sum(i * j for i, j in zip(x[1:] + x[:1], y ))) / 2
>>> points = [(3,4), (5,11), (12,8), (9,5), (5,6)]
>>> x, y = zip(*points)
>>> area_by_shoelace(x, y)
30.0
>>> | 281Shoelace formula for polygonal area | 3python | bv7kr |
package main
import (
"fmt"
"strings"
)
type test struct {
bs string
n int
}
func setRightBits(bits []byte, e, n int) []byte {
if e == 0 || n <= 0 {
return bits
}
bits2 := make([]byte, len(bits))
copy(bits2, bits)
for i := 0; i < e-1; i++ {
c := bits[i]
if... | 287Set right-adjacent bits | 0go | qjjxz |
import Control.Monad (mfilter)
import Crypto.Hash.SHA256 (hash)
import qualified Data.ByteString as B
import Data.ByteString.Builder (byteStringHex, char7, hPutBuilder)
import Data.Functor ((<&>))
import Data.Maybe (listToMaybe)
import Data.Strict.Tuple (Pair(..))
import qualified Data.Strict.Tuple as T
import System.E... | 285SHA-256 Merkle tree | 8haskell | hlvju |
int main() {
int i, j;
char k[4];
for (i = 0; i < 16; ++i) {
for (j = 32 + i; j < 128; j += 16) {
switch (j) {
default: sprintf(k, , j); break;
case 32: sprintf(k, ); break;
case 127: sprintf(k, ); break;
}
printf(... | 288Show ASCII table | 5c | puvby |
use strict;
use warnings;
while( <DATA> )
{
my ($n, $input) = split;
my $width = length $input;
my $result = '';
$result |= substr 0 x $_ . $input, 0, $width for 0 .. $n;
print "n = $n width = $width\n input $input\nresult $result\n\n";
}
__DATA__
2 1000
2 0100
2 0011
2 0000
0 010000000000100000000010... | 287Set right-adjacent bits | 2perl | 4665d |
import java.io.*;
import java.security.*;
import java.util.*;
public class SHA256MerkleTree {
public static void main(String[] args) {
if (args.length != 1) {
System.err.println("missing file argument");
System.exit(1);
}
try (InputStream in = new BufferedInputStream... | 285SHA-256 Merkle tree | 9java | 53yuf |
public class SierpinskiTriangle {
public static void main(String[] args) {
System.out.println(getSierpinskiTriangle(4));
}
private static final String getSierpinskiTriangle(int n) {
if ( n == 0 ) {
return "*";
}
String s = getSierpinskiTriangle(n-1);
St... | 278Sierpinski triangle | 9java | 303zg |
Point = Struct.new(:x,:y) do
def shoelace(other)
x * other.y - y * other.x
end
end
class Polygon
def initialize(*coords)
@points = coords.map{|c| Point.new(*c) }
end
def area
points = @points + [@points.first]
points.each_cons(2).sum{|p1,p2| p1.shoelace(p2) }.abs.fdiv(2)
end
end
puts... | 281Shoelace formula for polygonal area | 14ruby | 15hpw |
$ perl -e 'print "Hello\n"'
Hello | 282Shell one-liner | 2perl | de0nw |
int main()
{
int i;
unsigned char result[SHA_DIGEST_LENGTH];
const char *string = ;
SHA1(string, strlen(string), result);
for(i = 0; i < SHA_DIGEST_LENGTH; i++)
printf(, result[i], i < (SHA_DIGEST_LENGTH-1) ? ' ' : '\n');
return EXIT_SUCCESS;
} | 289SHA-1 | 5c | wr4ec |
from operator import or_
from functools import reduce
def set_right_adjacent_bits(n: int, b: int) -> int:
return reduce(or_, (b >> x for x in range(n+1)), 0)
if __name__ == :
print()
n = 2
bits =
first = True
for b_str in bits.split():
b = int(b_str, 2)
e = len(b_str)
... | 287Set right-adjacent bits | 3python | gyy4h |
case class Point( x:Int,y:Int ) { override def toString = "(" + x + "," + y + ")" }
case class Polygon( pp:List[Point] ) {
require( pp.size > 2, "A Polygon must consist of more than two points" )
override def toString = "Polygon(" + pp.mkString(" ", ", ", " ") + ")"
def area = { | 281Shoelace formula for polygonal area | 16scala | x71wg |
$ php -r 'echo ;'
Hello | 282Shell one-liner | 12php | jc57z |
use std::ops::{BitOrAssign, Shr};
fn set_right_adjacent_bits<E: Clone + BitOrAssign + Shr<usize, Output = E>>(b: &mut E, n: usize) {
for _ in 1..=n {
*b |= b.clone() >> 1;
}
}
macro_rules! test {
( $t:ident, $n:expr, $e:expr, $g:ty, $b:expr, $c:expr$(,)? ) => {
#[test]
fn $t() {
... | 287Set right-adjacent bits | 15rust | jcc72 |
(function (order) { | 278Sierpinski triangle | 10javascript | cdc9j |
import Foundation
struct Point {
var x: Double
var y: Double
}
extension Point: CustomStringConvertible {
var description: String {
return "Point(x: \(x), y: \(y))"
}
}
struct Polygon {
var points: [Point]
var area: Double {
let xx = points.map({ $0.x })
let yy = points.map({ $0.y })
let... | 281Shoelace formula for polygonal area | 17swift | pujbl |
int main (void) {
const char *s = ;
unsigned char *d = SHA256(s, strlen(s), 0);
int i;
for (i = 0; i < SHA256_DIGEST_LENGTH; i++)
printf(, d[i]);
putchar('\n');
return 0;
} | 290SHA-256 | 5c | cn89c |
package main
import "fmt"
func sieve(limit int) []bool {
limit++ | 286Sexy primes | 0go | hl2jq |
use strict;
use warnings;
use Crypt::Digest::SHA256 'sha256' ;
my @blocks;
open my $fh, '<:raw', './title.png';
while ( read $fh, my $chunk, 1024 ) { push @blocks, sha256 $chunk }
while ( scalar @blocks > 1 ) {
my @clone = @blocks and @blocks = ();
while ( @_ = splice @clone, 0, 2 ) {
push @blocks, sca... | 285SHA-256 Merkle tree | 2perl | x7hw8 |
(defn cell [code]
(let [text (get {32 "Spc", 127 "Del"} code (char code))]
(format "%3d:%3s" code text)))
(defn ascii-table [n-cols st-code end-code]
(let [n-cells (inc (- end-code st-code))
n-rows (/ n-cells n-cols)
code (fn [r c] (+ st-code r (* c n-rows)))
row-str (fn [r]
... | 288Show ASCII table | 6clojure | x7rwk |
$ python -c 'print '
Hello | 282Shell one-liner | 3python | fw8de |
char *names[4][3] = {
{ , , },
{ , , },
{ , , },
{ , , }
};
int set[81][81];
void init_sets(void)
{
int i, j, t, a, b;
for (i = 0; i < 81; i++) {
for (j = 0; j < 81; j++) {
for (t = 27; t; t /= 3) {
a = (i / t) % 3;
b = (j / t) % 3;
set[i][j] += t * (a == b ? a : 3 - a - b);
}
}
}
}
... | 291Set puzzle | 5c | ld8cy |
(defun sha1-hash (data)
(let ((sha1 (ironclad:make-digest 'ironclad:sha1))
(bin-data (ironclad:ascii-string-to-byte-array data)))
(ironclad:update-digest sha1 bin-data)
(ironclad:byte-array-to-hex-string (ironclad:produce-digest sha1)))) | 289SHA-1 | 6clojure | 8bh05 |
int rand5()
{
int r, rand_max = RAND_MAX - (RAND_MAX % 5);
while ((r = rand()) >= rand_max);
return r / (rand_max / 5) + 1;
}
int rand5_7()
{
int r;
while ((r = rand5() * 5 + rand5()) >= 27);
return r / 3 - 1;
}
int main()
{
printf(check(rand5, 5, 1000000, .05) ? : );
printf(check(rand7, 7, 1000000, .05) ? ... | 292Seven-sided dice from five-sided dice | 5c | zq1tx |
import Text.Printf (printf)
import Data.Numbers.Primes (isPrime, primes)
type Pair = (Int, Int)
type Triplet = (Int, Int, Int)
type Quad = (Int, Int, Int, Int)
type Quin = (Int, Int, Int, Int, Int)
type Result = ([Pair], [Triplet], [Quad], [Quin], [Int])
groups :: Int -> Result -> Result
groups n r@(p, t, q,... | 286Sexy primes | 8haskell | i1aor |
$ echo 'cat("Hello\n")' | R --slave
Hello | 282Shell one-liner | 13r | opx84 |
import argh
import hashlib
import sys
@argh.arg('filename', nargs='?', default=None)
def main(filename, block_size=1024*1024):
if filename:
fin = open(filename, 'rb')
else:
fin = sys.stdin
stack = []
block = fin.read(block_size)
while block:
node = (0, hashlib.s... | 285SHA-256 Merkle tree | 3python | qjkxi |
null | 278Sierpinski triangle | 11kotlin | nenij |
$ ruby -e 'puts '
Hello | 282Shell one-liner | 14ruby | zqitw |
(use 'pandect.core)
(sha256 "Rosetta code") | 290SHA-256 | 6clojure | 53fuz |
(def dice5 #(rand-int 5))
(defn dice7 []
(quot (->> dice5
(repeatedly 2)
(apply #(+ %1 (* 5 %2)))
#()
repeatedly
(drop-while #(> % 20))
first) ... | 292Seven-sided dice from five-sided dice | 6clojure | 9iqma |
import java.util.ArrayList;
import java.util.List;
public class SexyPrimes {
public static void main(String[] args) {
sieve();
int pairs = 0;
List<String> pairList = new ArrayList<>();
int triples = 0;
List<String> tripleList = new ArrayList<>();
int quadruplets = 0... | 286Sexy primes | 9java | x7jwy |
$ echo 'fn main(){println!("Hello!")}' | rustc -;./rust_out | 282Shell one-liner | 15rust | 3snz8 |
C:\>scala -e "println(\"Hello\")"
Hello | 282Shell one-liner | 16scala | motyc |
null | 286Sexy primes | 11kotlin | pu5b6 |
extern crate crypto;
use crypto::digest::Digest;
use crypto::sha2::Sha256;
use std::fs::File;
use std::io::prelude::*;
use std::io::BufReader;
fn sha256_merkle_tree(filename: &str, block_size: usize) -> std::io::Result<Option<Vec<u8>>> {
let mut md = Sha256::new();
let mut input = BufReader::new(File::open(fi... | 285SHA-256 Merkle tree | 15rust | 8b107 |
package main
import "fmt"
func a(v bool) bool {
fmt.Print("a")
return v
}
func b(v bool) bool {
fmt.Print("b")
return v
}
func test(i, j bool) {
fmt.Printf("Testing a(%t) && b(%t)\n", i, j)
fmt.Print("Trace: ")
fmt.Println("\nResult:", a(i) && b(j))
fmt.Printf("Testing a(%t) || b(%... | 284Short-circuit evaluation | 0go | 46952 |
local N = 1000035 | 286Sexy primes | 1lua | 154po |
function sierpinski(depth)
lines = {}
lines[1] = '*'
for i = 2, depth+1 do
sp = string.rep(' ', 2^(i-2))
tmp = {}
for idx, line in ipairs(lines) do
tmp[idx] = sp .. line .. sp
tmp[idx+#lines] = line .. ' ' .. line
end
lines = tmp
end
return table.concat(li... | 278Sierpinski triangle | 1lua | dwdnq |
def f = { println ' AHA!'; it instanceof String }
def g = { printf ('%5d ', it); it > 50 }
println 'bitwise'
assert g(100) & f('sss')
assert g(2) | f('sss')
assert ! (g(1) & f('sss'))
assert g(200) | f('sss')
println '''
logical'''
assert g(100) && f('sss')
assert g(2) || f('sss')
assert ! (g(1) && f('sss'))
assert ... | 284Short-circuit evaluation | 7groovy | ldzc1 |
module ShortCircuit where
import Prelude hiding ((&&), (||))
import Debug.Trace
False && _ = False
True && False = False
_ && _ = True
True || _ = True
False || True = True
_ || _ = False
a p = trace ("<a " ++ show p ++ ">") p
b p = trace ("<b " ++ show p ++ ">") p
main = mapM_ print ( ... | 284Short-circuit evaluation | 8haskell | qjbx9 |
package main
import (
"fmt"
"math/rand"
"time"
)
const (
number = [3]string{"1", "2", "3"}
color = [3]string{"red", "green", "purple"}
shade = [3]string{"solid", "open", "striped"}
shape = [3]string{"oval", "squiggle", "diamond"}
)
type card int
func (c card) String() string {
ret... | 291Set puzzle | 0go | x75wf |
use ntheory qw/prime_iterator is_prime/;
sub tuple_tail {
my($n,$cnt,@array) = @_;
$n = @array if $n > @array;
my @tail;
for (1..$n) {
my $p = $array[-$n+$_-1];
push @tail, "(" . join(" ", map { $p+6*$_ } 0..$cnt-1) . ")";
}
return @tail;
}
sub comma {
(my $s = reverse shif... | 286Sexy primes | 2perl | y8o6u |
public class ShortCirc {
public static void main(String[] args){
System.out.println("F and F = " + (a(false) && b(false)) + "\n");
System.out.println("F or F = " + (a(false) || b(false)) + "\n");
System.out.println("F and T = " + (a(false) && b(true)) + "\n");
System.out.println("F ... | 284Short-circuit evaluation | 9java | pugb3 |
import Control.Monad.State
(State, evalState, replicateM, runState, state)
import System.Random (StdGen, newStdGen, randomR)
import Data.List (find, nub, sort)
combinations :: Int -> [a] -> [[a]]
combinations 0 _ = [[]]
combinations _ [] = []
combinations k (y:ys) = map (y:) (combinations (k - 1) ys) ++ combina... | 291Set puzzle | 8haskell | y8x66 |
package main
import (
"fmt"
"math"
"math/rand"
"time"
) | 292Seven-sided dice from five-sided dice | 0go | k2yhz |
package main
import (
"fmt"
"strings"
"unicode/utf8"
)
var order = 3
var grain = "#"
func main() {
carpet := []string{grain}
for ; order > 0; order-- { | 283Sierpinski carpet | 0go | vty2m |
(function () {
'use strict';
function a(bool) {
console.log('a -->', bool);
return bool;
}
function b(bool) {
console.log('b -->', bool);
return bool;
}
var x = a(false) && b(true),
y = a(true) || b(false),
z = true ? a(true) : b(false);
r... | 284Short-circuit evaluation | 10javascript | x7kw9 |
import java.util.*;
public class SetPuzzle {
enum Color {
GREEN(0), PURPLE(1), RED(2);
private Color(int v) {
val = v;
}
public final int val;
}
enum Number {
ONE(0), TWO(1), THREE(2);
private Number(int v) {
val = v;
}
... | 291Set puzzle | 9java | debn9 |
random = new Random()
int rand5() {
random.nextInt(5) + 1
}
int rand7From5() {
def raw = 25
while (raw > 21) {
raw = 5*(rand5() - 1) + rand5()
}
(raw % 7) + 1
} | 292Seven-sided dice from five-sided dice | 7groovy | gyf46 |
import System.Random
import Data.List
sevenFrom5Dice = do
d51 <- randomRIO(1,5) :: IO Int
d52 <- randomRIO(1,5) :: IO Int
let d7 = 5*d51+d52-6
if d7 > 20 then sevenFrom5Dice
else return $ 1 + d7 `mod` 7 | 292Seven-sided dice from five-sided dice | 8haskell | nahie |
def base3 = { BigInteger i -> i.toString(3) }
def sierpinskiCarpet = { int order ->
StringBuffer sb = new StringBuffer()
def positions = 0..<(3**order)
def digits = 0..<([order,1].max())
positions.each { i ->
String i3 = base3(i).padLeft(order, '0')
positions.each { j ->
S... | 283Sierpinski carpet | 7groovy | mofy5 |
null | 284Short-circuit evaluation | 11kotlin | 792r4 |
null | 291Set puzzle | 11kotlin | 0krsf |
package main
import (
"crypto/sha1"
"fmt"
)
func main() {
h := sha1.New()
h.Write([]byte("Rosetta Code"))
fmt.Printf("%x\n", h.Sum(nil))
} | 289SHA-1 | 0go | cno9g |
inCarpet :: Int -> Int -> Bool
inCarpet 0 _ = True
inCarpet _ 0 = True
inCarpet x y = not ((xr == 1) && (yr == 1)) && inCarpet xq yq
where ((xq, xr), (yq, yr)) = (x `divMod` 3, y `divMod` 3)
carpet :: Int -> [String]
carpet n = map
(zipWith
(\x y -> if inCarpet x y then '#' else ' ')
... | 283Sierpinski carpet | 8haskell | eghai |
import java.util.Random;
public class SevenSidedDice
{
private static final Random rnd = new Random();
public static void main(String[] args)
{
SevenSidedDice now=new SevenSidedDice();
System.out.println("Random number from 1 to 7: "+now.seven());
}
int seven()
{
int v=21;
while(v>20)
v=five()+five()*... | 292Seven-sided dice from five-sided dice | 9java | qj5xa |
function dice5()
{
return 1 + Math.floor(5 * Math.random());
}
function dice7()
{
while (true)
{
var dice55 = 5 * dice5() + dice5() - 6;
if (dice55 < 21)
return dice55 % 7 + 1;
}
}
distcheck(dice5, 1000000);
print();
distcheck(dice7, 1000000); | 292Seven-sided dice from five-sided dice | 10javascript | i1jol |
LIMIT = 1_000_035
def primes2(limit=LIMIT):
if limit < 2: return []
if limit < 3: return [2]
lmtbf = (limit - 3)
buf = [True] * (lmtbf + 1)
for i in range((int(limit ** 0.5) - 3)
if buf[i]:
p = i + i + 3
s = p * (i + 1) + i
buf[s::p] = [False] * ((lmtbf ... | 286Sexy primes | 3python | moiyh |
package main
import (
"crypto/sha256"
"fmt"
"log"
)
func main() {
h := sha256.New()
if _, err := h.Write([]byte("Rosetta code")); err != nil {
log.Fatal(err)
}
fmt.Printf("%x\n", h.Sum(nil))
} | 290SHA-256 | 0go | wr5eg |
module Digestor
where
import Data.Digest.Pure.SHA
import qualified Data.ByteString.Lazy as B
convertString :: String -> B.ByteString
convertString phrase = B.pack $ map ( fromIntegral . fromEnum ) phrase
convertToSHA1 :: String -> String
convertToSHA1 word = showDigest $ sha1 $ convertString word
main = do
p... | 289SHA-1 | 8haskell | pu2bt |
null | 292Seven-sided dice from five-sided dice | 11kotlin | 15cpd |
use strict;
use warnings;
my $fmt = '%4o';
my @deck = grep sprintf($fmt, $_) !~ tr/124//c, 01111 .. 04444;
my @features = map [split ' '], split /\n/,<<'';
! red green ! purple
! one two ! three
! oval squiggle ! diamond
! solid open ! striped
81 == @deck or die "There are ".@deck." cards (sh... | 291Set puzzle | 2perl | 53du2 |
def sha256Hash = { text ->
java.security.MessageDigest.getInstance("SHA-256").digest(text.bytes)
.collect { String.format("%02x", it) }.join('')
} | 290SHA-256 | 7groovy | bvcky |
dice5 = function() return math.random(5) end
function dice7()
x = dice5() * 5 + dice5() - 6
if x > 20 then return dice7() end
return x%7 + 1
end | 292Seven-sided dice from five-sided dice | 1lua | a4l1v |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.