code
stringlengths
1
46.1k
label
class label
1.18k classes
domain_label
class label
21 classes
index
stringlengths
4
5
use std::str::FromStr; #[derive(Debug, Copy, Clone, PartialEq)] pub enum State { Empty, Conductor, ElectronTail, ElectronHead, } impl State { fn next(&self, e_nearby: usize) -> State { match self { State::Empty => State::Empty, State::Conductor => { ...
48Wireworld
15rust
dohny
<? $contents = file('http: foreach ($contents as $line){ if (($pos = strpos($line, ' UTC')) === false) continue; echo subStr($line, 4, $pos - 4); break; }
49Web scraping
12php
qevx3
>>> import textwrap >>> help(textwrap.fill) Help on function fill in module textwrap: fill(text, width=70, **kwargs) Fill a single paragraph of text, returning a new string. Reformat the single paragraph in 'text' to fit in lines of no more than 'width' columns, and return a new string containing the enti...
44Word wrap
3python
yzs6q
import collections import re import string import sys def main(): counter = collections.Counter(re.findall(r,open(sys.argv[1]).read().lower())) print counter.most_common(int(sys.argv[2])) if __name__ == : main()
50Word frequency
3python
r5ngq
> x <- "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec a diam lectus. Sed sit amet ipsum mauris. Maecenas congue ligula ac quam viverra nec consectetur ante hendrerit. Donec et mollis dolor. Praesent et diam eget libero egestas mattis sit amet vitae augue. Nam tincidunt congue enim, ut porta lorem lacin...
44Word wrap
13r
tnefz
import urllib page = urllib.urlopen('http: for line in page: if ' UTC' in line: print line.strip()[4:] break page.close()
49Web scraping
3python
29slz
wordcount<-function(file,n){ punctuation=c("`","~","!","@"," wordlist=scan(file,what=character()) wordlist=tolower(wordlist) for(i in 1:length(punctuation)){ wordlist=gsub(punctuation[i],"",wordlist,fixed=T) } df=data.frame("Word"=sort(unique(wordlist)),"Count"=rep(0,length(unique(wordlist)))) for(i i...
50Word frequency
13r
ul0vx
all_lines <- readLines("http://tycho.usno.navy.mil/cgi-bin/timer.pl") utc_line <- grep("UTC", all_lines, value = TRUE) matched <- regexpr("(\\w{3}.*UTC)", utc_line) utc_time_str <- substring(line, matched, matched + attr(matched, "match.length") - 1L)
49Web scraping
13r
m3ey4
class String def wrap(width) txt = gsub(, ) para = [] i = 0 while i < length j = i + width j -= 1 while j!= txt.length && j > i + 1 &&!(txt[j] =~ /\s/) para << txt[i ... j] i = j + 1 end para end end text = <<END In olden times when wishing still helped one, there l...
44Word wrap
14ruby
968mz
require open('http: p.each_line do |line| if line =~ /UTC/ puts line.match(/ (\d{1,2}:\d{1,2}:\d{1,2}) /) break end end end
49Web scraping
14ruby
ul8vz
class String def wc n = Hash.new(0) downcase.scan(/[A-Za-z-]+/) { |g| n[g] += 1 } n.sort{|n,g| n[1]<=>g[1]} end end open('135-0.txt') { |n| n.read.wc[-10,10].each{|n| puts n[0].to_s++n[1].to_s} }
50Word frequency
14ruby
jgf7x
#[derive(Clone, Debug)] pub struct LineComposer<I> { words: I, width: usize, current: Option<String>, } impl<I> LineComposer<I> { pub(crate) fn new<S>(words: I, width: usize) -> Self where I: Iterator<Item = S>, S: AsRef<str>, { LineComposer { words, ...
44Word wrap
15rust
cyo9z
null
49Web scraping
15rust
52ouq
use std::cmp::Reverse; use std::collections::HashMap; use std::fs::File; use std::io::{BufRead, BufReader}; extern crate regex; use regex::Regex; fn word_count(file: File, n: usize) { let word_regex = Regex::new("(?i)[a-z']+").unwrap(); let mut words = HashMap::new(); for line in BufReader::new(file).lin...
50Word frequency
15rust
hrtj2
import scala.io.Source object WordCount extends App { val url = "http:
50Word frequency
16scala
ph6bj
import java.util.StringTokenizer object WordWrap extends App { final val defaultLineWidth = 80 final val spaceWidth = 1 def letsWrap(text: String, lineWidth: Int = defaultLineWidth) = { println(s"\n\nWrapped at: $lineWidth") println("." * lineWidth) minNumLinesWrap(ewd, lineWidth) } final def e...
44Word wrap
16scala
vcd2s
import scala.io.Source object WebTime extends Application { val text = Source.fromURL("http:
49Web scraping
16scala
r5dgn
import Foundation func printTopWords(path: String, count: Int) throws {
50Word frequency
17swift
74drq
doors = [False] * 100 for i in range(100): for j in range(i, 100, i+1): doors[j] = not doors[j] print(% (i+1), 'open' if doors[i] else 'close')
21100 doors
3python
z4tt
package main import ( "fmt" "math/rand" "time" ) var suits = []string{"", "", "", ""} var faces = []string{"2", "3", "4", "5", "6", "7", "8", "9", "T", "J", "Q", "K", "A"} var cards = make([]string, 52) var ranks = make([]int, 52) func init() { for i := 0; i < 52; i++ { cards[i] = fmt.Sprintf...
51War card game
0go
0xvsk
null
51War card game
1lua
n8gi8
doors_puzzle <- function(ndoors, passes = ndoors) { doors <- logical(ndoors) for (ii in seq(passes)) { mask <- seq(ii, ndoors, ii) doors[mask] <- !doors[mask] } which(doors) } doors_puzzle(100)
21100 doors
13r
n2i2
use strict; use warnings; use List::Util qw( shuffle ); my %rank; @rank{ 2 .. 9, qw(t j q k a) } = 1 .. 13; local $_ = join '', shuffle map { my $f = $_; map $f.$_, qw( S H C D ) } 2 .. 9, qw( a t j q k ); substr $_, 52, 0, "\n"; my $war = ''; my $cnt = 0; $cnt++ while print( /(.*)\n(.*)/ && "one: $1\ntwo: $2\n\n...
51War card game
2perl
r5igd
from numpy.random import shuffle SUITS = ['', '', '', ''] FACES = ['2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K', 'A'] DECK = [f + s for f in FACES for s in SUITS] CARD_TO_RANK = dict((DECK[i], (i + 3) class WarCardGame: def __init__(self): deck = DECK.copy() shuffle(deck) ...
51War card game
3python
74nrm
doors = Array.new(101,0) print (1..100).step(){ |i| (i..100).step(i) { |d| doors[d] = doors[d]^= 1 if i == d and doors[d] == 1 then print end } }
21100 doors
14ruby
6r3t
fn main() { let mut door_open = [false; 100]; for pass in 1..101 { let mut door = pass; while door <= 100 { door_open[door - 1] =!door_open[door - 1]; door += pass; } } for (i, &is_open) in door_open.iter().enumerate() { println!("Door {} is {}.", ...
21100 doors
15rust
y768
for { i <- 1 to 100 r = 1 to 100 map (i % _ == 0) reduceLeft (_^_) } println (i +" "+ (if (r) "open" else "closed"))
21100 doors
16scala
ck93
DECLARE @sqr INT, @i INT, @door INT; SELECT @sqr =1, @i = 3, @door = 1; WHILE(@door <=100) BEGIN IF(@door = @sqr) BEGIN PRINT 'Door ' + RTRIM(CAST(@door AS CHAR)) + ' is open.'; SET @sqr= @sqr+@i; SET @i=@i+2; END ELSE BEGIN PRINT 'Door ' + RTRIM(CONVERT(CHAR,@door)) + ' is closed.'; END SET @doo...
21100 doors
19sql
v12y
enum DoorState: String { case Opened = "Opened" case Closed = "Closed" } var doorsStateList = [DoorState](count: 100, repeatedValue: DoorState.Closed) for i in 1...100 { map(stride(from: i - 1, to: 100, by: i)) { doorsStateList[$0] = doorsStateList[$0] == .Opened? .Closed: .Opened } } ...
21100 doors
17swift
3gz2
interface Door { id: number; open: boolean; } function doors(): Door[] { var Doors: Door[] = []; for (let i = 1; i <= 100; i++) { Doors.push({id: i, open: false}); } for (let secuence of Doors) { for (let door of Doors) { if (door.id% secuence.id == 0) { door.open =!door.open; ...
21100 doors
20typescript
7sr5
typedef int bool; int supply[N_ROWS] = { 50, 60, 50, 50 }; int demand[N_COLS] = { 30, 20, 70, 30, 60 }; int costs[N_ROWS][N_COLS] = { { 16, 16, 13, 22, 17 }, { 14, 14, 13, 19, 15 }, { 19, 19, 20, 23, 50 }, { 50, 12, 50, 15, 11 } }; bool row_done[N_ROWS] = { FALSE }; bool col_done[N_COLS] = { FALSE };...
52Vogel's approximation method
5c
gu845
package main import ( "fmt" "math" ) var supply = []int{50, 60, 50, 50} var demand = []int{30, 20, 70, 30, 60} var costs = make([][]int, 4) var nRows = len(supply) var nCols = len(demand) var rowDone = make([]bool, nRows) var colDone = make([]bool, nCols) var results = make([][]int, nRows) func init() { ...
52Vogel's approximation method
0go
i05og
import java.util.Arrays; import static java.util.Arrays.stream; import java.util.concurrent.*; public class VogelsApproximationMethod { final static int[] demand = {30, 20, 70, 30, 60}; final static int[] supply = {50, 60, 50, 50}; final static int[][] costs = {{16, 16, 13, 22, 17}, {14, 14, 13, 19, 15}, ...
52Vogel's approximation method
9java
yzb6g
null
52Vogel's approximation method
11kotlin
firdo
function initArray(n,v) local tbl = {} for i=1,n do table.insert(tbl,v) end return tbl end function initArray2(m,n,v) local tbl = {} for i=1,m do table.insert(tbl,initArray(n,v)) end return tbl end supply = {50, 60, 50, 50} demand = {30, 20, 70, 30, 60} costs = { {1...
52Vogel's approximation method
1lua
tn7fn
enum { WALK_OK = 0, WALK_BADPATTERN, WALK_BADOPEN, }; int walker(const char *dir, const char *pattern) { struct dirent *entry; regex_t reg; DIR *d; if (regcomp(&reg, pattern, REG_EXTENDED | REG_NOSUB)) return WALK_BADPATTERN; if (!(d = opendir(dir))) return WALK_BADOPE...
53Walk a directory/Non-recursively
5c
29elo
use strict; use warnings; use List::AllUtils qw( max_by nsort_by min ); my $data = <<END; A=30 B=20 C=70 D=30 E=60 W=50 X=60 Y=50 Z=50 AW=16 BW=16 CW=13 DW=22 EW=17 AX=14 BX=14 CX=13 DX=19 EX=15 AY=19 BY=19 CY=20 DY=23 EY=50 AZ=50 BZ=12 CZ=50 DZ=15 EZ=11 END my $table = sprintf +('%4s' x 6 . "\n") x 5, map {my $t =...
52Vogel's approximation method
2perl
hrdjl
(import java.nio.file.FileSystems) (defn match-files [f pattern] (.matches (.getPathMatcher (FileSystems/getDefault) (str "glob:*" pattern)) (.toPath f))) (defn walk-directory [dir pattern] (let [directory (clojure.java.io/file dir)] (map #(.getPath %) (filter #(match-files % pattern) (.listFiles directory)))...
53Walk a directory/Non-recursively
6clojure
gu04f
from collections import defaultdict costs = {'W': {'A': 16, 'B': 16, 'C': 13, 'D': 22, 'E': 17}, 'X': {'A': 14, 'B': 14, 'C': 13, 'D': 19, 'E': 15}, 'Y': {'A': 19, 'B': 19, 'C': 20, 'D': 23, 'E': 50}, 'Z': {'A': 50, 'B': 12, 'C': 50, 'D': 15, 'E': 11}} demand = {'A': 30, 'B': 20, 'C': 70...
52Vogel's approximation method
3python
k7fhf
double site[N_SITES][2]; unsigned char rgb[N_SITES][3]; int size_x = 640, size_y = 480; inline double sq2(double x, double y) { return x * x + y * y; } int nearest_site(double x, double y) { int k, ret = 0; double d, dist = 0; for_k { d = sq2(x - site[k][0], y - site[k][1]); if (!k || d < dist) { dist = ...
54Voronoi diagram
5c
n8ui6
COSTS = {W: {A: 16, B: 16, C: 13, D: 22, E: 17}, X: {A: 14, B: 14, C: 13, D: 19, E: 15}, Y: {A: 19, B: 19, C: 20, D: 23, E: 50}, Z: {A: 50, B: 12, C: 50, D: 15, E: 11}} demand = {A: 30, B: 20, C: 70, D: 30, E: 60} supply = {W: 50, X: 60, Y: 50, Z: 50} COLS = demand.keys res = {}; COSTS.ea...
52Vogel's approximation method
14ruby
phzbh
package main import ( "fmt" "path/filepath" ) func main() { fmt.Println(filepath.Glob("*.go")) }
53Walk a directory/Non-recursively
0go
qe9xz
null
53Walk a directory/Non-recursively
7groovy
1kzp6
const char *encoded = ; const double freq[] = { 0.08167, 0.01492, 0.02782, 0.04253, 0.12702, 0.02228, 0.02015, 0.06094, 0.06966, 0.00153, 0.00772, 0.04025, 0.02406, 0.06749, 0.07507, 0.01929, 0.00095, 0.05987, 0.06327, 0.09...
55Vigenère cipher/Cryptanalysis
5c
jg870
package main import ( "fmt" "image" "image/color" "image/draw" "image/png" "math/rand" "os" "time" ) const ( imageWidth = 300 imageHeight = 200 nSites = 10 ) func main() { writePngFile(generateVoronoi(randomSites())) } func generateVoronoi(sx, sy []int) image.Im...
54Voronoi diagram
0go
r50gm
import System.Directory import Text.Regex import Data.Maybe walk :: FilePath -> String -> IO () walk dir pattern = do filenames <- getDirectoryContents dir mapM_ putStrLn $ filter (isJust.(matchRegex $ mkRegex pattern)) filenames main = walk "." ".\\.hs$"
53Walk a directory/Non-recursively
8haskell
m3byf
int getWater(int* arr,int start,int end,int cutoff){ int i, sum = 0; for(i=start;i<=end;i++) sum += ((arr[cutoff] > arr[i])?(arr[cutoff] - arr[i]):0); return sum; } int netWater(int* arr,int size){ int i, j, ref1, ref2, marker, markerSet = 0,sum = 0; if(size<3) return 0; for(i=0;i<size-1;i++){ start:if...
56Water collected between towers
5c
abf11
module Main where import System.Random import Data.Word import Data.Array.Repa as Repa import Data.Array.Repa.IO.BMP sqDistance :: Word32 -> Word32 -> Word32 -> Word32 -> Word32 sqDistance !x1 !y1 !x2 !y2 = ((x1-x2)^2) + ((y1-y2)^2) centers :: Int -> Int -> Array U DIM2 Word32 centers nCenters nCells = fro...
54Voronoi diagram
8haskell
0xcs7
typedef struct stem_t *stem; struct stem_t { const char *str; stem next; }; void tree(int root, stem head) { static const char *sdown = , *slast = , *snone = ; struct stem_t col = {0, 0}, *tail; for (tail = head; tail; tail = tail->next) { printf(, tail->str); if (!tail->next) break; } printf(, root); if ...
57Visualize a tree
5c
i0co2
package main import ( "fmt" "strings" ) var encoded = "MOMUD EKAPV TQEFM OEVHP AJMII CDCTI FGYAG JSPXY ALUYM NSMYH" + "VUXJE LEPXJ FXGCM JHKDZ RYICU HYPUS PGIGM OIYHF WHTCQ KMLRD" + "ITLXZ LJFVQ GHOLW CUHLO MDSOE KTALU VYLNZ RFGBX PHVGA LWQIS" + "FGRPH JOOFW GUBYI LAPLA LCAFA AMKLG CETDW VOEL...
55Vigenère cipher/Cryptanalysis
0go
fi5d0
enum { WALK_OK = 0, WALK_BADPATTERN, WALK_NAMETOOLONG, WALK_BADIO, }; int walk_recur(char *dname, regex_t *reg, int spec) { struct dirent *dent; DIR *dir; struct stat st; char fn[FILENAME_MAX]; int res = WALK_OK; int len = strlen(dname); if (len >= FILENAME_MAX - 1) return WALK_NAMETOOLONG; strcp...
58Walk a directory/Recursively
5c
vcb2o
File dir = new File("/foo/bar"); String[] contents = dir.list(); for (String file : contents) if (file.endsWith(".mp3")) System.out.println(file);
53Walk a directory/Non-recursively
9java
figdv
var fso = new ActiveXObject("Scripting.FileSystemObject"); var dir = fso.GetFolder('test_folder'); function walkDirectory(dir, re_pattern) { WScript.Echo("Files in " + dir.name + " matching '" + re_pattern +"':"); walkDirectoryFilter(dir.Files, re_pattern); WScript.Echo("Folders in " + dir.name + " matchi...
53Walk a directory/Non-recursively
10javascript
yzk6r
import Data.List(transpose, nub, sort, maximumBy) import Data.Ord (comparing) import Data.Char (ord) import Data.Map (Map, fromListWith, toList, findWithDefault) average :: Fractional a => [a] -> a average as = sum as / fromIntegral (length as) countEntries :: Ord a => [a] -> Map a Int countEntries = fromListWith (...
55Vigenère cipher/Cryptanalysis
8haskell
4vx5s
(defn trapped-water [towers] (let [maxes #(reductions max %) maxl (maxes towers) maxr (reverse (maxes (reverse towers))) mins (map min maxl maxr)] (reduce + (map - mins towers))))
56Water collected between towers
6clojure
swyqr
import java.awt.Color; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.geom.Ellipse2D; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import java.util.Random; import javax.imageio.ImageIO; import javax.swing.JFrame; public class Voronoi extends JFrame { st...
54Voronoi diagram
9java
abz1y
null
53Walk a directory/Non-recursively
11kotlin
8q20q
public class Vig{ static String encodedMessage = "MOMUD EKAPV TQEFM OEVHP AJMII CDCTI FGYAG JSPXY ALUYM NSMYH VUXJE LEPXJ FXGCM JHKDZ RYICU HYPUS PGIGM OIYHF WHTCQ KMLRD ITLXZ LJFVQ GHOLW CUHLO MDSOE KTALU VYLNZ RFGBX PHVGA LWQIS FGRPH JOOFW GUBYI LAPLA LCAFA AMKLG CETDW VOELJ IKGJB XPHVG ALWQC SNWBU BYHCU HKOCE XJ...
55Vigenère cipher/Cryptanalysis
9java
cyb9h
<!-- VoronoiD.html --> <html> <head><title>Voronoi diagram</title> <script>
54Voronoi diagram
10javascript
sw9qz
(use 'vijual) (draw-tree [[:A] [:B] [:C [:D [:E] [:F]] [:G]]])
57Visualize a tree
6clojure
zd5tj
null
55Vigenère cipher/Cryptanalysis
11kotlin
3frz5
(use '[clojure.java.io]) (defn walk [dirpath pattern] (doall (filter #(re-matches pattern (.getName %)) (file-seq (file dirpath))))) (map #(println (.getPath %)) (walk "src" #".*\.clj"))
58Walk a directory/Recursively
6clojure
r5wg2
null
54Voronoi diagram
11kotlin
hrij3
require "lfs" directorypath = "."
53Walk a directory/Non-recursively
1lua
osv8h
inline int rand5() { int r, rand_max = RAND_MAX - (RAND_MAX % 5); while ((r = rand()) >= rand_max); return r / (rand_max / 5) + 1; } inline int rand5_7() { int r; while ((r = rand5() * 5 + rand5()) >= 27); return r / 3 - 1; } int check(int (*gen)(), int n, int cnt, double delta) { int i = cnt, *bins = calloc...
59Verify distribution uniformity/Naive
5c
96rm1
use strict; use warnings; use feature 'say'; my %English_letter_freq = ( E => 12.70, L => 4.03, Y => 1.97, P => 1.93, T => 9.06, A => 8.17, O => 7.51, I => 6.97, N => 6.75, S => 6.33, H => 6.09, R => 5.99, D => 4.25, C => 2.78, U => 2.76, M => 2.41, W => 2.36, F => 2.23, G => 2.02, B...
55Vigenère cipher/Cryptanalysis
2perl
phdb0
(defn verify [rand n & [delta]] (let [rands (frequencies (repeatedly n rand)) avg (/ (reduce + (map val rands)) (count rands)) max-delta (* avg (or delta 1/10)) acceptable? #(<= (- avg max-delta) % (+ avg max-delta))] (for [[num count] (sort rands)] [num count (acceptable? count)])))...
59Verify distribution uniformity/Naive
6clojure
ulbvi
function love.load( ) love.math.setRandomSeed( os.time( ) )
54Voronoi diagram
1lua
k7nh2
static const int d[][10] = { {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}, {1, 2, 3, 4, 0, 6, 7, 8, 9, 5}, {2, 3, 4, 0, 1, 7, 8, 9, 5, 6}, {3, 4, 0, 1, 2, 8, 9, 5, 6, 7}, {4, 0, 1, 2, 3, 9, 5, 6, 7, 8}, {5, 9, 8, 7, 6, 0, 4, 3, 2, 1}, {6, 5, 9, 8, 7, 1, 0, 4, 3, 2}, {7, 6, 5, 9, 8, 2, 1, 0, 4, 3}, {8, 7, 6, 5, 9,...
60Verhoeff algorithm
5c
m34ys
char *get_input(void); int main(int argc, char *argv[]) { char const usage[] = ; char sign = 1; char const plainmsg[] = ; char const cryptmsg[] = ; bool encrypt = true; int opt; while ((opt = getopt(argc, argv, )) != -1) { switch (opt) { case 'd': sign = -1; ...
61Vigenère cipher
5c
4vb5t
from string import uppercase from operator import itemgetter def vigenere_decrypt(target_freqs, input): nchars = len(uppercase) ordA = ord('A') sorted_targets = sorted(target_freqs) def frequency(input): result = [[c, 0.0] for c in uppercase] for c in input: result[c - ordA...
55Vigenère cipher/Cryptanalysis
3python
1kfpc
package main import "fmt" var d = [][]int{ {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}, {1, 2, 3, 4, 0, 6, 7, 8, 9, 5}, {2, 3, 4, 0, 1, 7, 8, 9, 5, 6}, {3, 4, 0, 1, 2, 8, 9, 5, 6, 7}, {4, 0, 1, 2, 3, 9, 5, 6, 7, 8}, {5, 9, 8, 7, 6, 0, 4, 3, 2, 1}, {6, 5, 9, 8, 7, 1, 0, 4, 3, 2}, {7, 6, 5, 9, 8, 2, ...
60Verhoeff algorithm
0go
abo1f
use std::iter::FromIterator; const CRYPTOGRAM: &str = "MOMUD EKAPV TQEFM OEVHP AJMII CDCTI FGYAG JSPXY ALUYM NSMYH VUXJE LEPXJ FXGCM JHKDZ RYICU HYPUS PGIGM OIYHF WHTCQ KMLRD ITLXZ LJFVQ GHOLW CUHLO MDSOE KTALU VYLNZ RFGBX PHVGA LWQIS FGRPH JOOFW GUBYI LAPLA LCAFA AMKLG CETDW VOELJ IKGJB XPHVG ALWQC SNWBU BYHCU HKOCE ...
55Vigenère cipher/Cryptanalysis
15rust
w13e4
package main import "fmt" func maxl(hm []int ) []int{ res := make([]int,len(hm)) max := 1 for i := 0; i < len(hm);i++{ if(hm[i] > max){ max = hm[i] } res[i] = max; } return res } func maxr(hm []int ) []int{ res := make([]int,len(hm)) max := 1 for i := len(hm) - 1 ; i >= 0;i--{ if(hm[i] > max){ m...
56Water collected between towers
0go
m3jyi
use strict; use warnings; use Imager; my %type = ( Taxicab => sub { my($px, $py, $x, $y) = @_; abs($px - $x) + abs($py - $y) }, Euclidean => sub { my($px, $py, $x, $y) = @_; ($px - $x)**2 + ($py - $y)**2 }, Minkowski => sub { my($px, $py, $x, $y) = @_; abs($px - $x)**3 + abs($py - $y)**3 }...
54Voronoi diagram
2perl
zdrtb
Integer waterBetweenTowers(List<Integer> towers) {
56Water collected between towers
7groovy
tn5fh
typedef double (* Ifctn)( double t); double Simpson3_8( Ifctn f, double a, double b, int N) { int j; double l1; double h = (b-a)/N; double h1 = h/3.0; double sum = f(a) + f(b); for (j=3*N-1; j>0; j--) { l1 = (j%3)? 3.0 : 2.0; sum += l1*f(a+h1*j) ; } return h*sum/8.0; } ...
62Verify distribution uniformity/Chi-squared test
5c
52huk
(ns org.rosettacode.clojure.vigenere (:require [clojure.string:as string])) (defn to-num [char] (- (int char) (int \A))) (defn from-num [num] (char (+ (mod num 26) (int \A)))) (defn to-normalized-seq [str] (map #'first (re-seq #"[A-Z]" (string/upper-case str)))) (defn crypt1 [op text key] (from-num (app...
61Vigenère cipher
6clojure
hrwjr
use 5.010; opendir my $dh, '/home/foo/bar'; say for grep { /php$/ } readdir $dh; closedir $dh;
53Walk a directory/Non-recursively
2perl
4vs5d
package main import ( "fmt" "os" "path/filepath" ) func VisitFile(fp string, fi os.FileInfo, err error) error { if err != nil { fmt.Println(err)
58Walk a directory/Recursively
0go
sw3qa
import Data.Vector.Unboxed (Vector) import qualified Data.Vector.Unboxed as V waterCollected :: Vector Int -> Int waterCollected = V.sum . V.filter (> 0) . (V.zipWith (-) =<< (V.zipWith min . V.scanl1 max <*> V.scanr1 max)) main :: IO () main = mapM_ (print . waterCollecte...
56Water collected between towers
8haskell
k7oh0
package main import ( "fmt" "math" "math/rand" "time" )
59Verify distribution uniformity/Naive
0go
epna6
use strict; use warnings; my @inv = qw(0 4 3 2 1 5 6 7 8 9); my @d = map [ split ], split /\n/, <<END; 0 1 2 3 4 5 6 7 8 9 1 2 3 4 0 6 7 8 9 5 2 3 4 0 1 7 8 9 5 6 3 4 0 1 2 8 9 5 6 7 4 0 1 2 3 9 5 6 7 8 5 9 8 7 6 0 4 3 2 1 6 5 9 8 7 1 0 4 3 2 7 6 5 9 ...
60Verhoeff algorithm
2perl
29jlf
package main import ( "encoding/json" "fmt" "log" ) type Node struct { Name string Children []*Node } func main() { tree := &Node{"root", []*Node{ &Node{"a", []*Node{ &Node{"d", nil}, &Node{"e", []*Node{ &Node{"f", nil}, }}}}, ...
57Visualize a tree
0go
guw4n
$pattern = 'php'; $dh = opendir('c:/foo/bar'); while (false !== ($file = readdir($dh))) { if ($file != '.' and $file != '..') { if (preg_match(, $file)) { echo ; } } } closedir($dh);
53Walk a directory/Non-recursively
12php
i0uov
new File('.').eachFileRecurse { if (it.name =~ /.*\.txt/) println it; }
58Walk a directory/Recursively
7groovy
abn1p
import System.Random import Data.List import Control.Monad import Control.Arrow distribCheck :: IO Int -> Int -> Int -> IO [(Int,(Int,Bool))] distribCheck f n d = do nrs <- replicateM n f let group = takeWhile (not.null) $ unfoldr (Just. (partition =<< (==). head)) nrs avg = (fromIntegral n) / fromIntegr...
59Verify distribution uniformity/Naive
8haskell
3fuzj
data Tree a = Empty | Node { value :: a, left :: Tree a, right :: Tree a } deriving (Show, Eq) tree = Node 1 (Node 2 (Node 4 (Node 7 Empty Empty) Empty) (Node 5 Empty Empty)) (Node 3 (Node 6 (Node 8 Empty Empty) (Node 9 Empty Empty)) Empty) treeIndent Empty = [" treeIndent t = [" ++ map (" |"++) ls ++ (" `" ++ ...
57Visualize a tree
8haskell
sw6qk
import System.Environment import System.Directory import System.FilePath.Find search pat = find always (fileName ~~? pat) main = do [pat] <- getArgs dir <- getCurrentDirectory files <- search pat dir mapM_ putStrLn files
58Walk a directory/Recursively
8haskell
967mo
public class WaterBetweenTowers { public static void main(String[] args) { int i = 1; int[][] tba = new int[][]{ new int[]{1, 5, 3, 7, 2}, new int[]{5, 3, 7, 2, 6, 4, 5, 9, 1, 2}, new int[]{2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1}, new int[]{5, ...
56Water collected between towers
9java
4vw58
MULTIPLICATION_TABLE = [ (0, 1, 2, 3, 4, 5, 6, 7, 8, 9), (1, 2, 3, 4, 0, 6, 7, 8, 9, 5), (2, 3, 4, 0, 1, 7, 8, 9, 5, 6), (3, 4, 0, 1, 2, 8, 9, 5, 6, 7), (4, 0, 1, 2, 3, 9, 5, 6, 7, 8), (5, 9, 8, 7, 6, 0, 4, 3, 2, 1), (6, 5, 9, 8, 7, 1, 0, 4, 3, 2), (7, 6, 5, 9, 8, 2, 1, 0, 4, 3), (8,...
60Verhoeff algorithm
3python
vch29
(function () { 'use strict';
56Water collected between towers
10javascript
hr8jh
import static java.lang.Math.abs; import java.util.*; import java.util.function.IntSupplier; public class Test { static void distCheck(IntSupplier f, int nRepeats, double delta) { Map<Integer, Integer> counts = new HashMap<>(); for (int i = 0; i < nRepeats; i++) counts.compute(f.getAs...
59Verify distribution uniformity/Naive
9java
i0mos
from PIL import Image import random import math def generate_voronoi_diagram(width, height, num_cells): image = Image.new(, (width, height)) putpixel = image.putpixel imgx, imgy = image.size nx = [] ny = [] nr = [] ng = [] nb = [] for i in range(num_cells): nx.append(random.randrange(imgx)) ny.append(rand...
54Voronoi diagram
3python
3f7zc
package main import ( "fmt" "math" ) type ifctn func(float64) float64 func simpson38(f ifctn, a, b float64, n int) float64 { h := (b - a) / float64(n) h1 := h / 3 sum := f(a) + f(b) for j := 3*n - 1; j > 0; j-- { if j%3 == 0 { sum += 2 * f(a+h1*float64(j)) } else {...
62Verify distribution uniformity/Chi-squared test
0go
8qt0g
import glob for filename in glob.glob('/foo/bar/*.mp3'): print(filename)
53Walk a directory/Non-recursively
3python
gu04h
import java.io.File; public class MainEntry { public static void main(String[] args) { walkin(new File("/home/user"));
58Walk a directory/Recursively
9java
tnvf9
package main import ( "fmt" "log" "os/exec" "time" ) func main() {
63Video display modes
0go
29gl7
function distcheck(random_func, times, opts) { if (opts === undefined) opts = {} opts['delta'] = opts['delta'] || 2; var count = {}, vals = []; for (var i = 0; i < times; i++) { var val = random_func(); if (! has_property(count, val)) { count[val] = 1; vals.push(...
59Verify distribution uniformity/Naive
10javascript
zdvt2
randHclr <- function() { m=255;r=g=b=0; r <- sample(0:m, 1, replace=TRUE); g <- sample(0:m, 1, replace=TRUE); b <- sample(0:m, 1, replace=TRUE); return(rgb(r,g,b,maxColorValue=m)); } Metric <- function(x, y, mt) { if(mt==1) {return(sqrt(x*x + y*y))} if(mt==2) {return(abs(x) + abs(y))} if(mt==3) {return...
54Voronoi diagram
13r
do5nt