code
stringlengths
1
46.1k
label
class label
1.18k classes
domain_label
class label
21 classes
index
stringlengths
4
5
public class VisualizeTree { public static void main(String[] args) { BinarySearchTree tree = new BinarySearchTree(); tree.insert(100); for (int i = 0; i < 20; i++) tree.insert((int) (Math.random() * 200)); tree.display(); } } class BinarySearchTree { private No...
57Visualize a tree
9java
1knp2
dir("/foo/bar", "mp3")
53Walk a directory/Non-recursively
13r
vcw27
var fso = new ActiveXObject("Scripting.FileSystemObject"); function walkDirectoryTree(folder, folder_name, re_pattern) { WScript.Echo("Files in " + folder_name + " matching '" + re_pattern + "':"); walkDirectoryFilter(folder.files, re_pattern); var subfolders = folder.SubFolders; WScript.Echo("Folders...
58Walk a directory/Recursively
10javascript
m3ryv
def invoke(String cmd) { println(cmd.execute().text) } invoke("xrandr -q") Thread.sleep(3000) invoke("xrandr -s 1024x768") Thread.sleep(3000) invoke("xrandr -s 1366x768")
63Video display modes
7groovy
yz26o
null
59Verify distribution uniformity/Naive
11kotlin
qetx1
import static java.lang.Math.pow; import java.util.Arrays; import static java.util.Arrays.stream; import org.apache.commons.math3.special.Gamma; public class Test { static double x2Dist(double[] data) { double avg = stream(data).sum() / data.length; double sqs = stream(data).reduce(0, (a, b) -> a ...
62Verify distribution uniformity/Chi-squared test
9java
3flzg
<!doctype html> <html id="doc"> <head><meta charset="utf-8"/> <title>Stuff</title> <script type="application/javascript"> function gid(id) { return document.getElementById(id); } function ce(tag, cls, parent_node) { var e = document.createElement(tag); e.className = cls; if (parent_node) parent_node....
57Visualize a tree
10javascript
qe3x8
null
58Walk a directory/Recursively
11kotlin
osm8z
null
56Water collected between towers
11kotlin
lmbcp
null
63Video display modes
11kotlin
52jua
print("\33[?3h")
63Video display modes
1lua
4vh5c
void to_seq(uint64_t x, uint8_t *out) { int i, j; for (i = 9; i > 0; i--) { if (x & 127ULL << i * 7) break; } for (j = 0; j <= i; j++) out[j] = ((x >> ((i - j) * 7)) & 127) | 128; out[i] ^= 128; } uint64_t from_seq(uint8_t *in) { uint64_t r = 0; do { r = (r << 7) | (uint64_t)(*in & 127); } while (*in++...
64Variable-length quantity
5c
3f9za
int_least32_t foo;
65Variable size/Set
5c
r5hg7
null
62Verify distribution uniformity/Chi-squared test
11kotlin
n86ij
function waterCollected(i,tower) local length = 0 for _ in pairs(tower) do length = length + 1 end local wu = 0 repeat local rht = length - 1 while rht >= 0 do if tower[rht + 1] > 0 then break end rht = rht - 1 end ...
56Water collected between towers
1lua
29pl3
$| = 1; my @info = `xrandr -q`; $info[0] =~ /current (\d+) x (\d+)/; my $current = "$1x$2"; my @resolutions; for (@info) { push @resolutions, $1 if /^\s+(\d+x\d+)/ } system("xrandr -s $resolutions[-1]"); print "Current resolution $resolutions[-1].\n"; for (reverse 1 .. 9) { print "\rChanging back in $_ secon...
63Video display modes
2perl
ost8x
import win32api import win32con import pywintypes devmode=pywintypes.DEVMODEType() devmode.PelsWidth=640 devmode.PelsHeight=480 devmode.Fields=win32con.DM_PELSWIDTH | win32con.DM_PELSHEIGHT win32api.ChangeDisplaySettings(devmode,0)
63Video display modes
3python
i0zof
typedef struct{ double x,y; }vector; vector initVector(double r,double theta){ vector c; c.x = r*cos(theta); c.y = r*sin(theta); return c; } vector addVector(vector a,vector b){ vector c; c.x = a.x + b.x; c.y = a.y + b.y; return c; } vector subtractVector(vector a,vector b){ vector c; c.x = a.x - b.x...
66Vector
5c
8qi04
null
57Visualize a tree
11kotlin
jgs7r
Dir.glob('*') { |file| puts file } Dir.glob( File.join('/foo/bar', '*') ) { |file| puts file } def file_match(pattern=/\.txt/, path='.') Dir[File.join(path,'*')].each do |file| puts file if file =~ pattern end end
53Walk a directory/Non-recursively
14ruby
74ori
local lfs = require("lfs")
58Walk a directory/Recursively
1lua
i09ot
package main import "fmt" type vkey string func newVigenre(key string) (vkey, bool) { v := vkey(upperOnly(key)) return v, len(v) > 0
61Vigenère cipher
0go
os38q
function makeTree(v,ac) if type(ac) == "table" then return {value=v,children=ac} else return {value=v} end end function printTree(t,last,prefix) if last == nil then printTree(t, false, '') else local current = '' local next = '' if last then ...
57Visualize a tree
1lua
hr0j8
extern crate docopt; extern crate regex; extern crate rustc_serialize; use docopt::Docopt; use regex::Regex; const USAGE: &'static str = " Usage: rosetta <pattern> Walks the directory tree starting with the current working directory and print filenames matching <pattern>. "; #[derive(Debug, RustcDecodable)] struct ...
53Walk a directory/Non-recursively
15rust
jgi72
object VideoDisplayModes extends App { import java.util.Scanner def runSystemCommand(command: String) { val proc = Runtime.getRuntime.exec(command) val a: Unit = { val a = new Scanner(proc.getInputStream) while (a.hasNextLine) println(a.nextLine()) } proc.waitFor() println() }
63Video display modes
16scala
3fczy
sub roll7 { 1+int rand(7) } sub roll5 { 1+int rand(5) } sub roll7_5 { while(1) { my $d7 = (5*&roll5 + &roll5 - 6) % 8; return $d7 if $d7; } } my $threshold = 5; print dist( $_, $threshold, \&roll7 ) for <1001 1000006>; print dist( $_, $threshold, \&roll7_5 ) for <1001 1000006>; sub dist { my($n, $thr...
59Verify distribution uniformity/Naive
2perl
vck20
package main import ( "fmt" "unsafe" ) func main() { i := 5
65Variable size/Set
0go
n8ti1
import Data.Int import Foreign.Storable task name value = putStrLn $ name ++ ": " ++ show (sizeOf value) ++ " byte(s)" main = do let i8 = 0::Int8 let i16 = 0::Int16 let i32 = 0::Int32 let i64 = 0::Int64 let int = 0::Int task "Int8" i8 task "Int16" i16 task "Int32" i32 task "Int64" i64 task "Int" ...
65Variable size/Set
8haskell
ulgv2
require_relative 'raster_graphics' class ColourPixel < Pixel def initialize(x, y, colour) @colour = colour super x, y end attr_accessor :colour def distance_to(px, py) Math.hypot(px - x, py - y) end end width = 300 height = 200 npoints = 20 pixmap = Pixmap.new(width, height) @bases = npoints.t...
54Voronoi diagram
14ruby
yzh6n
import Data.Char import Text.Printf crypt f key = map toLetter . zipWith f (cycle key) where toLetter = chr . (+) (ord 'A') enc k c = (ord k + ord c) `mod` 26 dec k c = (ord c - ord k) `mod` 26 encrypt = crypt enc decrypt = crypt dec convert = map toUpper . filter isLetter main :: IO () main = do let key ...
61Vigenère cipher
8haskell
297ll
import java.io.File val dir = new File("/foo/bar").list() dir.filter(file => file.endsWith(".mp3")).foreach(println)
53Walk a directory/Non-recursively
16scala
bjfk6
null
65Variable size/Set
11kotlin
tn6f0
extern crate piston; extern crate opengl_graphics; extern crate graphics; extern crate touch_visualizer; #[cfg(feature = "include_sdl2")] extern crate sdl2_window; extern crate getopts; extern crate voronoi; extern crate rand; use touch_visualizer::TouchVisualizer; use opengl_graphics::{ GlGraphics, OpenGL }; use gr...
54Voronoi diagram
15rust
m3kya
use List::Util qw(sum reduce); use constant pi => 3.14159265; sub incomplete_G_series { my($s, $z) = @_; my $n = 10; push @numers, $z**$_ for 1..$n; my @denoms = $s+1; push @denoms, $denoms[-1]*($s+$_) for 2..$n; my $M = 1; $M += $numers[$_-1]/$denoms[$_-1] for 1..$n; $z**$s / $s * exp(...
62Verify distribution uniformity/Chi-squared test
2perl
741rh
use Modern::Perl; use List::Util qw{ min max sum }; sub water_collected { my @t = map { { TOWER => $_, LEFT => 0, RIGHT => 0, LEVEL => 0 } } @_; my ( $l, $r ) = ( 0, 0 ); $_->{LEFT} = ( $l = max( $l, $_->{TOWER} ) ) for @t; $_->{RIGHT} = ( $r = max( $r, $_->{TOWER} ) ) for reverse @t; $_->{LEVEL}...
56Water collected between towers
2perl
qe6x6
package main import ( "fmt" "encoding/binary" ) func main() { buf := make([]byte, binary.MaxVarintLen64) for _, x := range []int64{0x200000, 0x1fffff} { v := buf[:binary.PutVarint(buf, x)] fmt.Printf("%d encodes into%d bytes:%x\n", x, len(v), v) x, _ = binary.Varint(v) ...
64Variable-length quantity
0go
bjekh
import java.awt.geom.Ellipse2D import java.awt.image.BufferedImage import java.awt.{Color, Graphics, Graphics2D} import scala.math.sqrt object Voronoi extends App { private val (cells, dim) = (100, 1000) private val rand = new scala.util.Random private val color = Vector.fill(cells)(rand.nextInt(0x1000000)) p...
54Voronoi diagram
16scala
lm1cq
from collections import Counter from pprint import pprint as pp def distcheck(fn, repeats, delta): '''\ Bin the answers to fn() and check bin counts are within +/- delta% of repeats/bincount''' bin = Counter(fn() for i in range(repeats)) target = repeats deltacount = int(delta / 100. * target)...
59Verify distribution uniformity/Naive
3python
ulbvd
final RADIX = 7 final MASK = 2**RADIX - 1 def octetify = { n -> def octets = [] for (def i = n; i != 0; i >>>= RADIX) { octets << ((byte)((i & MASK) + (octets.empty ? 0: MASK + 1))) } octets.reverse() } def deoctetify = { octets -> octets.inject(0) { long n, octet -> (n << RADIX) +...
64Variable-length quantity
7groovy
r5kgh
import Numeric (readOct, showOct) import Data.List (intercalate) to :: Int -> String to = flip showOct "" from :: String -> Int from = fst . head . readOct main :: IO () main = mapM_ (putStrLn . intercalate " <-> " . (pure (:) <*> to <*> (return . show . from . to))) [2097152, 2097151]
64Variable-length quantity
8haskell
do3n4
with javascript_semantics requires("1.0.0") include mpfr.e mpfr pi = mpfr_init(0,-121) -- 120 dp, +1 for the "3." mpfr_const_pi(pi) printf(1,"PI with 120 decimals:%s\n\n",mpfr_get_fixed(pi,120))
65Variable size/Set
2perl
k71hc
import math import random def GammaInc_Q( a, x): a1 = a-1 a2 = a-2 def f0( t ): return t**a1*math.exp(-t) def df0(t): return (a1-t)*t**a2*math.exp(-t) y = a1 while f0(y)*(x-y) >2.0e-8 and y < x: y += .3 if y > x: y = x h = 3.0e-4 n = int(y/h) h = y/n hh = ...
62Verify distribution uniformity/Chi-squared test
3python
jga7p
public class VigenereCipher { public static void main(String[] args) { String key = "VIGENERECIPHER"; String ori = "Beware the Jabberwock, my son! The jaws that bite, the claws that catch!"; String enc = encrypt(ori, key); System.out.println(enc); System.out.println(decrypt(e...
61Vigenère cipher
9java
6tv3z
use warnings; use strict; use utf8; use open OUT => ':utf8', ':std'; sub parse { my ($tree) = shift; if (my ($root, $children) = $tree =~ /^(.+?)\((.*)\)$/) { my $depth = 0; for my $pos (0 .. length($children) - 1) { my $char = \substr $children, $pos, 1; if (0 == $dept...
57Visualize a tree
2perl
tnufg
distcheck <- function(fn, repetitions=1e4, delta=3) { if(is.character(fn)) { fn <- get(fn) } if(!is.function(fn)) { stop("fn is not a function") } samp <- fn(n=repetitions) counts <- table(samp) expected <- repetitions/length(counts) lbound <- expected * (1 - 0.01*delta) ...
59Verify distribution uniformity/Naive
13r
cy795
dset1=c(199809,200665,199607,200270,199649) dset2=c(522573,244456,139979,71531,21461) chi2IsUniform<-function(dataset,significance=0.05){ chi2IsUniform=(chisq.test(dataset)$p.value>significance) } for (ds in list(dset1,dset2)){ print(c("Data set:",ds)) print(chisq.test(ds)) print(paste("uniform?",chi2IsUnifor...
62Verify distribution uniformity/Chi-squared test
13r
4vk5y
null
61Vigenère cipher
10javascript
lmrcf
public class VLQCode { public static byte[] encode(long n) { int numRelevantBits = 64 - Long.numberOfLeadingZeros(n); int numBytes = (numRelevantBits + 6) / 7; if (numBytes == 0) numBytes = 1; byte[] output = new byte[numBytes]; for (int i = numBytes - 1; i >= 0; i--) { int curBy...
64Variable-length quantity
9java
swiq0
numeric digits 100 z = 12345678901111111112222222222333333333344444444445555555555.66 n =-12345678901111111112222222222333333333344444444445555555555.66
65Variable size/Set
3python
bjakr
println(s"A Byte variable has a range of: ${Byte.MinValue} to ${Byte.MaxValue}") println(s"A Short variable has a range of: ${Short.MinValue} to ${Short.MaxValue}") println(s"An Int variable has a range of: ${Int.MinValue} to ${Int.MaxValue}") println(s"A Long variable has a range of: ${Long.MinValue} to...
65Variable size/Set
16scala
xa0wg
use File::Find qw(find); my $dir = '.'; my $pattern = 'foo'; my $callback = sub { print $File::Find::name, "\n" if /$pattern/ }; find $callback, $dir;
58Walk a directory/Recursively
2perl
gue4e
def water_collected(tower): N = len(tower) highest_left = [0] + [max(tower[:n]) for n in range(1,N)] highest_right = [max(tower[n:N]) for n in range(1,N)] + [0] water_level = [max(min(highest_left[n], highest_right[n]) - tower[n], 0) for n in range(N)] print(, highest_left) print(, highe...
56Water collected between towers
3python
swyq9
def distcheck(n, delta=1) unless block_given? raise ArgumentError, end h = Hash.new(0) n.times {h[ yield ] += 1} target = 1.0 * n / h.length h.each do |key, value| if (value - target).abs > 0.01 * delta * n raise StandardError, end end puts h.sort.map{|k, v| } end if __F...
59Verify distribution uniformity/Naive
14ruby
4v15p
const RADIX = 7; const MASK = 2**RADIX - 1; const octetify = (n)=> { if (n >= 2147483648) { throw new RangeError("Variable Length Quantity not supported for numbers >= 2147483648"); } const octets = []; for (let i = n; i != 0; i >>>= RADIX) { octets.push((((i & MASK) + (octets.empty ? 0 : (MASK + 1))))); } o...
64Variable-length quantity
10javascript
n8ziy
void varstrings(int count, ...) { va_list args; va_start(args, count); while (count--) puts(va_arg(args, const char *)); va_end(args); } varstrings(5, , , , , );
67Variadic function
5c
sw0q5
printf(, sizeof(int));
68Variable size/Get
5c
oso80
package main import "fmt" type vector []float64 func (v vector) add(v2 vector) vector { r := make([]float64, len(v)) for i, vi := range v { r[i] = vi + v2[i] } return r } func (v vector) sub(v2 vector) vector { r := make([]float64, len(v)) for i, vi := range v { r[i] = vi - v...
66Vector
0go
52gul
function findFiles($dir = '.', $pattern = '/./'){ $prefix = $dir . '/'; $dir = dir($dir); while (false !== ($file = $dir->read())){ if ($file === '.' || $file === '..') continue; $file = $prefix . $file; if (is_dir($file)) findFiles($file, $pattern); if (preg_match($pattern, $file)){ echo $f...
58Walk a directory/Recursively
12php
n8cig
object DistrubCheck1 extends App { private def distCheck(f: () => Int, nRepeats: Int, delta: Double): Unit = { val counts = scala.collection.mutable.Map[Int, Int]() for (_ <- 0 until nRepeats) counts.updateWith(f()) { case Some(count) => Some(count + 1) case None => Some(1) } ...
59Verify distribution uniformity/Naive
16scala
jgx7i
int main() { int i, gprev = 0; int s[7] = {1, 2, 2, 3, 4, 4, 5}; for (i = 0; i < 7; ++i) { int curr = s[i]; int prev = 0; if (i > 0 && curr == prev) printf(, i); prev = curr; } for (i = 0; i < 7; ++i) { int curr = s[i]; if (i > 0 && curr ...
69Variable declaration reset
5c
1hbpj
null
64Variable-length quantity
11kotlin
abq13
import groovy.transform.EqualsAndHashCode @EqualsAndHashCode class Vector { private List<Number> elements Vector(List<Number> e ) { if (!e) throw new IllegalArgumentException("A Vector must have at least one element.") if (!e.every { it instanceof Number }) throw new IllegalArgumentException("E...
66Vector
7groovy
cy29i
def gammaInc_Q(a, x) a1, a2 = a-1, a-2 f0 = lambda {|t| t**a1 * Math.exp(-t)} df0 = lambda {|t| (a1-t) * t**a2 * Math.exp(-t)} y = a1 y += 0.3 while f0[y]*(x-y) > 2.0e-8 and y < x y = x if y > x h = 3.0e-4 n = (y/h).to_i h = y/n hh = 0.5 * h sum = 0 (n-1).step(0, -1) do |j| t = h * j ...
62Verify distribution uniformity/Chi-squared test
14ruby
k7whg
null
61Vigenère cipher
11kotlin
domnz
Python 3.2.3 (default, May 3 2012, 15:54:42) [GCC 4.6.3] on linux2 Type , or for more information. >>> help('pprint.pprint') Help on function pprint in pprint: pprint.pprint = pprint(object, stream=None, indent=1, width=80, depth=None) Pretty-print a Python object to a stream [default is sys.stdout]. >>> from...
57Visualize a tree
3python
zd5tt
(defn foo [& args] (doseq [a args] (println a))) (foo :bar :baz :quux) (apply foo [:bar :baz :quux])
67Variadic function
6clojure
n8dik
add (u,v) (x,y) = (u+x,v+y) minus (u,v) (x,y) = (u-x,v-y) multByScalar k (x,y) = (k*x,k*y) divByScalar (x,y) k = (x/k,y/k) main = do let vecA = (3.0,8.0) let (r,theta) = (3,pi/12) :: (Double,Double) let vecB = (r*(cos theta),r*(sin theta)) putStrLn $ "vecA = " ++ (show vecA) putStrLn $ "vecB = " +...
66Vector
8haskell
xasw4
use statrs::function::gamma::gamma_li; fn chi_distance(dataset: &[u32]) -> f64 { let expected = f64::from(dataset.iter().sum::<u32>()) / dataset.len() as f64; dataset .iter() .fold(0., |acc, &elt| acc + (elt as f64 - expected).powf(2.)) / expected } fn chi2_probability(dof: f64, distan...
62Verify distribution uniformity/Chi-squared test
15rust
bjxkx
import org.apache.commons.math3.special.Gamma.regularizedGammaQ object ChiSquare extends App { private val dataSets: Seq[Seq[Double]] = Seq( Seq(199809, 200665, 199607, 200270, 199649), Seq(522573, 244456, 139979, 71531, 21461) ) private def 2IsUniform(data: Seq[Double], significance: Double) ...
62Verify distribution uniformity/Chi-squared test
16scala
ab01n
package main import "fmt" func main() { s := []int{1, 2, 2, 3, 4, 4, 5}
69Variable declaration reset
0go
yt364
import java.util.Locale; public class Test { public static void main(String[] args) { System.out.println(new Vec2(5, 7).add(new Vec2(2, 3))); System.out.println(new Vec2(5, 7).sub(new Vec2(2, 3))); System.out.println(new Vec2(5, 7).mult(11)); System.out.println(new Vec2(5, 7).div(2...
66Vector
9java
bj1k3
def a(array) n=array.length left={} right={} left[0]=array[0] i=1 loop do break if i >=n left[i]=[left[i-1],array[i]].max i += 1 end right[n-1]=array[n-1] i=n-2 loop do break if i<0 right[i]=[right[i+1],array[i]].max i-=1 end i=0 water=0 loop do break if i>=n water+=[left[i],right[i]].min-array[i] i+=1 end pu...
56Water collected between towers
14ruby
8q901
public class VariableDeclarationReset { public static void main(String[] args) { int[] s = {1, 2, 2, 3, 4, 4, 5};
69Variable declaration reset
9java
5lvuf
<!DOCTYPE html> <html lang="en" > <head> <meta charset="utf-8"/> <meta name="viewport" content="width=device-width, initial-scale=1"/> <title>variable declaration reset</title> </head> <body> <script> "use strict"; let s = [1, 2, 2, 3, 4, 4, 5]; for (let i=0; i<7; i+=1) { let curr = s[i], prev; if (i...
69Variable declaration reset
10javascript
j4r7n
typedef uint64_t xint; typedef unsigned long long ull; xint tens[20]; inline xint max(xint a, xint b) { return a > b ? a : b; } inline xint min(xint a, xint b) { return a < b ? a : b; } inline int ndigits(xint x) { int n = 0; while (x) n++, x /= 10; return n; } inline xint dtally(xint x) { xint t = 0; while (x)...
70Vampire number
5c
tinf4
use warnings; use strict; for my $testcase ( 0, 0xa, 123, 254, 255, 256, 257, 65534, 65535, 65536, 65537, 0x1fffff, 0x200000 ) { my @vlq = vlq_encode($testcase); printf "%8s%12s%8s\n", $testcase, ( join ':', @vlq ), vlq_decode(@vlq); } sub vlq_encode { my @vlq; my $binary = spr...
64Variable-length quantity
2perl
96vmn
function Encrypt( _msg, _key ) local msg = { _msg:upper():byte( 1, -1 ) } local key = { _key:upper():byte( 1, -1 ) } local enc = {} local j, k = 1, 1 for i = 1, #msg do if msg[i] >= string.byte('A') and msg[i] <= string.byte('Z') then enc[k] = ( msg[i] + key[j] - 2*s...
61Vigenère cipher
1lua
fi9dp
root = BinaryTreeNode.from_array [1, [2, [4, 7], [5]], [3, [6, [8], [9]]]]
57Visualize a tree
14ruby
6tg3t
extern crate rustc_serialize; extern crate term_painter; use rustc_serialize::json; use std::fmt::{Debug, Display, Formatter, Result}; use term_painter::ToStyle; use term_painter::Color::*; type NodePtr = Option<usize>; #[derive(Debug, PartialEq, Clone, Copy)] enum Side { Left, Right, Up, } #[derive(Deb...
57Visualize a tree
15rust
yzr68
use std::cmp::min; fn getfill(pattern: &[usize]) -> usize { let mut total = 0; for (idx, val) in pattern.iter().enumerate() { let l_peak = pattern[..idx].iter().max(); let r_peak = pattern[idx + 1..].iter().max(); if l_peak.is_some() && r_peak.is_some() { let peak = min(l_pe...
56Water collected between towers
15rust
osc83
@s = <1 2 2 3 4 4 5>; for ($i = 0; $i < 7; $i++) { $curr = $s[$i]; if ($i > 1 and $curr == $prev) { print "$i\n" } $prev = $curr; }
69Variable declaration reset
2perl
x1ew8
null
66Vector
11kotlin
r5jgo
from pathlib import Path for path in Path('.').rglob('*.*'): print(path)
58Walk a directory/Recursively
3python
r5wgq
dir("/bar/foo", "mp3",recursive=T)
58Walk a directory/Recursively
13r
ulpvx
import scala.collection.parallel.CollectionConverters.VectorIsParallelizable
56Water collected between towers
16scala
dovng
def tobits(n, _group=8, _sep='_', _pad=False): 'Express n as binary bits with separator' bits = '{0:b}'.format(n)[::-1] if _pad: bits = '{0:0{1}b}'.format(n, ((_group+len(bits)-1) answer = _sep.join(bits[i:i+_group] for i in ...
64Variable-length quantity
3python
cyu9q
import "unsafe" unsafe.Sizeof(x)
68Variable size/Get
0go
4v452
vector = {mt = {}} function vector.new (x, y) local new = {x = x or 0, y = y or 0} setmetatable(new, vector.mt) return new end function vector.mt.__add (v1, v2) return vector.new(v1.x + v2.x, v1.y + v2.y) end function vector.mt.__sub (v1, v2) return vector.new(v1.x - v2.x, v1.y - v2.y) end func...
66Vector
1lua
74hru
s = [1, 2, 2, 3, 4, 4, 5] for i in range(len(s)): curr = s[i] if i > 0 and curr == prev: print(i) prev = curr
69Variable declaration reset
3python
qawxi
(defn factor-pairs [n] (for [x (range 2 (Math/sqrt n)) :when (zero? (mod n x))] [x (quot n x)])) (defn fangs [n] (let [dlen (comp count str) half (/ (dlen n) 2) halves? #(apply = (cons half (map dlen %))) digits #(sort (apply str %))] (filter #(and (halves? %) ...
70Vampire number
6clojure
mz3yq
import Foreign sizeOf (undefined :: Int) sizeOf (undefined :: Double) sizeOf (undefined :: Bool) sizeOf (undefined :: Ptr a)
68Variable size/Get
8haskell
qeqx9
int check_isin(char *a) { int i, j, k, v, s[24]; j = 0; for(i = 0; i < 12; i++) { k = a[i]; if(k >= '0' && k <= '9') { if(i < 2) return 0; s[j++] = k - '0'; } else if(k >= 'A' && k <= 'Z') { if(i == 11) return 0; k -= 'A' - 10; ...
71Validate International Securities Identification Number
5c
2mmlo
null
68Variable size/Get
11kotlin
747r4
null
56Water collected between towers
17swift
0xms6
typedef struct{ float i,j,k; }Vector; Vector a = {3, 4, 5},b = {4, 3, 5},c = {-5, -12, -13}; float dotProduct(Vector a, Vector b) { return a.i*b.i+a.j*b.j+a.k*b.k; } Vector crossProduct(Vector a,Vector b) { Vector c = {a.j*b.k - a.k*b.j, a.k*b.i - a.i*b.k, a.i*b.j - a.j*b.i}; return c; } float scalarTriplePro...
72Vector products
5c
pj7by
void vc(int n, int base, int *num, int *denom) { int p = 0, q = 1; while (n) { p = p * base + (n % base); q *= base; n /= base; } *num = p; *denom = q; while (p) { n = p; p = q % p; q = n; } *num /= q; *...
73Van der Corput sequence
5c
wpkec
[0x200000, 0x1fffff].each do |i| ber = [i].pack() hex = ber.unpack().collect {|c| % c}.join() printf , i, hex j = ber.unpack().first i == j or fail end
64Variable-length quantity
14ruby
294lw
object VlqCode { def encode(x:Long)={ val result=scala.collection.mutable.Stack[Byte]() result push (x&0x7f).toByte var l = x >>> 7 while(l>0){ result push ((l&0x7f)|0x80).toByte l >>>= 7 } result.toArray } def decode(a:Array[Byte])=a.foldLeft(0L)((r, b) => r<<7|b&0x7f) def...
64Variable-length quantity
16scala
4vj50
> s = "hello" > print(#s) 5 > t = { 1,2,3,4,5 } > print(#t) 5
68Variable size/Get
1lua
jgj71
<?php function printTree( array $tree , string $key = , string $stack = , $first = TRUE , $firstPadding = NULL ) { if ( gettype($tree) == ) { if($firstPadding === NULL) $firstPadding = ( count($tree)>1 )? : ; echo $key . PHP_EOL ; foreach ($tree as $key => $value) { i...
57Visualize a tree
12php
k78hv