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 Node root; private class Node { private int key; private Node left, right; Node(int k) { key = k; } } public boolean insert(int key) { if (root == null) root = new Node(key); else { Node n = root; Node parent; while (true) { if (n.key == key) return false; parent = n; boolean goLeft = key < n.key; n = goLeft ? n.left : n.right; if (n == null) { if (goLeft) { parent.left = new Node(key); } else { parent.right = new Node(key); } break; } } } return true; } public void display() { final int height = 5, width = 64; int len = width * height * 2 + 2; StringBuilder sb = new StringBuilder(len); for (int i = 1; i <= len; i++) sb.append(i < len - 2 && i % width == 0 ? "\n" : ' '); displayR(sb, width / 2, 1, width / 4, width, root, " "); System.out.println(sb); } private void displayR(StringBuilder sb, int c, int r, int d, int w, Node n, String edge) { if (n != null) { displayR(sb, c - d, r + 2, d / 2, w, n.left, " /"); String s = String.valueOf(n.key); int idx1 = r * w + c - (s.length() + 1) / 2; int idx2 = idx1 + s.length(); int idx3 = idx1 - w; if (idx2 < sb.length()) sb.replace(idx1, idx2, s).replace(idx3, idx3 + 2, edge); displayR(sb, c + d, r + 2, d / 2, w, n.right, "\\ "); } } }
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 in " + folder_name + " matching '" + re_pattern + "':"); walkDirectoryFilter(subfolders, re_pattern); WScript.Echo(); var en = new Enumerator(subfolders); while (! en.atEnd()) { var subfolder = en.item(); walkDirectoryTree(subfolder, folder_name + "/" + subfolder.name, re_pattern); en.moveNext(); } } function walkDirectoryFilter(items, re_pattern) { var e = new Enumerator(items); while (! e.atEnd()) { var item = e.item(); if (item.name.match(re_pattern)) WScript.Echo(item.name); e.moveNext(); } } walkDirectoryTree(dir, dir.name, '\\.txt$');
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 + pow((b - avg), 2)); return sqs / avg; } static double x2Prob(double dof, double distance) { return Gamma.regularizedGammaQ(dof / 2, distance / 2); } static boolean x2IsUniform(double[] data, double significance) { return x2Prob(data.length - 1.0, x2Dist(data)) > significance; } public static void main(String[] a) { double[][] dataSets = {{199809, 200665, 199607, 200270, 199649}, {522573, 244456, 139979, 71531, 21461}}; System.out.printf("%4s%12s %12s%8s %s%n", "dof", "distance", "probability", "Uniform?", "dataset"); for (double[] ds : dataSets) { int dof = ds.length - 1; double dist = x2Dist(ds); double prob = x2Prob(dof, dist); System.out.printf("%4d%12.3f %12.8f %5s %6s%n", dof, dist, prob, x2IsUniform(ds, 0.05) ? "YES" : "NO", Arrays.toString(ds)); } } }
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.appendChild(e); return e; } function dom_tree(id) { gid('tree').textContent = ""; gid('tree').appendChild(mktree(gid(id), null)); } function mktree(e, p) { var t = ce("div", "tree", p); var tog = ce("span", "toggle", t); var h = ce("span", "tag", t); if (e.tagName === undefined) { h.textContent = "#Text"; var txt = e.textContent; if (txt.length > 0 && txt.match(/\S/)) { h = ce("div", "txt", t); h.textContent = txt; } return t; } tog.textContent = ""; tog.onclick = function () { clicked(tog); } h.textContent = e.nodeName; var l = e.childNodes; for (var i = 0; i!= l.length; i++) mktree(l[i], t); return t; } function clicked(e) { var is_on = e.textContent == ""; e.textContent = is_on? "+": ""; e.parentNode.className = is_on? "tree-hide": "tree"; } </script> <style> #tree { white-space: pre; font-family: monospace; border: 1px solid } .tree > .tree-hide, .tree > .tree { margin-left: 2em; border-left: 1px dotted rgba(0,0,0,.2)} .tree-hide > .tree, .tree-hide > .tree-hide { display: none } .tag { color: navy } .tree-hide > .tag { color: maroon } .txt { color: gray; padding: 0 .5em; margin: 0 .5em 0 2em; border: 1px dotted rgba(0,0,0,.1) } .toggle { display: inline-block; width: 2em; text-align: center } </style> </head> <body> <article> <section> <h1>Headline</h1> Blah blah </section> <section> <h1>More headline</h1> <blockquote>Something something</blockquote> <section><h2>Nested section</h2> Somethin somethin list: <ul> <li>Apples</li> <li>Oranges</li> <li>Cetera Fruits</li> </ul> </section> </section> </article> <div id="tree"><a href="javascript:dom_tree('doc')">click me</a></div> </body> </html>
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++ & 128); return r; } int main() { uint8_t s[10]; uint64_t x[] = { 0x7f, 0x4000, 0, 0x3ffffe, 0x1fffff, 0x200000, 0x3311a1234df31413ULL}; int i, j; for (j = 0; j < sizeof(x)/8; j++) { to_seq(x[j], s); printf(, x[j]); i = 0; do { printf(, s[i]); } while ((s[i++] & 128)); printf(, from_seq(s)); } return 0; }
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 if rht < 0 then break end local bof = 0 local col = 0 while col <= rht do if tower[col + 1] > 0 then tower[col + 1] = tower[col + 1] - 1 bof = bof + 1 elseif bof > 0 then wu = wu + 1 end col = col + 1 end if bof < 2 then break end until false if wu == 0 then print(string.format("Block%d does not hold any water.", i)) else print(string.format("Block%d holds%d water units.", i, wu)) end end function main() local towers = { {1, 5, 3, 7, 2}, {5, 3, 7, 2, 6, 4, 5, 9, 1, 2}, {2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1}, {5, 5, 5, 5}, {5, 6, 7, 8}, {8, 7, 7, 6}, {6, 7, 10, 7, 6} } for i,tbl in pairs(towers) do waterCollected(i,tbl) end end main()
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 $_ seconds..."; sleep 1; } system("xrandr -s $current"); print "\rResolution returned to $current.\n";
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; c.y = a.y - b.y; return c; } vector multiplyVector(vector a,double b){ vector c; c.x = b*a.x; c.y = b*a.y; return c; } vector divideVector(vector a,double b){ vector c; c.x = a.x/b; c.y = a.y/b; return c; } void printVector(vector a){ printf(,a.x,140,(a.y>=0)?'+':'-',(a.y>=0)?a.y:fabs(a.y),150); } int main() { vector a = initVector(3,pi/6); vector b = initVector(5,2*pi/3); printf(); printVector(a); printf(); printVector(b); printf(); printVector(addVector(a,b)); printf(); printVector(subtractVector(a,b)); printf(); printVector(multiplyVector(a,3)); printf(); printVector(divideVector(b,2.5)); return 0; }
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 current = prefix .. '\\-' .. t.value next = prefix .. ' ' else current = prefix .. '|-' .. t.value next = prefix .. '| ' end print(current:sub(3)) if t.children ~= nil then for k,v in pairs(t.children) do printTree(v, k == #t.children, next) end end end end printTree( makeTree('A', { makeTree('B0', { makeTree('C1'), makeTree('C2', { makeTree('D', { makeTree('E1'), makeTree('E2'), makeTree('E3') }) }), makeTree('C3', { makeTree('F1'), makeTree('F2'), makeTree('F3', {makeTree('G')}), makeTree('F4', { makeTree('H1'), makeTree('H2') }) }) }), makeTree('B1',{ makeTree('K1'), makeTree('K2', { makeTree('L1', {makeTree('M')}), makeTree('L2'), makeTree('L3') }), makeTree('K3') }) }) )
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 Args { arg_pattern: String, } fn main() { let args: Args = Docopt::new(USAGE) .and_then(|d| d.decode()) .unwrap_or_else(|e| e.exit()); let re = Regex::new(&args.arg_pattern).unwrap(); let paths = std::fs::read_dir(".").unwrap(); for path in paths { let path = path.unwrap().path(); let path = path.to_str().unwrap(); if re.is_match(path) { println!("{}", path); } } }
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, $threshold, $producer) = @_; my @dist; my $result; my $expect = $n / 7; $result .= sprintf "%10d expected\n", $expect; for (1..$n) { @dist[&$producer]++; } for my $i (1..7) { my $v = @dist[$i]; my $pct = ($v - $expect)/$expect*100; $result .= sprintf "%d%8d%6.1f%%%s\n", $i, $v, $pct, (abs($pct) > $threshold ? ' - skewed' : ''); } return $result . "\n"; }
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" 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.times.collect do |_i| ColourPixel.new( 3 + rand(width - 6), 3 + rand(height - 6), RGBColour.new(rand(256), rand(256), rand(256)) ) end pixmap.each_pixel do |x, y| nearest = @bases.min_by { |base| base.distance_to(x, y) } pixmap[x, y] = nearest.colour end @bases.each do |base| pixmap[base.x, base.y] = RGBColour::BLACK pixmap.draw_circle(base, 2, RGBColour::BLACK) end pixmap.save_as_png('voronoi_rb.png')
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 = "VIGENERECIPHER" text = "Beware the Jabberwock, my son! The jaws that bite, " ++ "the claws that catch!" encr = encrypt key $ convert text decr = decrypt key encr printf " Input:%s\n Key:%s\nEncrypted:%s\nDecrypted:%s\n" text key encr decr
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 graphics::{ Context, Graphics }; use piston::window::{ Window, WindowSettings }; use piston::input::*; use piston::event_loop::*; #[cfg(feature = "include_sdl2")] use sdl2_window::Sdl2Window as AppWindow; use voronoi::{voronoi, Point, make_polygons}; use rand::Rng; static DEFAULT_WINDOW_HEIGHT: u32 = 600; static DEFAULT_WINDOW_WIDTH: u32 = 600; struct Settings { lines_only: bool, random_count: usize } fn main() { let args: Vec<String> = std::env::args().collect(); let mut opts = getopts::Options::new(); opts.optflag("l", "lines_only", "Don't color polygons, just outline them"); opts.optopt("r", "random_count", "On keypress \"R\", put this many random points on-screen", "RANDOMCOUNT"); let matches = opts.parse(&args[1..]).expect("Failed to parse args"); let settings = Settings{ lines_only: matches.opt_present("l"), random_count: match matches.opt_str("r") { None => { 50 }, Some(s) => { s.parse().expect("Random count of bad format") } } }; event_loop(&settings); } fn random_point() -> [f64; 2] { [rand::thread_rng().gen_range(0., DEFAULT_WINDOW_HEIGHT as f64), rand::thread_rng().gen_range(0., DEFAULT_WINDOW_WIDTH as f64)] } fn random_color() -> [f32; 4] { [rand::random::<f32>(), rand::random::<f32>(), rand::random::<f32>(), 1.0] } fn random_voronoi(dots: &mut Vec<[f64;2]>, colors: &mut Vec<[f32;4]>, num: usize) { dots.clear(); colors.clear(); for _ in 0..num { dots.push(random_point()); colors.push(random_color()); } } fn event_loop(settings: &Settings) { let opengl = OpenGL::V3_2; let mut window: AppWindow = WindowSettings::new("Interactive Voronoi", [DEFAULT_WINDOW_HEIGHT, DEFAULT_WINDOW_WIDTH]) .exit_on_esc(true).opengl(opengl).build().unwrap(); let ref mut gl = GlGraphics::new(opengl); let mut touch_visualizer = TouchVisualizer::new(); let mut events = Events::new(EventSettings::new().lazy(true)); let mut dots = Vec::new(); let mut colors = Vec::new(); let mut mx = 0.0; let mut my = 0.0; while let Some(e) = events.next(&mut window) { touch_visualizer.event(window.size(), &e); if let Some(button) = e.release_args() { match button { Button::Keyboard(key) => { if key == piston::input::keyboard::Key::N { dots.clear(); colors.clear(); } if key == piston::input::keyboard::Key::R { random_voronoi(&mut dots, &mut colors, settings.random_count); } } Button::Mouse(_) => { dots.push([mx, my]); colors.push(random_color()); }, _ => () } }; e.mouse_cursor(|x, y| { mx = x; my = y; }); if let Some(args) = e.render_args() { gl.draw(args.viewport(), |c, g| { graphics::clear([1.0; 4], g); let mut vor_pts = Vec::new(); for d in &dots { vor_pts.push(Point::new(d[0], d[1])); } if vor_pts.len() > 0 { let vor_diagram = voronoi(vor_pts, DEFAULT_WINDOW_WIDTH as f64); let vor_polys = make_polygons(&vor_diagram); for (i, poly) in vor_polys.iter().enumerate() { if settings.lines_only { draw_lines_in_polygon(poly, &c, g); } else { draw_polygon(poly, &c, g, colors[i]); } } } for d in &dots { draw_ellipse(&d, &c, g); } }); } } } fn draw_lines_in_polygon<G: Graphics>( poly: &Vec<Point>, c: &Context, g: &mut G, ) { let color = [0.0, 0.0, 1.0, 1.0]; for i in 0..poly.len()-1 { graphics::line( color, 2.0, [poly[i].x.into(), poly[i].y.into(), poly[i+1].x.into(), poly[i+1].y.into()], c.transform, g ) } } fn draw_polygon<G: Graphics>( poly: &Vec<Point>, c: &Context, g: &mut G, color: [f32; 4] ) { let mut polygon_points: Vec<[f64; 2]> = Vec::new(); for p in poly { polygon_points.push([p.x.into(), p.y.into()]); } graphics::polygon( color, polygon_points.as_slice(), c.transform, g ) } fn draw_ellipse<G: Graphics>( cursor: &[f64; 2], c: &Context, g: &mut G, ) { let color = [0.0, 0.0, 0.0, 1.0]; graphics::ellipse( color, graphics::ellipse::circle(cursor[0], cursor[1], 4.0), c.transform, g ); }
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(-$z) * $M; } sub G_of_half { my($n) = @_; if ($n % 2) { f(2*$_) / (4**$_ * f($_)) * sqrt(pi) for int ($n-1) / 2 } else { f(($n/2)-1) } } sub f { reduce { $a * $b } 1, 1 .. $_[0] } sub chi_squared_cdf { my($k, $x) = @_; my $f = $k < 20 ? 20 : 10; if ($x == 0) { 0.0 } elsif ($x < $k + $f*sqrt($k)) { incomplete_G_series($k/2, $x/2) / G_of_half($k) } else { 1.0 } } sub chi_squared_test { my(@bins) = @_; $significance = 0.05; my $n = @bins; my $N = sum @bins; my $expected = $N / $n; my $chi_squared = sum map { ($_ - $expected)**2 / $expected } @bins; my $p_value = 1 - chi_squared_cdf($n-1, $chi_squared); return $chi_squared, $p_value, $p_value > $significance ? 'True' : 'False'; } for $dataset ([199809, 200665, 199607, 200270, 199649], [522573, 244456, 139979, 71531, 21461]) { printf "C2 =%10.3f, p-value =%.3f, uniform =%s\n", chi_squared_test(@$dataset); }
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} = min( $_->{LEFT}, $_->{RIGHT} ) for @t; return sum map { $_->{LEVEL} > 0 ? $_->{LEVEL} - $_->{TOWER} : 0 } @t; } say join ' ', map { water_collected( @{$_} ) } ( [ 1, 5, 3, 7, 2 ], [ 5, 3, 7, 2, 6, 4, 5, 9, 1, 2 ], [ 2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1 ], [ 5, 5, 5, 5 ], [ 5, 6, 7, 8 ], [ 8, 7, 7, 6 ], [ 6, 7, 10, 7, 6 ], );
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) fmt.Println(x, "decoded") } }
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)) private val image = new BufferedImage(dim, dim, BufferedImage.TYPE_INT_RGB) private val g: Graphics2D = image.createGraphics() private val px = Vector.fill(cells)(rand.nextInt(dim)) private val py = Vector.fill(cells)(rand.nextInt(dim)) for (x <- 0 until dim; y <- 0 until dim) { var n = 0 def distance(x1: Int, x2: Int, y1: Int, y2: Int) = sqrt((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2).toDouble)
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) assert all( abs(target - count) < deltacount for count in bin.values() ), % ( target, deltacount, [ (key, target - count) for key, count in sorted(bin.items()) ] ) pp(dict(bin))
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) + ((int)(octet) & MASK) } }
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 = 0.5*h gamax = h * sum( f0(t)+hh*df0(t) for t in ( h*j for j in xrange(n-1, -1, -1))) return gamax/gamma_spounge(a) c = None def gamma_spounge( z): global c a = 12 if c is None: k1_factrl = 1.0 c = [] c.append(math.sqrt(2.0*math.pi)) for k in range(1,a): c.append( math.exp(a-k) * (a-k)**(k-0.5) / k1_factrl ) k1_factrl *= -k accm = c[0] for k in range(1,a): accm += c[k] / (z+k) accm *= math.exp( -(z+a)) * (z+a)**(z+0.5) return accm/z; def chi2UniformDistance( dataSet ): expected = sum(dataSet)*1.0/len(dataSet) cntrd = (d-expected for d in dataSet) return sum(x*x for x in cntrd)/expected def chi2Probability(dof, distance): return 1.0 - GammaInc_Q( 0.5*dof, 0.5*distance) def chi2IsUniform(dataSet, significance): dof = len(dataSet)-1 dist = chi2UniformDistance(dataSet) return chi2Probability( dof, dist ) > significance dset1 = [ 199809, 200665, 199607, 200270, 199649 ] dset2 = [ 522573, 244456, 139979, 71531, 21461 ] for ds in (dset1, dset2): print , ds dof = len(ds)-1 distance =chi2UniformDistance(ds) print % (dof, distance), prob = chi2Probability( dof, distance) print %prob, print , if chi2IsUniform(ds,0.05) else
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(enc, key)); } static String encrypt(String text, final String key) { String res = ""; text = text.toUpperCase(); for (int i = 0, j = 0; i < text.length(); i++) { char c = text.charAt(i); if (c < 'A' || c > 'Z') continue; res += (char)((c + key.charAt(j) - 2 * 'A') % 26 + 'A'); j = ++j % key.length(); } return res; } static String decrypt(String text, final String key) { String res = ""; text = text.toUpperCase(); for (int i = 0, j = 0; i < text.length(); i++) { char c = text.charAt(i); if (c < 'A' || c > 'Z') continue; res += (char)((c - key.charAt(j) + 26) % 26 + 'A'); j = ++j % key.length(); } return res; } }
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 == $depth and ',' eq $$char) { $$char = "\x0"; } elsif ('(' eq $$char) { $depth++; } elsif (')' eq $$char) { $depth--; } } return($root, [map parse($_), split /\x0/, $children]); } else { return $tree; } } sub output { my ($parsed, $prefix) = @_; my $is_root = not defined $prefix; $prefix //= ' '; while (my $member = shift @$parsed) { my $last = !@$parsed || (1 == @$parsed and ref $parsed->[0]); unless ($is_root) { substr $prefix, -3, 1, ' '; substr($prefix, -4, 1) =~ s///; substr $prefix, -2, 1, ref $member ? ' ' : '' if $last; } if (ref $member) { output($member, $prefix . ''); } else { print $prefix, $member, "\n"; } } } my $tree = 'a(b0(c1,c2(d(ef,gh)),c3(i1,i2,i3(jj),i4(kk,m))),b1(C1,C2(D1(E),D2,D3),C3))'; my $parsed = [parse($tree)]; output($parsed);
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) ubound <- expected * (1 + 0.01*delta) status <- ifelse(counts < lbound, "under", ifelse(counts > ubound, "over", "okay")) data.frame(value=names(counts), counts=as.vector(counts), status=status) } distcheck(dice7.vec)
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?",chi2IsUniform(ds))) }
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 curByte = (int)(n & 0x7F); if (i != (numBytes - 1)) curByte |= 0x80; output[i] = (byte)curByte; n >>>= 7; } return output; } public static long decode(byte[] b) { long n = 0; for (int i = 0; i < b.length; i++) { int curByte = b[i] & 0xFF; n = (n << 7) | (curByte & 0x7F); if ((curByte & 0x80) == 0) break; } return n; } public static String byteArrayToString(byte[] b) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < b.length; i++) { if (i > 0) sb.append(", "); String s = Integer.toHexString(b[i] & 0xFF); if (s.length() < 2) s = "0" + s; sb.append(s); } return sb.toString(); } public static void main(String[] args) { long[] testNumbers = { 2097152, 2097151, 1, 127, 128, 589723405834L }; for (long n : testNumbers) { byte[] encoded = encode(n); long decoded = decode(encoded); System.out.println("Original input=" + n + ", encoded = [" + byteArrayToString(encoded) + "], decoded=" + decoded + ", " + ((n == decoded) ? "OK" : "FAIL")); } } }
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 ${Long.MaxValue}") println(s"A Float variable has a range of: ${Float.MinValue} to ${Float.MaxValue}") println(s"A Double variable has a range of: ${Double.MinValue} to ${Double.MaxValue}")
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(, highest_right) print(, water_level) print(, tower) print(, sum(water_level)) print() return sum(water_level) towers = [[1, 5, 3, 7, 2], [5, 3, 7, 2, 6, 4, 5, 9, 1, 2], [2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1], [5, 5, 5, 5], [5, 6, 7, 8], [8, 7, 7, 6], [6, 7, 10, 7, 6]] [water_collected(tower) for tower in towers]
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 __FILE__ == $0 begin distcheck(100_000) {rand(10)} distcheck(100_000) {rand > 0.95} rescue StandardError => e p e end end
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))))); } octets.reverse(); return octets; }; const deoctetify = (octets)=> octets.reduce((n, octet)=> (n << RADIX) + (octet & MASK) , 0);
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 - v2[i] } return r } func (v vector) scalarMul(s float64) vector { r := make([]float64, len(v)) for i, vi := range v { r[i] = vi * s } return r } func (v vector) scalarDiv(s float64) vector { r := make([]float64, len(v)) for i, vi := range v { r[i] = vi / s } return r } func main() { v1 := vector{5, 7} v2 := vector{2, 3} fmt.Println(v1.add(v2)) fmt.Println(v1.sub(v2)) fmt.Println(v1.scalarMul(11)) fmt.Println(v1.scalarDiv(2)) }
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 $file . ; } } } findFiles('./foo', '/\.bar$/');
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) } val target: Double = nRepeats.toDouble / counts.size val deltaCount: Int = (delta / 100.0 * target).toInt counts.foreach { case (k, v) => if (math.abs(target - v) >= deltaCount) println(f"distribution potentially skewed for $k%s: $v%d") } counts.toIndexedSeq.foreach(entry => println(f"${entry._1}%d ${entry._2}%d")) } distCheck(() => 1 + util.Random.nextInt(5), 1_000_000, 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 == gprev) printf(, i); gprev = curr; } return 0; }
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("Every element must be a number.") elements = [] + e } Vector(Number... e) { this(e as List) } def order() { elements.size() } def norm2() { elements.sum { it ** 2 } ** 0.5 } def plus(Vector that) { if (this.order() != that.order()) throw new IllegalArgumentException("Vectors must be conformable for addition.") [this.elements,that.elements].transpose()*.sum() as Vector } def minus(Vector that) { this + (-that) } def multiply(Number that) { this.elements.collect { it * that } as Vector } def div(Number that) { this * (1/that) } def negative() { this * -1 } String toString() { "(${elements.join(',')})" } } class VectorCategory { static Vector plus (Number a, Vector b) { b + a } static Vector minus (Number a, Vector b) { -b + a } static Vector multiply (Number a, Vector b) { b * a } }
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 sum += f0[t] + hh * df0[t] end h * sum / gamma_spounge(a) end A = 12 k1_factrl = 1.0 coef = [Math.sqrt(2.0*Math::PI)] COEF = (1...A).each_with_object(coef) do |k,c| c << Math.exp(A-k) * (A-k)**(k-0.5) / k1_factrl k1_factrl *= -k end def gamma_spounge(z) accm = (1...A).inject(COEF[0]){|res,k| res += COEF[k] / (z+k)} accm * Math.exp(-(z+A)) * (z+A)**(z+0.5) / z end def chi2UniformDistance(dataSet) expected = dataSet.inject(:+).to_f / dataSet.size dataSet.map{|d|(d-expected)**2}.inject(:+) / expected end def chi2Probability(dof, distance) 1.0 - gammaInc_Q(0.5*dof, 0.5*distance) end def chi2IsUniform(dataSet, significance=0.05) dof = dataSet.size - 1 dist = chi2UniformDistance(dataSet) chi2Probability(dof, dist) > significance end dsets = [ [ 199809, 200665, 199607, 200270, 199649 ], [ 522573, 244456, 139979, 71531, 21461 ] ] for ds in dsets puts dof = ds.size - 1 puts % dof distance = chi2UniformDistance(ds) puts % distance puts % chi2Probability(dof, distance) puts % (chi2IsUniform(ds)? : ) end
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 pprint import pprint >>> for tree in [ (1, 2, 3, 4, 5, 6, 7, 8), (1, (( 2, 3 ), (4, (5, ((6, 7), 8))))), ((((1, 2), 3), 4), 5, 6, 7, 8) ]: print(% (tree, )) pprint(tree, indent=1, width=1) Tree (1, 2, 3, 4, 5, 6, 7, 8) can be pprint'd as: (1, 2, 3, 4, 5, 6, 7, 8) Tree (1, ((2, 3), (4, (5, ((6, 7), 8))))) can be pprint'd as: (1, ((2, 3), (4, (5, ((6, 7), 8))))) Tree ((((1, 2), 3), 4), 5, 6, 7, 8) can be pprint'd as: ((((1, 2), 3), 4), 5, 6, 7, 8) >>>
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 = " ++ (show vecB) putStrLn $ "vecA + vecB = " ++ (show.add vecA $ vecB) putStrLn $ "vecA - vecB = " ++ (show.minus vecA $ vecB) putStrLn $ "2 * vecB = " ++ (show.multByScalar 2 $ vecB) putStrLn $ "vecA / 3 = " ++ (show.divByScalar vecA $ 3)
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, distance: f64) -> f64 { 1. - gamma_li(dof * 0.5, distance * 0.5) } fn chi2_uniform(dataset: &[u32], significance: f64) -> bool { let d = chi_distance(&dataset); chi2_probability(dataset.len() as f64 - 1., d) > significance } fn main() { let dsets = vec![ vec![199809, 200665, 199607, 200270, 199649], vec![522573, 244456, 139979, 71531, 21461], ]; for ds in dsets { println!("Data set: {:?}", ds); let d = chi_distance(&ds); print!("Distance: {:.6} ", d); print!( "Chi2 probability: {:.6} ", chi2_probability(ds.len() as f64 - 1., d) ); print!("Uniform? {}\n", chi2_uniform(&ds, 0.05)); } }
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) = 2Prob(data.size - 1.0, 2Dist(data)) > significance private def 2Dist(data: Seq[Double]) = { val avg = data.sum / data.size data.reduce((a, b) => a + math.pow(b - avg, 2)) / avg } private def 2Prob(dof: Double, distance: Double) = regularizedGammaQ(dof / 2, distance / 2) printf("%4s%10s %12s%8s %s%n", "d.f.", "distance", "probability", "Uniform?", "dataset") dataSets.foreach { ds => val (dist, dof) = (2Dist(ds), ds.size - 1) printf("%4d%11.3f %13.8f %5s %6s%n", dof, dist, 2Prob(dof.toDouble, dist), if (2IsUniform(ds, 0.05)) "YES" else "NO", ds.mkString(", ")) } }
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)); } } class Vec2 { final double x, y; Vec2(double x, double y) { this.x = x; this.y = y; } Vec2 add(Vec2 v) { return new Vec2(x + v.x, y + v.y); } Vec2 sub(Vec2 v) { return new Vec2(x - v.x, y - v.y); } Vec2 div(double val) { return new Vec2(x / val, y / val); } Vec2 mult(double val) { return new Vec2(x * val, y * val); } @Override public String toString() { return String.format(Locale.US, "[%s,%s]", x, y); } }
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 puts water end a([ 5, 3, 7, 2, 6, 4, 5, 9, 1, 2 ]) a([ 2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1 ]) a([ 5, 5, 5, 5 ]) a([ 5, 6, 7, 8 ]) a([ 8, 7, 7, 6 ]) a([ 6, 7, 10, 7, 6 ]) return
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>0 && (curr===prev)) { console.log(i); } prev = curr; } </script> </body> </html>
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) t += 1<<((x%10) * 6), x /= 10; return t; } int fangs(xint x, xint *f) { int n = 0; int nd = ndigits(x); if (nd & 1) return 0; nd /= 2; xint lo, hi; lo = max(tens[nd-1], (x + tens[nd] - 2)/ (tens[nd] - 1)); hi = min(x / lo, sqrt(x)); xint a, b, t = dtally(x); for (a = lo; a <= hi; a++) { b = x / a; if (a * b == x && ((a%10) || (b%10)) && t == dtally(a) + dtally(b)) f[n++] = a; } return n; } void show_fangs(xint x, xint *f, xint cnt) { printf(, (ull)x); int i; for (i = 0; i < cnt; i++) printf(, (ull)f[i], (ull)(x / f[i])); putchar('\n'); } int main(void) { int i, j, n; xint x, f[16], bigs[] = {16758243290880ULL, 24959017348650ULL, 14593825548650ULL, 0}; tens[0] = 1; for (i = 1; i < 20; i++) tens[i] = tens[i-1] * 10; for (x = 1, n = 0; n < 25; x++) { if (!(j = fangs(x, f))) continue; printf(, ++n); show_fangs(x, f, j); } putchar('\n'); for (i = 0; bigs[i]; i++) { if ((j = fangs(bigs[i], f))) show_fangs(bigs[i], f, j); else printf(, (ull)bigs[i]); } return 0; }
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 = sprintf "%s%b", 0 x 7, shift; $binary =~ s/(.{7})$//; @vlq = ( unpack 'H2', ( pack 'B8', '0' . $1 ) ); while ( 0 + $binary ) { $binary =~ s/(.{7})$//; unshift @vlq, ( unpack 'H2', pack 'B8', '1' . $1 ); } return @vlq; } sub vlq_decode { my $num; $num .= sprintf "%07b", hex(shift @_) & 0x7f while @_; return oct '0b' . $num; }
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*string.byte('A') ) % 26 + string.byte('A') k = k + 1 if j == #key then j = 1 else j = j + 1 end end end return string.char( unpack(enc) ) end function Decrypt( _msg, _key ) local msg = { _msg:byte( 1, -1 ) } local key = { _key:upper():byte( 1, -1 ) } local dec = {} local j = 1 for i = 1, #msg do dec[i] = ( msg[i] - key[j] + 26 ) % 26 + string.byte('A') if j == #key then j = 1 else j = j + 1 end end return string.char( unpack(dec) ) end original = "Beware the Jabberwock, my son! The jaws that bite, the claws that catch!" key = "VIGENERECIPHER"; encrypted = Encrypt( original, key ) decrypted = Decrypt( encrypted, key ) print( encrypted ) print( decrypted )
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(Debug, PartialEq, Clone, Copy)] enum DisplayElement { TrunkSpace, SpaceLeft, SpaceRight, SpaceSpace, Root, } impl DisplayElement { fn string(&self) -> String { match *self { DisplayElement::TrunkSpace => " ".to_string(), DisplayElement::SpaceRight => " ".to_string(), DisplayElement::SpaceLeft => " ".to_string(), DisplayElement::SpaceSpace => " ".to_string(), DisplayElement::Root => "".to_string(), } } } #[derive(Debug, Clone, Copy, RustcDecodable, RustcEncodable)] struct Node<K, V> { key: K, value: V, left: NodePtr, right: NodePtr, up: NodePtr, } impl<K: Ord + Copy, V: Copy> Node<K, V> { pub fn get_ptr(&self, side: Side) -> NodePtr { match side { Side::Up => self.up, Side::Left => self.left, _ => self.right, } } } #[derive(Debug, RustcDecodable, RustcEncodable)] struct Tree<K, V> { root: NodePtr, store: Vec<Node<K, V>>, } impl<K: Ord + Copy + Debug + Display, V: Debug + Copy + Display> Tree<K, V> { pub fn get_node(&self, np: NodePtr) -> Node<K, V> { assert!(np.is_some()); self.store[np.unwrap()] } pub fn get_pointer(&self, np: NodePtr, side: Side) -> NodePtr { assert!(np.is_some()); self.store[np.unwrap()].get_ptr(side) }
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_peak.unwrap(), r_peak.unwrap()); if peak > val { total += peak - val; } } } total } fn main() { let patterns = vec![ vec![1, 5, 3, 7, 2], vec![5, 3, 7, 2, 6, 4, 5, 9, 1, 2], vec![2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1], vec![5, 5, 5, 5], vec![5, 6, 7, 8], vec![8, 7, 7, 6], vec![6, 7, 10, 7, 6], ]; for pattern in patterns { println!("pattern: {:?}, fill: {}", &pattern, getfill(&pattern)); } }
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 range(0, len(bits), _group))[::-1] answer = '0'*(len(_sep)-1) + answer else: answer = _sep.join(bits[i:i+_group] for i in range(0, len(bits), _group))[::-1] return answer def tovlq(n): return tobits(n, _group=7, _sep='1_', _pad=True) def toint(vlq): return int(''.join(vlq.split('_1')), 2) def vlqsend(vlq): for i, byte in enumerate(vlq.split('_')[::-1]): print('Sent byte {0:3}: {1:
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 function vector.mt.__mul (v, s) return vector.new(v.x * s, v.y * s) end function vector.mt.__div (v, s) return vector.new(v.x / s, v.y / s) end function vector.print (vec) print("(" .. vec.x .. ", " .. vec.y .. ")") end local a, b = vector.new(5, 7), vector.new(2, 3) vector.print(a + b) vector.print(a - b) vector.print(a * 11) vector.print(a / 2)
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? %) (= (sort (str n)) (digits %))) (factor-pairs n)))) (defn vampiric? [n] (let [fangs (fangs n)] (if (empty? fangs) nil [n fangs]))) (doseq [n (take 25 (keep vampiric? (range)))] (prn n)) (doseq [n [16758243290880, 24959017348650, 14593825548650]] (println (or (vampiric? n) (str n " is not vampiric."))))
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; s[j++] = k / 10; s[j++] = k % 10; } else { return 0; } } if(a[i]) return 0; v = 0; for(i = j - 2; i >= 0; i -= 2) { k = 2 * s[i]; v += k > 9 ? k - 9 : k; } for(i = j - 1; i >= 0; i -= 2) { v += s[i]; } return v % 10 == 0; } int main() { char *test[7] = {, , , , , , }; int i; for(i = 0; i < 7; i++) printf(, check_isin(test[i]) ? 'T' : 'F', i == 6 ? '\n' : ' '); return 0; }
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 scalarTripleProduct(Vector a,Vector b,Vector c) { return dotProduct(a,crossProduct(b,c)); } Vector vectorTripleProduct(Vector a,Vector b,Vector c) { return crossProduct(a,crossProduct(b,c)); } void printVector(Vector a) { printf(,a.i,a.j,a.k); } int main() { printf(); printVector(a); printf(); printVector(b); printf(); printVector(c); printf(,dotProduct(a,b)); printf(); printVector(crossProduct(a,b)); printf(,scalarTripleProduct(a,b,c)); printf(); printVector(vectorTripleProduct(a,b,c)); return 0; }
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; *denom /= q; } int main() { int d, n, i, b; for (b = 2; b < 6; b++) { printf(, b); for (i = 0; i < 10; i++) { vc(i, b, &n, &d); if (n) printf(, n, d); else printf(); } printf(); } return 0; }
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 toString(a:Array[Byte])=a map("%02x".format(_)) mkString("[", ", ", "]") def test(x:Long)={ val enc=encode(x) println("0x%x =>%s => 0x%x".format(x, toString(enc), decode(enc))) } def main(args: Array[String]): Unit = { val xs=Seq(0, 0x7f, 0x80, 0x2000, 0x3fff, 0x4000, 0x1FFFFF, 0x200000, 0x8000000, 0xFFFFFFF, 0xFFFFFFFFL, 0x842FFFFFFFFL, 0x0FFFFFFFFFFFFFFFL) xs foreach test } }
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) { if ($key === array_key_last($tree)){ echo (($first)? : $firstPadding ) . $stack . ; $padding = ; if($first) $firstPadding = ; } else { echo (($first)? : $firstPadding ) . $stack . ; $padding = ; } if( is_array($value) )printTree( $value , $key , $stack . (($first)? : $padding ) , FALSE , $firstPadding ); else echo $key . . $value . PHP_EOL; } } else echo $tree . PHP_EOL; } $sample_array_1 = [ 0 => [ 'item_id' => 6, 'price' => , 'qty' => 12, 'discount' => 0 ], 1 => [ 'item_id' => 7, 'price' => , 'qty' => 1, 'discount' => 12 ], 2 => [ 'item_id' => 8, 'price' => , 'qty' => 0, 'discount' => 24 ] ]; $sample_array_2 = array( array( =>, =>, =>, =>, =>, =>array( =>, =>array( => ) ) ) ); $sample_array_3 = [ => [ =>[ , => [ , , => [ , , ] ], , ] , => [ => [ => [1]] ] ] ]; $sample_array_4 = []; $sample_array_5 = []; $sample_array_5 = []; $sample_array_6 = [ , , , , , , , , , , , ]; printTree($sample_array_1); echo PHP_EOL . . PHP_EOL; printTree($sample_array_2); echo PHP_EOL . . PHP_EOL; printTree($sample_array_3); echo PHP_EOL . . PHP_EOL; printTree($sample_array_4); echo PHP_EOL . . PHP_EOL; printTree($sample_array_5); echo PHP_EOL . . PHP_EOL; printTree($sample_array_6); ?>
57Visualize a tree
12php
k78hv