code
stringlengths 1
46.1k
⌀ | label
class label 1.18k
classes | domain_label
class label 21
classes | index
stringlengths 4
5
|
---|---|---|---|
<?php
$encoded = ;
$unencoded = rawurldecode($encoded);
echo ;
?> | 80URL decoding
| 12php
| 1h2pq |
DIGIT_F = {
=> 0,
=> 1,
=> 2,
=> 3,
=> 4,
=> 5,
=> 6,
=> 7,
=> 8,
=> 9,
}
DIGIT_R = {
=> 0,
=> 1,
=> 2,
=> 3,
=> 4,
=> 5,
=> 6,
=> 7,
=> 8,
=> 9,
}
END_SENTINEL =
MID_SENTINEL =
def decode_upc(s)
def decode_upc_impl(input)
upc = input.strip
if upc.length!= 95 then
return false
end
pos = 0
digits = []
sum = 0
if upc[pos .. pos + 2] == END_SENTINEL then
pos += 3
else
return false
end
for i in 0 .. 5
digit = DIGIT_F[upc[pos .. pos + 6]]
if digit == nil then
return false
else
digits.push(digit)
sum += digit * [1, 3][digits.length % 2]
pos += 7
end
end
if upc[pos .. pos + 4] == MID_SENTINEL then
pos += 5
else
return false
end
for i in 0 .. 5
digit = DIGIT_R[upc[pos .. pos + 6]]
if digit == nil then
return false
else
digits.push(digit)
sum += digit * [1, 3][digits.length % 2]
pos += 7
end
end
if upc[pos .. pos + 2] == END_SENTINEL then
pos += 3
else
return false
end
if sum % 10 == 0 then
print digits,
return true
else
print
return false
end
end
if decode_upc_impl(s) then
puts
elsif decode_upc_impl(s.reverse) then
puts
else
puts
end
end
def main
num = 0
print % [num += 1]
decode_upc()
print % [num += 1]
decode_upc()
print % [num += 1]
decode_upc()
print % [num += 1]
decode_upc()
print % [num += 1]
decode_upc()
print % [num += 1]
decode_upc()
print % [num += 1]
decode_upc()
print % [num += 1]
decode_upc()
print % [num += 1]
decode_upc()
print % [num += 1]
decode_upc()
end
main() | 84UPC
| 14ruby
| n07it |
print('Enter a string: ')
s = io.stdin:read()
print('Enter a number: ')
i = tonumber(io.stdin:read()) | 83User input/Text
| 1lua
| v982x |
Vector = {}
function Vector.new( _x, _y, _z )
return { x=_x, y=_y, z=_z }
end
function Vector.dot( A, B )
return A.x*B.x + A.y*B.y + A.z*B.z
end
function Vector.cross( A, B )
return { x = A.y*B.z - A.z*B.y,
y = A.z*B.x - A.x*B.z,
z = A.x*B.y - A.y*B.x }
end
function Vector.scalar_triple( A, B, C )
return Vector.dot( A, Vector.cross( B, C ) )
end
function Vector.vector_triple( A, B, C )
return Vector.cross( A, Vector.cross( B, C ) )
end
A = Vector.new( 3, 4, 5 )
B = Vector.new( 4, 3, 5 )
C = Vector.new( -5, -12, -13 )
print( Vector.dot( A, B ) )
r = Vector.cross(A, B )
print( r.x, r.y, r.z )
print( Vector.scalar_triple( A, B, C ) )
r = Vector.vector_triple( A, B, C )
print( r.x, r.y, r.z ) | 72Vector products
| 1lua
| c6392 |
import urllib
print urllib.unquote()
from urllib.parse import unquote
print(unquote('http%3A%2F%2Ffoo%20bar%2F')) | 80URL decoding
| 3python
| ytq6q |
require 'tk'
def main
root = TkRoot.new
l1 = TkLabel.new(root, => )
e1 = TkEntry.new(root)
l2 = TkLabel.new(root, => )
e2 = TkEntry.new(root) do
validate
validatecommand lambda {e2.value.to_i == 75_000}
invalidcommand lambda {focus_number_entry(e2)}
end
ok = TkButton.new(root) do
text
command lambda {validate_input(e1, e2)}
end
Tk.grid(l1, e1)
Tk.grid(l2, e2)
Tk.grid(,ok, => )
Tk.mainloop
end
def validate_input(text_entry, number_entry)
if number_entry.value.to_i!= 75_000
focus_number_entry(number_entry)
else
puts %Q{You entered: and }
root.destroy
end
end
def focus_number_entry(widget)
widget \
.configure( => , => ) \
.selection_range(0, ) \
.focus
end
main | 82User input/Graphical
| 14ruby
| mzxyj |
require 'cgi'
puts CGI.escape().gsub(, ) | 78URL encoding
| 14ruby
| ruygs |
URLdecode("http%3A%2F%2Ffoo%20bar%2F") | 80URL decoding
| 13r
| tiafz |
import swing.Dialog.{Message, showInput}
import scala.swing.Swing
object UserInput extends App {
def responce = showInput(null,
"Complete the sentence:\n\"Green eggs and...\"",
"Customized Dialog",
Message.Plain,
Swing.EmptyIcon,
Nil, "ham")
println(responce)
} | 82User input/Graphical
| 16scala
| 2m8lb |
const INPUT: &str = "http: | 78URL encoding
| 15rust
| 75mrc |
import java.net.{URLDecoder, URLEncoder}
import scala.compat.Platform.currentTime
object UrlCoded extends App {
val original = """http: | 78URL encoding
| 16scala
| krlhk |
require 'cgi'
puts CGI.unescape() | 80URL decoding
| 14ruby
| 930mz |
sub dofruit {
$fruit='apple';
}
dofruit;
print "The fruit is $fruit"; | 76Variables
| 2perl
| mziyz |
const INPUT1: &str = "http%3A%2F%2Ffoo%20bar%2F";
const INPUT2: &str = "google.com/search?q=%60Abdu%27l-Bah%C3%A1";
fn append_frag(text: &mut String, frag: &mut String) {
if!frag.is_empty() {
let encoded = frag.chars()
.collect::<Vec<char>>()
.chunks(2)
.map(|ch| {
u8::from_str_radix(&ch.iter().collect::<String>(), 16).unwrap()
}).collect::<Vec<u8>>();
text.push_str(&std::str::from_utf8(&encoded).unwrap());
frag.clear();
}
}
fn decode(text: &str) -> String {
let mut output = String::new();
let mut encoded_ch = String::new();
let mut iter = text.chars();
while let Some(ch) = iter.next() {
if ch == '%' {
encoded_ch.push_str(&format!("{}{}", iter.next().unwrap(), iter.next().unwrap()));
} else {
append_frag(&mut output, &mut encoded_ch);
output.push(ch);
}
}
append_frag(&mut output, &mut encoded_ch);
output
}
fn main() {
println!("{}", decode(INPUT1));
println!("{}", decode(INPUT2));
} | 80URL decoding
| 15rust
| c689z |
import java.net.{URLDecoder, URLEncoder}
import scala.compat.Platform.currentTime
object UrlCoded extends App {
val original = """http: | 80URL decoding
| 16scala
| v9n2s |
<?php
$null = NULL; var_dump($null);
$boolean = true; var_dump($boolean);
$boolean = false; var_dump($boolean);
$boolean = (bool)1; var_dump($boolean);
$boolean = (boolean)1; var_dump($boolean);
$boolean = (bool)0; var_dump($boolean);
$boolean = (boolean)0; var_dump($boolean);
$int = 0; var_dump($int);
$float = 0.01; var_dump($float);
var_dump((double)$float);
var_dump((real)$float);
var_dump((int)$float);
var_dump((int)($float+1));
var_dump((int)($float+1.9));
$string = 'string';
var_dump($string);
$another_string = &$string;
var_dump($another_string);
$string = ;
var_dump($another_string);
unset($another_string);
$string = 'string';
$parsed_string = ;
var_dump($parsed_string);
$parsed_string .= ;
var_dump($parsed_string);
$heredoc = <<<HEREDOC
This is the content of \$string: {$string}
HEREDOC;
var_dump($heredoc);
$nowdoc = <<<'NOWDOC'
This is the content of \$string: {$string}
NOWDOC;
var_dump($nowdoc);
$stdObject = new stdClass(); var_dump($stdObject);
class Foo {}
$foo = new Foo(); var_dump($foo);
$array = array(); var_dump($array);
$assoc = array(
0 => $int,
'integer' => $int,
1 => $float,
'float' => $float,
2 => $string,
'string' => $string,
3 => NULL,
3,
5 => $stdObject,
'Foo' => $foo,
);
var_dump($assoc);
function a_function()
{
var_dump(isset($foo));
global $foo;
var_dump(isset($foo));
}
a_function(); | 76Variables
| 12php
| ebra9 |
import Foundation
let encoded = "http%3A%2F%2Ffoo%20bar%2F"
if let normal = encoded.stringByReplacingPercentEscapesUsingEncoding(NSUTF8StringEncoding) {
println(normal)
} | 80URL decoding
| 17swift
| mzsyk |
example1 = 3
example2 = 3.0
example3 = True
example4 =
example1 = | 76Variables
| 3python
| 93nmf |
foo <- 3.4
bar = "abc" | 76Variables
| 13r
| 3d0zt |
print "Enter a string: ";
my $string = <>;
print "Enter an integer: ";
my $integer = <>; | 83User input/Text
| 2perl
| se5q3 |
$a_global_var = 5
class Demo
@@a_class_var = 6
A_CONSTANT = 8
def initialize
@an_instance_var = 7
end
def incr(a_local_var)
@an_instance_var += a_local_var
end
end | 76Variables
| 14ruby
| lyfcl |
<?php
$string = fgets(STDIN);
$integer = (int) fgets(STDIN); | 83User input/Text
| 12php
| ucov5 |
$ include "seed7_05.s7i";
var integer: foo is 5; # foo is global
const proc: aFunc is func
local
var integer: bar is 10; # bar is local to aFunc
begin
writeln("foo + bar = " <& foo + bar);
end func;
const proc: main is func
begin
aFunc;
end func; | 76Variables
| 16scala
| 5l6ut |
import Foundation | 76Variables
| 17swift
| c6d9t |
package Vector;
use List::Util 'sum';
use List::MoreUtils 'pairwise';
sub new { shift; bless [@_] }
use overload (
'""' => sub { "(@{+shift})" },
'&' => sub { sum pairwise { $a * $b } @{+shift}, @{+shift} },
'^' => sub {
my @a = @{+shift};
my @b = @{+shift};
bless [ $a[1]*$b[2] - $a[2]*$b[1],
$a[2]*$b[0] - $a[0]*$b[2],
$a[0]*$b[1] - $a[1]*$b[0] ]
},
);
package main;
my $a = Vector->new(3, 4, 5);
my $b = Vector->new(4, 3, 5);
my $c = Vector->new(-5, -12, -13);
print "a = $a b = $b c = $c\n";
print "$a . $b = ", $a & $b, "\n";
print "$a x $b = ", $a ^ $b, "\n";
print "$a . ($b x $c) = ", $a & ($b ^ $c), "\n";
print "$a x ($b x $c) = ", $a ^ ($b ^ $c), "\n"; | 72Vector products
| 2perl
| wpbe6 |
string = raw_input() | 83User input/Text
| 3python
| 0w4sq |
stringval <- readline("String: ")
intval <- as.integer(readline("Integer: ")) | 83User input/Text
| 13r
| wp2e5 |
int main()
{
int junk, *junkp;
printf(, junk);
junkp = malloc(sizeof *junkp);
if (junkp)
printf(, *junkp);
return 0;
} | 85Undefined values
| 5c
| yt16f |
<?php
class Vector
{
private $values;
public function setValues(array $values)
{
if (count($values) != 3)
throw new Exception('Values must contain exactly 3 values');
foreach ($values as $value)
if (!is_int($value) && !is_float($value))
throw new Exception('Value has an invalid type');
$this->values = $values;
}
public function getValues()
{
if ($this->values == null)
$this->setValues(array (
0,
0,
0
));
return $this->values;
}
public function Vector(array $values)
{
$this->setValues($values);
}
public static function dotProduct(Vector $va, Vector $vb)
{
$a = $va->getValues();
$b = $vb->getValues();
return ($a[0] * $b[0]) + ($a[1] * $b[1]) + ($a[2] * $b[2]);
}
public static function crossProduct(Vector $va, Vector $vb)
{
$a = $va->getValues();
$b = $vb->getValues();
return new Vector(array (
($a[1] * $b[2]) - ($a[2] * $b[1]),
($a[2] * $b[0]) - ($a[0] * $b[2]),
($a[0] * $b[1]) - ($a[1] * $b[0])
));
}
public static function scalarTripleProduct(Vector $va, Vector $vb, Vector $vc)
{
return self::dotProduct($va, self::crossProduct($vb, $vc));
}
public static function vectorTrippleProduct(Vector $va, Vector $vb, Vector $vc)
{
return self::crossProduct($va, self::crossProduct($vb, $vc));
}
}
class Program
{
public function Program()
{
$a = array (
3,
4,
5
);
$b = array (
4,
3,
5
);
$c = array (
-5,
-12,
-13
);
$va = new Vector($a);
$vb = new Vector($b);
$vc = new Vector($c);
$result1 = Vector::dotProduct($va, $vb);
$result2 = Vector::crossProduct($va, $vb)->getValues();
$result3 = Vector::scalarTripleProduct($va, $vb, $vc);
$result4 = Vector::vectorTrippleProduct($va, $vb, $vc)->getValues();
printf();
printf(, $a[0], $a[1], $a[2]);
printf(, $b[0], $b[1], $b[2]);
printf(, $c[0], $c[1], $c[2]);
printf();
printf(, $result1);
printf(, $result2[0], $result2[1], $result2[2]);
printf(, $result3);
printf(, $result4[0], $result4[1], $result4[2]);
}
}
new Program();
?> | 72Vector products
| 12php
| ly6cj |
print
s = gets
printf
i = gets.to_i
printf
f = Float(gets) rescue nil
puts
puts
puts | 83User input/Text
| 14ruby
| oqr8v |
int cmpstr(const void *a, const void *b)
{
return strcmp(*(const char**)a, *(const char**)b);
}
int main(void)
{
DIR *basedir;
char path[PATH_MAX];
struct dirent *entry;
char **dirnames;
int diralloc = 128;
int dirsize = 0;
if (!(dirnames = malloc(diralloc * sizeof(char*)))) {
perror();
return 1;
}
if (!getcwd(path, PATH_MAX)) {
perror();
return 1;
}
if (!(basedir = opendir(path))) {
perror();
return 1;
}
while ((entry = readdir(basedir))) {
if (dirsize >= diralloc) {
diralloc *= 2;
if (!(dirnames = realloc(dirnames, diralloc * sizeof(char*)))) {
perror();
return 1;
}
}
dirnames[dirsize++] = strdup(entry->d_name);
}
qsort(dirnames, dirsize, sizeof(char*), cmpstr);
int i;
for (i = 0; i < dirsize; ++i) {
if (dirnames[i][0] != '.') {
printf(, dirnames[i]);
}
}
for (i = 0; i < dirsize; ++i)
free(dirnames[i]);
free(dirnames);
closedir(basedir);
return 0;
} | 86Unix/ls
| 5c
| v9q2o |
use std::io::{self, Write};
use std::fmt::Display;
use std::process;
fn main() {
let s = grab_input("Give me a string")
.unwrap_or_else(|e| exit_err(&e, e.raw_os_error().unwrap_or(-1)));
println!("You entered: {}", s.trim());
let n: i32 = grab_input("Give me an integer")
.unwrap_or_else(|e| exit_err(&e, e.raw_os_error().unwrap_or(-1)))
.trim()
.parse()
.unwrap_or_else(|e| exit_err(&e, 2));
println!("You entered: {}", n);
}
fn grab_input(msg: &str) -> io::Result<String> {
let mut buf = String::new();
print!("{}: ", msg);
try!(io::stdout().flush());
try!(io::stdin().read_line(&mut buf));
Ok(buf)
}
fn exit_err<T: Display>(msg: T, code: i32) ->! {
let _ = writeln!(&mut io::stderr(), "Error: {}", msg);
process::exit(code)
} | 83User input/Text
| 15rust
| is7od |
print("Enter a number: ")
val i=Console.readLong | 83User input/Text
| 16scala
| fokd4 |
package main
import "fmt"
var (
s []int
p *int
f func()
i interface{}
m map[int]int
c chan int
)
func main() {
fmt.Println("Exercise nil objects:")
status() | 85Undefined values
| 0go
| 1hyp5 |
int main() {
int = 1;
++;
printf(,);
return 0;
} | 87Unicode variable names
| 5c
| ucqv4 |
(def files (sort (filter #(= "." (.getParent %)) (file-seq (clojure.java.io/file ".")))))
(doseq [n files] (println (.getName n))) | 86Unix/ls
| 6clojure
| ruig2 |
main = print $ "Incoming error | 85Undefined values
| 8haskell
| tihf7 |
(let [ 1]
(inc )) | 87Unicode variable names
| 6clojure
| 75ir0 |
String string = null; | 85Undefined values
| 9java
| 8x506 |
typedef struct bit_array_tag {
uint32_t size;
uint32_t* array;
} bit_array;
bool bit_array_create(bit_array* b, uint32_t size) {
uint32_t* array = calloc((size + 31)/32, sizeof(uint32_t));
if (array == NULL)
return false;
b->size = size;
b->array = array;
return true;
}
void bit_array_destroy(bit_array* b) {
free(b->array);
b->array = NULL;
}
void bit_array_set(bit_array* b, uint32_t index, bool value) {
assert(index < b->size);
uint32_t* p = &b->array[index >> 5];
uint32_t bit = 1 << (index & 31);
if (value)
*p |= bit;
else
*p &= ~bit;
}
bool bit_array_get(const bit_array* b, uint32_t index) {
assert(index < b->size);
uint32_t* p = &b->array[index >> 5];
uint32_t bit = 1 << (index & 31);
return (*p & bit) != 0;
}
typedef struct sieve_tag {
uint32_t limit;
bit_array not_prime;
} sieve;
bool sieve_create(sieve* s, uint32_t limit) {
if (!bit_array_create(&s->not_prime, limit/2))
return false;
for (uint32_t p = 3; p * p <= limit; p += 2) {
if (bit_array_get(&s->not_prime, p/2 - 1) == false) {
uint32_t inc = 2 * p;
for (uint32_t q = p * p; q <= limit; q += inc)
bit_array_set(&s->not_prime, q/2 - 1, true);
}
}
s->limit = limit;
return true;
}
void sieve_destroy(sieve* s) {
bit_array_destroy(&s->not_prime);
}
bool is_prime(const sieve* s, uint32_t n) {
assert(n <= s->limit);
if (n == 2)
return true;
if (n < 2 || n % 2 == 0)
return false;
return bit_array_get(&s->not_prime, n/2 - 1) == false;
}
uint32_t count_digits(uint32_t n) {
uint32_t digits = 0;
for (; n > 0; ++digits)
n /= 10;
return digits;
}
uint32_t change_digit(uint32_t n, uint32_t index, uint32_t new_digit) {
uint32_t p = 1;
uint32_t changed = 0;
for (; index > 0; p *= 10, n /= 10, --index)
changed += p * (n % 10);
changed += (10 * (n/10) + new_digit) * p;
return changed;
}
bool unprimeable(const sieve* s, uint32_t n) {
if (is_prime(s, n))
return false;
uint32_t d = count_digits(n);
for (uint32_t i = 0; i < d; ++i) {
for (uint32_t j = 0; j <= 9; ++j) {
uint32_t m = change_digit(n, i, j);
if (m != n && is_prime(s, m))
return false;
}
}
return true;
}
int main() {
const uint32_t limit = 10000000;
setlocale(LC_ALL, );
sieve s = { 0 };
if (!sieve_create(&s, limit)) {
fprintf(stderr, );
return 1;
}
printf();
uint32_t n = 100;
uint32_t lowest[10] = { 0 };
for (uint32_t count = 0, found = 0; n < limit && (found < 10 || count < 600); ++n) {
if (unprimeable(&s, n)) {
if (count < 35) {
if (count != 0)
printf();
printf(, n);
}
++count;
if (count == 600)
printf(, n);
uint32_t last_digit = n % 10;
if (lowest[last_digit] == 0) {
lowest[last_digit] = n;
++found;
}
}
}
sieve_destroy(&s);
for (uint32_t i = 0; i < 10; ++i)
printf( , i, lowest[i]);
return 0;
} | 88Unprimeable numbers
| 5c
| gv045 |
def crossp(a, b):
'''Cross product of two 3D vectors'''
assert len(a) == len(b) == 3, 'For 3D vectors only'
a1, a2, a3 = a
b1, b2, b3 = b
return (a2*b3 - a3*b2, a3*b1 - a1*b3, a1*b2 - a2*b1)
def dotp(a,b):
'''Dot product of two eqi-dimensioned vectors'''
assert len(a) == len(b), 'Vector sizes must match'
return sum(aterm * bterm for aterm,bterm in zip(a, b))
def scalartriplep(a, b, c):
'''Scalar triple product of three vectors: '''
return dotp(a, crossp(b, c))
def vectortriplep(a, b, c):
'''Vector triple product of three vectors: '''
return crossp(a, crossp(b, c))
if __name__ == '__main__':
a, b, c = (3, 4, 5), (4, 3, 5), (-5, -12, -13)
print(% (a, b, c))
print(% dotp(a,b))
print( % (crossp(a,b),))
print(% scalartriplep(a, b, c))
print(% (vectortriplep(a, b, c),)) | 72Vector products
| 3python
| x1pwr |
var a;
typeof(a) === "undefined";
typeof(b) === "undefined";
var obj = {}; | 85Undefined values
| 10javascript
| fojdg |
package main
import (
"fmt"
big "github.com/ncw/gmp"
)
var two = big.NewInt(2)
func a(n uint) int {
one := big.NewInt(1)
p := new(big.Int).Lsh(one, 1 << n)
p.Sub(p, one)
for k := 1; ; k += 2 {
if p.ProbablyPrime(15) {
return k
}
p.Sub(p, two)
}
}
func main() {
fmt.Println(" n k")
fmt.Println("----------")
for n := uint(1); n < 14; n++ {
fmt.Printf("%2d %d\n", n, a(n))
}
} | 89Ultra useful primes
| 0go
| qamxz |
int biased(int bias)
{
int r, rand_max = RAND_MAX - (RAND_MAX % bias);
while ((r = rand()) > rand_max);
return r < rand_max / bias;
}
int unbiased(int bias)
{
int a;
while ((a = biased(bias)) == biased(bias));
return a;
}
int main()
{
int b, n = 10000, cb, cu, i;
for (b = 3; b <= 6; b++) {
for (i = cb = cu = 0; i < n; i++) {
cb += biased(b);
cu += unbiased(b);
}
printf(, b,
100. * cb / n, 100. * cu / n);
}
return 0;
} | 90Unbias a random generator
| 5c
| n0vi6 |
package main
import "fmt"
func sumDivisors(n int) int {
sum := 1
k := 2
if n%2 == 0 {
k = 1
}
for i := 1 + k; i*i <= n; i += k {
if n%i == 0 {
sum += i
j := n / i
if j != i {
sum += j
}
}
}
return sum
}
func sieve(n int) []bool {
n++
s := make([]bool, n+1) | 91Untouchable numbers
| 0go
| foud0 |
print("Enter a string: ", terminator: "")
if let str = readLine() {
print(str)
} | 83User input/Text
| 17swift
| 8xg0v |
null | 85Undefined values
| 11kotlin
| wpcek |
use strict;
use warnings;
use feature 'say';
use bigint;
use ntheory 'is_prime';
sub useful {
my @n = @_;
my @u;
for my $n (@n) {
my $p = 2**(2**$n);
LOOP: for (my $k = 1; $k < $p; $k += 2) {
is_prime($p-$k) and push @u, $k and last LOOP;
}
}
@u
}
say join ' ', useful 1..13; | 89Ultra useful primes
| 2perl
| 42q5d |
a <- c(3, 4, 5)
b <- c(4, 3, 5)
c <- c(-5, -12, -13)
dotp <- function(x, y) {
if (length(x) == length(y)) {
sum(x*y)
}
}
crossp <- function(x, y) {
if (length(x) == 3 && length(y) == 3) {
c(x[2]*y[3] - x[3]*y[2], x[3]*y[1] - x[1]*y[3], x[1]*y[2] - x[2]*y[1])
}
}
scalartriplep <- function(x, y, z) {
if (length(x) == 3 && length(y) == 3 && length(z) == 3) {
dotp(x, crossp(y, z))
}
}
vectortriplep <- function(x, y, z) {
if (length(x) == 3 && length(y) == 3 && length(z) == 3) {
crosssp(x, crossp(y, z))
}
}
cat("a . b =", dotp(a, b))
cat("a x b =", crossp(a, b))
cat("a . (b x c) =", scalartriplep(a, b, c))
cat("a x (b x c) =", vectortriplep(a, b, c)) | 72Vector products
| 13r
| 1hjpn |
wchar_t poker[] = L;
wchar_t four_two[] = L;
int main() {
if (!setlocale(LC_CTYPE, )) {
fprintf(stderr, );
return 1;
}
printf(, 0x2708);
printf(, poker);
printf(, four_two);
printf();
printf();
printf();
return 0;
} | 92Unicode strings
| 5c
| akd11 |
print( a )
local b
print( b )
if b == nil then
b = 5
end
print( b ) | 85Undefined values
| 1lua
| x1lwz |
package main
import "fmt"
func main() {
:= 1
++
fmt.Println()
} | 87Unicode variable names
| 0go
| 0w2sk |
main = print
where = 1
= + 1 | 87Unicode variable names
| 7groovy
| ebyal |
(defn biased [n]
(if (< (rand 2) (/ n)) 0 1))
(defn unbiased [n]
(loop [a 0 b 0]
(if (= a b)
(recur (biased n) (biased n))
a)))
(for [n (range 3 7)]
[n
(double (/ (apply + (take 50000 (repeatedly #(biased n)))) 50000))
(double (/ (apply + (take 50000 (repeatedly #(unbiased n)))) 50000))])
([3 0.83292 0.50422]
[4 0.87684 0.5023]
[5 0.90122 0.49728]
[6 0.91526 0.5]) | 90Unbias a random generator
| 6clojure
| 3drzr |
main = print
where = 1
= + 1 | 87Unicode variable names
| 8haskell
| c6a94 |
use strict;
use warnings;
use enum qw(False True);
use ntheory qw/divisor_sum is_prime/;
sub sieve {
my($n) = @_;
my %s;
for my $k (0 .. $n+1) {
my $sum = divisor_sum($k) - $k;
$s{$sum} = True if $sum <= $n+1;
}
%s
}
my(%s,%c);
my($max, $limit, $cnt) = (2000, 1e5, 0);
%s = sieve 14 * $limit;
!is_prime($_) and $c{$_} = True for 1..$limit;
my @untouchable = (2, 5);
for ( my $n = 6; $n <= $limit; $n += 2 ) {
push @untouchable, $n if !$s{$n} and $c{$n-1} and $c{$n-3};
}
map { $cnt++ if $_ <= $max } @untouchable;
print "Number of untouchable numbers $max: $cnt \n\n" .
(sprintf "@{['%6d' x $cnt]}", @untouchable[0..$cnt-1]) =~ s/(.{84})/$1\n/gr . "\n";
my($p, $count) = (10, 0);
my $fmt = "%6d untouchable numbers were found %7d\n";
for my $n (@untouchable) {
$count++;
if ($n > $p) {
printf $fmt, $count-1, $p;
printf($fmt, scalar @untouchable, $limit) and last if $limit == ($p *= 10)
}
} | 91Untouchable numbers
| 2perl
| pjnb0 |
package main
import (
"fmt"
"math/big"
"time"
)
var maxChar = 128
type Node struct {
children []*Node
suffixLink *Node
start int
end *int
suffixIndex int
}
var (
text string
root *Node
lastNewNode *Node
activeNode *Node
activeEdge = -1
activeLength = 0
remainingSuffixCount = 0
leafEnd = -1
rootEnd *int
splitEnd *int
size = -1
)
func newNode(start int, end *int) *Node {
node := new(Node)
node.children = make([]*Node, maxChar)
node.suffixLink = root
node.start = start
node.end = end
node.suffixIndex = -1
return node
}
func edgeLength(n *Node) int {
if n == root {
return 0
}
return *(n.end) - n.start + 1
}
func walkDown(currNode *Node) bool {
if activeLength >= edgeLength(currNode) {
activeEdge += edgeLength(currNode)
activeLength -= edgeLength(currNode)
activeNode = currNode
return true
}
return false
}
func extendSuffixTree(pos int) {
leafEnd = pos
remainingSuffixCount++
lastNewNode = nil
for remainingSuffixCount > 0 {
if activeLength == 0 {
activeEdge = pos
}
if activeNode.children[text[activeEdge]] == nil {
activeNode.children[text[activeEdge]] = newNode(pos, &leafEnd)
if lastNewNode != nil {
lastNewNode.suffixLink = activeNode
lastNewNode = nil
}
} else {
next := activeNode.children[text[activeEdge]]
if walkDown(next) {
continue
}
if text[next.start+activeLength] == text[pos] {
if lastNewNode != nil && activeNode != root {
lastNewNode.suffixLink = activeNode
lastNewNode = nil
}
activeLength++
break
}
temp := next.start + activeLength - 1
splitEnd = &temp
split := newNode(next.start, splitEnd)
activeNode.children[text[activeEdge]] = split
split.children[text[pos]] = newNode(pos, &leafEnd)
next.start += activeLength
split.children[text[next.start]] = next
if lastNewNode != nil {
lastNewNode.suffixLink = split
}
lastNewNode = split
}
remainingSuffixCount--
if activeNode == root && activeLength > 0 {
activeLength--
activeEdge = pos - remainingSuffixCount + 1
} else if activeNode != root {
activeNode = activeNode.suffixLink
}
}
}
func setSuffixIndexByDFS(n *Node, labelHeight int) {
if n == nil {
return
}
if n.start != -1 { | 93Ukkonen’s suffix tree construction
| 0go
| gve4n |
package main
import (
"fmt"
"log"
"os"
"sort"
)
func main() {
f, err := os.Open(".")
if err != nil {
log.Fatal(err)
}
files, err := f.Readdirnames(0)
f.Close()
if err != nil {
log.Fatal(err)
}
sort.Strings(files)
for _, n := range files {
fmt.Println(n)
}
} | 86Unix/ls
| 0go
| se2qa |
int = 1;
double = 3.141592;
String = "hello";
++;
System.out.println(); | 87Unicode variable names
| 9java
| znjtq |
var = "something";
var = "hello";
var = "too less";
var = "javascript"; | 87Unicode variable names
| 10javascript
| 931ml |
import Control.Monad
import Data.List
import System.Directory
dontStartWith = flip $ (/=) . head
main = do
files <- getDirectoryContents "."
mapM_ putStrLn $ sort $ filter (dontStartWith '.') files | 86Unix/ls
| 8haskell
| 93amo |
var i int
var u rune
for i, u = range "voil" {
fmt.Println(i, u)
} | 92Unicode strings
| 0go
| mz7yi |
package main
import (
"fmt"
"strconv"
)
func isPrime(n int) bool {
switch {
case n < 2:
return false
case n%2 == 0:
return n == 2
case n%3 == 0:
return n == 3
default:
d := 5
for d*d <= n {
if n%d == 0 {
return false
}
d += 2
if n%d == 0 {
return false
}
d += 4
}
return true
}
}
func commatize(n int) string {
s := fmt.Sprintf("%d", n)
le := len(s)
for i := le - 3; i >= 1; i -= 3 {
s = s[0:i] + "," + s[i:]
}
return s
}
func main() {
fmt.Println("The first 35 unprimeable numbers are:")
count := 0 | 88Unprimeable numbers
| 0go
| isuog |
fun main(args: Array<String>) {
var = 1
++
print()
} | 87Unicode variable names
| 11kotlin
| is5o4 |
package rosetta;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
public class UnixLS {
public static void main(String[] args) throws IOException {
Files.list(Path.of("")).sorted().forEach(System.out::println);
}
} | 86Unix/ls
| 9java
| tijf9 |
const fs = require('fs');
fs.readdir('.', (err, names) => names.sort().map( name => console.log(name) )); | 86Unix/ls
| 10javascript
| mz1yv |
require 'matrix'
class Vector
def scalar_triple_product(b, c)
self.inner_product(b.cross_product c)
end
def vector_triple_product(b, c)
self.cross_product(b.cross_product c)
end
end
a = Vector[3, 4, 5]
b = Vector[4, 3, 5]
c = Vector[-5, -12, -13]
puts
puts
puts
puts | 72Vector products
| 14ruby
| seaqw |
''
| 92Unicode strings
| 8haskell
| kr8h0 |
--raw-input | -R:: each line of input is converted to a JSON string;
--ascii-output | -a:: every non-ASCII character that would otherwise
be sent to output is translated to an equivalent
ASCII escape sequence;
--raw-output | -r:: output strings as raw strings, e.g. "a\nb" is
output as: | 92Unicode strings
| 9java
| 42e58 |
import Control.Lens ((.~), ix, (&))
import Data.Numbers.Primes (isPrime)
import Data.List (find, intercalate)
import Data.Char (intToDigit)
import Data.Maybe (mapMaybe)
import Data.List.Split (chunksOf)
import Text.Printf (printf)
isUnprimable :: Int -> Bool
isUnprimable = all (not . isPrime) . swapdigits
swapdigits :: Int -> [Int]
swapdigits n = map read $ go $ pred $ length digits
where
digits = show n
go (-1) = []
go n'' = map (\x -> digits & (ix n'') .~ intToDigit x) [0..9] <> go (pred n'')
unPrimeable :: [Int]
unPrimeable = filter isUnprimable [1..]
main :: IO ()
main = do
printf "First 35 unprimeable numbers:\n%s\n\n" $ show $ take 35 unPrimeable
printf "600th unprimeable number:%d\n\n" $ unPrimeable !! 599
mapM_ (uncurry (printf "Lowest unprimeable number ending with%d:%10s\n")) $ mapMaybe lowest [0..9]
where
thousands = reverse . intercalate "," . chunksOf 3 . reverse
lowest n = do
x <- find (\x -> x `mod` 10 == n) unPrimeable
pure (n, thousands $ show x) | 88Unprimeable numbers
| 8haskell
| v9w2k |
= 1
= + 1
print() | 87Unicode variable names
| 1lua
| n04i8 |
#[derive(Debug)]
struct Vector {
x: f64,
y: f64,
z: f64,
}
impl Vector {
fn new(x: f64, y: f64, z: f64) -> Self {
Vector {
x: x,
y: y,
z: z,
}
}
fn dot_product(&self, other: &Vector) -> f64 {
(self.x * other.x) + (self.y * other.y) + (self.z * other.z)
}
fn cross_product(&self, other: &Vector) -> Vector {
Vector::new(self.y * other.z - self.z * other.y,
self.z * other.x - self.x * other.z,
self.x * other.y - self.y * other.x)
}
fn scalar_triple_product(&self, b: &Vector, c: &Vector) -> f64 {
self.dot_product(&b.cross_product(&c))
}
fn vector_triple_product(&self, b: &Vector, c: &Vector) -> Vector {
self.cross_product(&b.cross_product(&c))
}
}
fn main(){
let a = Vector::new(3.0, 4.0, 5.0);
let b = Vector::new(4.0, 3.0, 5.0);
let c = Vector::new(-5.0, -12.0, -13.0);
println!("a . b = {}", a.dot_product(&b));
println!("a x b = {:?}", a.cross_product(&b));
println!("a . (b x c) = {}", a.scalar_triple_product(&b, &c));
println!("a x (b x c) = {:?}", a.vector_triple_product(&b, &c));
} | 72Vector products
| 15rust
| 0wesl |
use strict;
our $var;
print "var contains an undefined value at first check\n" unless defined $var;
$var = "Chocolate";
print "var contains an undefined value at second check\n" unless defined $var;
$var = undef;
undef($var);
print "var contains an undefined value at third check\n" unless defined $var;
$var = 42;
print "var contains an undefined value at fourth check\n" unless defined $var;
print "Done\n"; | 85Undefined values
| 2perl
| lyxc5 |
null | 92Unicode strings
| 11kotlin
| lykcp |
static int nextInt(int size) {
return rand() % size;
}
static bool cylinder[6];
static void rshift() {
bool t = cylinder[5];
int i;
for (i = 4; i >= 0; i--) {
cylinder[i + 1] = cylinder[i];
}
cylinder[0] = t;
}
static void unload() {
int i;
for (i = 0; i < 6; i++) {
cylinder[i] = false;
}
}
static void load() {
while (cylinder[0]) {
rshift();
}
cylinder[0] = true;
rshift();
}
static void spin() {
int lim = nextInt(6) + 1;
int i;
for (i = 1; i < lim; i++) {
rshift();
}
}
static bool fire() {
bool shot = cylinder[0];
rshift();
return shot;
}
static int method(const char *s) {
unload();
for (; *s != '\0'; s++) {
switch (*s) {
case 'L':
load();
break;
case 'S':
spin();
break;
case 'F':
if (fire()) {
return 1;
}
break;
}
}
return 0;
}
static void append(char *out, const char *txt) {
if (*out != '\0') {
strcat(out, );
}
strcat(out, txt);
}
static void mstring(const char *s, char *out) {
for (; *s != '\0'; s++) {
switch (*s) {
case 'L':
append(out, );
break;
case 'S':
append(out, );
break;
case 'F':
append(out, );
break;
}
}
}
static void test(char *src) {
char buffer[41] = ;
const int tests = 100000;
int sum = 0;
int t;
double pc;
for (t = 0; t < tests; t++) {
sum += method(src);
}
mstring(src, buffer);
pc = 100.0 * sum / tests;
printf(, buffer, pc);
}
int main() {
srand(time(0));
test();
test();
test();
test();
return 0;
} | 94Two bullet roulette
| 5c
| v9k2o |
null | 86Unix/ls
| 11kotlin
| oq58z |
case class Vector3D(x:Double, y:Double, z:Double) {
def dot(v:Vector3D):Double=x*v.x + y*v.y + z*v.z;
def cross(v:Vector3D)=Vector3D(y*v.z - z*v.y, z*v.x - x*v.z, x*v.y - y*v.x)
def scalarTriple(v1:Vector3D, v2:Vector3D)=this dot (v1 cross v2)
def vectorTriple(v1:Vector3D, v2:Vector3D)=this cross (v1 cross v2)
}
object VectorTest {
def main(args:Array[String])={
val a=Vector3D(3,4,5)
val b=Vector3D(4,3,5)
val c=Vector3D(-5,-12,-13)
println(" a . b: " + (a dot b))
println(" a x b: " + (a cross b))
println("a . (b x c): " + (a scalarTriple(b, c)))
println("a x (b x c): " + (a vectorTriple(b, c)))
}
} | 72Vector products
| 16scala
| isqox |
<?php
if (!isset($var))
echo ;
$var = ;
if (!isset($var))
echo ;
unset($var);
if (!isset($var))
echo ;
$var = 42;
if (!isset($var))
echo ;
echo ;
?> | 85Undefined values
| 12php
| qa2x3 |
public class UnprimeableNumbers {
private static int MAX = 10_000_000;
private static boolean[] primes = new boolean[MAX];
public static void main(String[] args) {
sieve();
System.out.println("First 35 unprimeable numbers:");
displayUnprimeableNumbers(35);
int n = 600;
System.out.printf("%nThe%dth unprimeable number =%,d%n%n", n, nthUnprimeableNumber(n));
int[] lowest = genLowest();
System.out.println("Least unprimeable number that ends in:");
for ( int i = 0 ; i <= 9 ; i++ ) {
System.out.printf("%d is%,d%n", i, lowest[i]);
}
}
private static int[] genLowest() {
int[] lowest = new int[10];
int count = 0;
int test = 1;
while ( count < 10 ) {
test++;
if ( unPrimable(test) && lowest[test % 10] == 0 ) {
lowest[test % 10] = test;
count++;
}
}
return lowest;
}
private static int nthUnprimeableNumber(int maxCount) {
int test = 1;
int count = 0;
int result = 0;
while ( count < maxCount ) {
test++;
if ( unPrimable(test) ) {
count++;
result = test;
}
}
return result;
}
private static void displayUnprimeableNumbers(int maxCount) {
int test = 1;
int count = 0;
while ( count < maxCount ) {
test++;
if ( unPrimable(test) ) {
count++;
System.out.printf("%d ", test);
}
}
System.out.println();
}
private static boolean unPrimable(int test) {
if ( primes[test] ) {
return false;
}
String s = test + "";
for ( int i = 0 ; i < s.length() ; i++ ) {
for ( int j = 0 ; j <= 9 ; j++ ) {
if ( primes[Integer.parseInt(replace(s, i, j))] ) {
return false;
}
}
}
return true;
}
private static String replace(String str, int position, int value) {
char[] sChar = str.toCharArray();
sChar[position] = (char) value;
return str.substring(0, position) + value + str.substring(position + 1);
}
private static final void sieve() { | 88Unprimeable numbers
| 9java
| ytk6g |
require("lfs")
for file in lfs.dir(".") do print(file) end | 86Unix/ls
| 1lua
| is4ot |
bool isPrime(int64_t n) {
int64_t i;
if (n < 2) return false;
if (n % 2 == 0) return n == 2;
if (n % 3 == 0) return n == 3;
if (n % 5 == 0) return n == 5;
if (n % 7 == 0) return n == 7;
if (n % 11 == 0) return n == 11;
if (n % 13 == 0) return n == 13;
if (n % 17 == 0) return n == 17;
if (n % 19 == 0) return n == 19;
for (i = 23; i * i <= n; i += 2) {
if (n % i == 0) return false;
}
return true;
}
int countTwinPrimes(int limit) {
int count = 0;
int64_t p3 = true, p2 = true, p1 = false;
int64_t i;
for (i = 5; i <= limit; i++) {
p3 = p2;
p2 = p1;
p1 = isPrime(i);
if (p3 && p1) {
count++;
}
}
return count;
}
void test(int limit) {
int count = countTwinPrimes(limit);
printf(, limit, count);
}
int main() {
test(10);
test(100);
test(1000);
test(10000);
test(100000);
test(1000000);
test(10000000);
test(100000000);
return 0;
} | 95Twin primes
| 5c
| 93gm1 |
Number.prototype.isPrime = function() {
let i = 2, num = this;
if (num == 0 || num == 1) return false;
if (num == 2) return true;
while (i <= Math.ceil(Math.sqrt(num))) {
if (num % i == 0) return false;
i++;
}
return true;
} | 88Unprimeable numbers
| 10javascript
| 2melr |
use utf8;
my $ = 1;
$++;
print $, "\n"; | 87Unicode variable names
| 2perl
| ruogd |
package main
import (
"fmt"
"math/rand"
"strings"
"time"
)
var cylinder = [6]bool{}
func rshift() {
t := cylinder[5]
for i := 4; i >= 0; i-- {
cylinder[i+1] = cylinder[i]
}
cylinder[0] = t
}
func unload() {
for i := 0; i < 6; i++ {
cylinder[i] = false
}
}
func load() {
for cylinder[0] {
rshift()
}
cylinder[0] = true
rshift()
}
func spin() {
var lim = 1 + rand.Intn(6)
for i := 1; i < lim; i++ {
rshift()
}
}
func fire() bool {
shot := cylinder[0]
rshift()
return shot
}
func method(s string) int {
unload()
for _, c := range s {
switch c {
case 'L':
load()
case 'S':
spin()
case 'F':
if fire() {
return 1
}
}
}
return 0
}
func mstring(s string) string {
var l []string
for _, c := range s {
switch c {
case 'L':
l = append(l, "load")
case 'S':
l = append(l, "spin")
case 'F':
l = append(l, "fire")
}
}
return strings.Join(l, ", ")
}
func main() {
rand.Seed(time.Now().UnixNano())
tests := 100000
for _, m := range []string{"LSLSFSF", "LSLSFF", "LLSFSF", "LLSFF"} {
sum := 0
for t := 1; t <= tests; t++ {
sum += method(m)
}
pc := float64(sum) * 100 / float64(tests)
fmt.Printf("%-40s produces%6.3f%% deaths.\n", mstring(m), pc)
}
} | 94Two bullet roulette
| 0go
| sezqa |
<?php
$ = 1;
++$;
echo $; | 87Unicode variable names
| 12php
| d8gn8 |
let Pistol = function(method) {
this.fired = false;
this.cylinder = new Array(6).fill(false);
this.trigger = 0;
this.rshift = function() {
this.trigger = this.trigger == 0 ? 5 : this.trigger-1;
}
this.load = function() {
while (this.cylinder[this.trigger]) this.rshift();
this.cylinder[this.trigger] = true;
this.rshift();
} | 94Two bullet roulette
| 10javascript
| mzgyv |
try: name
except NameError: print
name =
try: name
except NameError: print
del name
try: name
except NameError: print
name = 42
try: name
except NameError: print
print | 85Undefined values
| 3python
| 2mqlz |
>>> x = 1
>>> x += 1
>>> print(x)
2
>>> | 87Unicode variable names
| 3python
| 75irm |
f <- function(``=1) ``+1
f(1) | 87Unicode variable names
| 13r
| 5lsuy |
package main
import (
"fmt"
"math/rand"
)
const samples = 1e6
func main() {
fmt.Println("Generator 1 count 0 count % 1 count")
for n := 3; n <= 6; n++ { | 90Unbias a random generator
| 0go
| rusgm |
import kotlin.random.Random
val cylinder = Array(6) { false }
fun rShift() {
val t = cylinder[cylinder.size - 1]
for (i in (0 until cylinder.size - 1).reversed()) {
cylinder[i + 1] = cylinder[i]
}
cylinder[0] = t
}
fun unload() {
for (i in cylinder.indices) {
cylinder[i] = false
}
}
fun load() {
while (cylinder[0]) {
rShift()
}
cylinder[0] = true
rShift()
}
fun spin() {
val lim = Random.nextInt(0, 6) + 1
for (i in 1..lim) {
rShift()
}
}
fun fire(): Boolean {
val shot = cylinder[0]
rShift()
return shot
}
fun method(s: String): Int {
unload()
for (c in s) {
when (c) {
'L' -> {
load()
}
'S' -> {
spin()
}
'F' -> {
if (fire()) {
return 1
}
}
}
}
return 0
}
fun mString(s: String): String {
val buf = StringBuilder()
fun append(txt: String) {
if (buf.isNotEmpty()) {
buf.append(", ")
}
buf.append(txt)
}
for (c in s) {
when (c) {
'L' -> {
append("load")
}
'S' -> {
append("spin")
}
'F' -> {
append("fire")
}
}
}
return buf.toString()
}
fun test(src: String) {
val tests = 100000
var sum = 0
for (t in 0..tests) {
sum += method(src)
}
val str = mString(src)
val pc = 100.0 * sum / tests
println("%-40s produces%6.3f%% deaths.".format(str, pc))
}
fun main() {
test("LSLSFSF");
test("LSLSFF");
test("LLSFSF");
test("LLSFF");
} | 94Two bullet roulette
| 11kotlin
| oqy8z |
opendir my $handle, '.' or die "Couldnt open current directory: $!";
while (readdir $handle) {
print "$_\n";
}
closedir $handle; | 86Unix/ls
| 2perl
| gvo4e |
exists("x") | 85Undefined values
| 13r
| mzay4 |
use utf8; | 92Unicode strings
| 2perl
| qa3x6 |
private const val MAX = 10000000
private val primes = BooleanArray(MAX)
fun main() {
sieve()
println("First 35 unprimeable numbers:")
displayUnprimeableNumbers(35)
val n = 600
println()
println("The ${n}th unprimeable number = ${nthUnprimeableNumber(n)}")
println()
val lowest = genLowest()
println("Least unprimeable number that ends in:")
for (i in 0..9) {
println(" $i is ${lowest[i]}")
}
}
private fun genLowest(): IntArray {
val lowest = IntArray(10)
var count = 0
var test = 1
while (count < 10) {
test++
if (unPrimable(test) && lowest[test % 10] == 0) {
lowest[test % 10] = test
count++
}
}
return lowest
}
private fun nthUnprimeableNumber(maxCount: Int): Int {
var test = 1
var count = 0
var result = 0
while (count < maxCount) {
test++
if (unPrimable(test)) {
count++
result = test
}
}
return result
}
private fun displayUnprimeableNumbers(maxCount: Int) {
var test = 1
var count = 0
while (count < maxCount) {
test++
if (unPrimable(test)) {
count++
print("$test ")
}
}
println()
}
private fun unPrimable(test: Int): Boolean {
if (primes[test]) {
return false
}
val s = test.toString() + ""
for (i in s.indices) {
for (j in 0..9) {
if (primes[replace(s, i, j).toInt()]) {
return false
}
}
}
return true
}
private fun replace(str: String, position: Int, value: Int): String {
val sChar = str.toCharArray()
sChar[position] = value.toChar()
return str.substring(0, position) + value + str.substring(position + 1)
}
private fun sieve() { | 88Unprimeable numbers
| 11kotlin
| fogdo |
import Control.Monad.Random
import Control.Monad
import Text.Printf
randN :: MonadRandom m => Int -> m Int
randN n = fromList [(0, fromIntegral n-1), (1, 1)] | 90Unbias a random generator
| 8haskell
| 0w9s7 |
use strict;
use warnings;
use feature 'say';
my @cyl;
my $shots = 6;
sub load {
push @cyl, shift @cyl while $cyl[1];
$cyl[1] = 1;
push @cyl, shift @cyl
}
sub spin { push @cyl, shift @cyl for 0 .. int rand @cyl }
sub fire { push @cyl, shift @cyl; $cyl[0] }
sub LSLSFSF {
@cyl = (0) x $shots;
load, spin, load, spin;
return 1 if fire;
spin;
fire
}
sub LSLSFF {
@cyl = (0) x $shots;
load, spin, load, spin;
fire or fire
}
sub LLSFSF {
@cyl = (0) x $shots;
load, load, spin;
return 1 if fire;
spin;
fire
}
sub LLSFF {
@cyl = (0) x $shots;
load, load, spin;
fire or fire
}
my $trials = 10000;
for my $ref (<LSLSFSF LSLSFF LLSFSF LLSFF>) {
no strict 'refs';
my $total = 0;
$total += &$ref for 1..$trials;
printf "%7s%.2f%%\n", $ref, $total / $trials * 100;
} | 94Two bullet roulette
| 2perl
| gva4e |
<?php
foreach(scandir('.') as $fileName){
echo $fileName.;
} | 86Unix/ls
| 12php
| n0gig |
u = 'abcd'
print(ord(u[-1])) | 92Unicode strings
| 3python
| se6q9 |
null | 88Unprimeable numbers
| 1lua
| tirfn |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.