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 => { if e_nearby == 1 || e_nearby == 2 { State::ElectronHead } else { State::Conductor } } State::ElectronTail => State::Conductor, State::ElectronHead => State::ElectronTail, } } } #[derive(Debug, Clone, PartialEq)] pub struct WireWorld { pub width: usize, pub height: usize, pub data: Vec<State>, } impl WireWorld { pub fn new(width: usize, height: usize) -> Self { WireWorld { width, height, data: vec![State::Empty; width * height], } } pub fn get(&self, x: usize, y: usize) -> Option<State> { if x >= self.width || y >= self.height { None } else { self.data.get(y * self.width + x).copied() } } pub fn set(&mut self, x: usize, y: usize, state: State) { self.data[y * self.width + x] = state; } fn neighbors<F>(&self, x: usize, y: usize, mut f: F) -> usize where F: FnMut(State) -> bool { let (x, y) = (x as i32, y as i32); let neighbors = [(x-1,y-1),(x-1,y),(x-1,y+1),(x,y-1),(x,y+1),(x+1,y-1),(x+1,y),(x+1,y+1)]; neighbors.iter().filter_map(|&(x, y)| self.get(x as usize, y as usize)).filter(|&s| f(s)).count() } pub fn next(&mut self) { let mut next_state = vec![]; for y in 0..self.height { for x in 0..self.width { let e_count = self.neighbors(x, y, |e| e == State::ElectronHead); next_state.push(self.get(x, y).unwrap().next(e_count)); } } self.data = next_state; } } impl FromStr for WireWorld { type Err = (); fn from_str(s: &str) -> Result<WireWorld, ()> { let s = s.trim(); let height = s.lines().count(); let width = s.lines().map(|l| l.trim_end().len()).max().unwrap_or(0); let mut world = WireWorld::new(width, height); for (y, line) in s.lines().enumerate() { for (x, ch) in line.trim_end().chars().enumerate() { let state = match ch { '.' => State::Conductor, 't' => State::ElectronTail, 'H' => State::ElectronHead, _ => State::Empty, }; world.set(x, y, state); } } Ok(world) } }
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 entire wrapped paragraph. As with wrap(), tabs are expanded and other whitespace characters converted to space. See TextWrapper class for available keyword args to customize wrapping behaviour. >>> txt = '''\ Reformat the single paragraph in 'text' to fit in lines of no more than 'width' columns, and return a new string containing the entire wrapped paragraph. As with wrap(), tabs are expanded and other whitespace characters converted to space. See TextWrapper class for available keyword args to customize wrapping behaviour.''' >>> print(textwrap.fill(txt, width=75)) Reformat the single paragraph in 'text' to fit in lines of no more than 'width' columns, and return a new string containing the entire wrapped paragraph. As with wrap(), tabs are expanded and other whitespace characters converted to space. See TextWrapper class for available keyword args to customize wrapping behaviour. >>> print(textwrap.fill(txt, width=45)) Reformat the single paragraph in 'text' to fit in lines of no more than 'width' columns, and return a new string containing the entire wrapped paragraph. As with wrap(), tabs are expanded and other whitespace characters converted to space. See TextWrapper class for available keyword args to customize wrapping behaviour. >>> print(textwrap.fill(txt, width=85)) Reformat the single paragraph in 'text' to fit in lines of no more than 'width' columns, and return a new string containing the entire wrapped paragraph. As with wrap(), tabs are expanded and other whitespace characters converted to space. See TextWrapper class for available keyword args to customize wrapping behaviour. >>>
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 lacinia consectetur. " > cat(paste(strwrap(x=c(x, "\n"), width=80), collapse="\n")) 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 lacinia consectetur. > cat(paste(strwrap(x=c(x, "\n"), width=60), collapse="\n")) 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 lacinia consectetur.
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 in 1:length(unique(wordlist))){ df[i,2]=length(which(wordlist==df[i,1])) } df=df[order(df[,2],decreasing = T),] row.names(df)=1:nrow(df) return(df[1:n,]) }
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 lived a king whose daughters were all beautiful, but the youngest was so beautiful that the sun itself, which has seen so much, was astonished whenever it shone in her face. Close by the king's castle lay a great dark forest, and under an old lime-tree in the forest was a well, and when the day was very warm, the king's child went out into the forest and sat down by the side of the cool fountain, and when she was bored she took a golden ball, and threw it up on high and caught it, and this ball was her favorite plaything. END [72,80].each do |w| puts * w puts text.wrap(w) end
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, width, current: None, } } } impl<I, S> Iterator for LineComposer<I> where I: Iterator<Item = S>, S: AsRef<str>, { type Item = String; fn next(&mut self) -> Option<Self::Item> { let mut next = match self.words.next() { None => return self.current.take(), Some(value) => value, }; let mut current = self.current.take().unwrap_or_else(String::new); loop { let word = next.as_ref(); if self.width <= current.len() + word.len() { self.current = Some(String::from(word));
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).lines() { word_regex .find_iter(&line.expect("Read error")) .map(|m| m.as_str()) .for_each(|word| { *words.entry(word.to_lowercase()).or_insert(0) += 1; }); } let mut words: Vec<_> = words.iter().collect(); words.sort_unstable_by_key(|&(word, count)| (Reverse(count), word)); for (word, count) in words.iter().take(n) { println!("{:8} {:>8}", word, count); } } fn main() { word_count(File::open("135-0.txt").expect("File open error"), 10) }
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 ewd = "Vijftig jaar geleden publiceerde Edsger Dijkstra zijn kortstepadalgoritme. Daarom een kleine ode" + " aan de in 2002 overleden Dijkstra, iemand waar we als Nederlanders best wat trotser op mogen zijn. Dijkstra was" + " een van de eerste programmeurs van Nederland. Toen hij in 1957 trouwde, werd het beroep computerprogrammeur door" + " de burgerlijke stand nog niet erkend en uiteindelijk gaf hij maar `theoretische natuurkundige op.\nZijn" + " beroemdste resultaat is het kortstepadalgoritme, dat de kortste verbinding vindt tussen twee knopen in een graaf" + " (een verzameling punten waarvan sommigen verbonden zijn). Denk bijvoorbeeld aan het vinden van de kortste route" + " tussen twee steden. Het slimme van Dijkstras algoritme is dat het niet alle mogelijke routes met elkaar" + " vergelijkt, maar dat het stap voor stap de kortst mogelijke afstanden tot elk punt opbouwt. In de eerste stap" + " kijk je naar alle punten die vanaf het beginpunt te bereiken zijn en markeer je al die punten met de afstand tot" + " het beginpunt. Daarna kijk je steeds vanaf het punt dat op dat moment de kortste afstand heeft tot het beginpunt" + " naar alle punten die je vanaf daar kunt bereiken. Als je een buurpunt via een nieuwe verbinding op een snellere" + " manier kunt bereiken, schrijf je de nieuwe, kortere afstand tot het beginpunt bij zon punt. Zo ga je steeds een" + " stukje verder tot je alle punten hebt gehad en je de kortste route tot het eindpunt hebt gevonden." def minNumLinesWrap(text: String, LineWidth: Int) { val tokenizer = new StringTokenizer(text) var SpaceLeft = LineWidth while (tokenizer.hasMoreTokens) { val word: String = tokenizer.nextToken if ((word.length + spaceWidth) > SpaceLeft) { print("\n" + word + " ") SpaceLeft = LineWidth - word.length } else { print(word + " ") SpaceLeft -= (word.length + spaceWidth) } } } letsWrap(ewd) letsWrap(ewd, 120) }
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("%s%s", faces[i%13], suits[i/13]) ranks[i] = i % 13 } } func war() { deck := make([]int, 52) for i := 0; i < 52; i++ { deck[i] = i } rand.Shuffle(52, func(i, j int) { deck[i], deck[j] = deck[j], deck[i] }) hand1 := make([]int, 26, 52) hand2 := make([]int, 26, 52) for i := 0; i < 26; i++ { hand1[25-i] = deck[2*i] hand2[25-i] = deck[2*i+1] } for len(hand1) > 0 && len(hand2) > 0 { card1 := hand1[0] copy(hand1[0:], hand1[1:]) hand1[len(hand1)-1] = 0 hand1 = hand1[0 : len(hand1)-1] card2 := hand2[0] copy(hand2[0:], hand2[1:]) hand2[len(hand2)-1] = 0 hand2 = hand2[0 : len(hand2)-1] played1 := []int{card1} played2 := []int{card2} numPlayed := 2 for { fmt.Printf("%s\t%s\t", cards[card1], cards[card2]) if ranks[card1] > ranks[card2] { hand1 = append(hand1, played1...) hand1 = append(hand1, played2...) fmt.Printf("Player 1 takes the%d cards. Now has%d.\n", numPlayed, len(hand1)) break } else if ranks[card1] < ranks[card2] { hand2 = append(hand2, played2...) hand2 = append(hand2, played1...) fmt.Printf("Player 2 takes the%d cards. Now has%d.\n", numPlayed, len(hand2)) break } else { fmt.Println("War!") if len(hand1) < 2 { fmt.Println("Player 1 has insufficient cards left.") hand2 = append(hand2, played2...) hand2 = append(hand2, played1...) hand2 = append(hand2, hand1...) hand1 = hand1[0:0] break } if len(hand2) < 2 { fmt.Println("Player 2 has insufficient cards left.") hand1 = append(hand1, played1...) hand1 = append(hand1, played2...) hand1 = append(hand1, hand2...) hand2 = hand2[0:0] break } fdCard1 := hand1[0]
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" ), s/^((.).)(.*)\n((?!\2)(.).)(.*)$/ my $win = $war; $war = ''; $rank{$2} > $rank{$5} ? "$3$1$4$win\n$6" : "$3\n$6$4$1$win" /e || s/^(.{4})(.*)\n(.{4})(.*)$/ print "WAR!!!\n\n"; $war .= "$1$3"; "$2\n$4" /e; print "player '", /^.{10}/ ? 'one' : 'two', "' wins in $cnt moves\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) self.deck1, self.deck2 = deck[:26], deck[26:] self.pending = [] def turn(self): if len(self.deck1) == 0 or len(self.deck2) == 0: return self.gameover() card1, card2 = self.deck1.pop(0), self.deck2.pop(0) rank1, rank2 = CARD_TO_RANK[card1], CARD_TO_RANK[card2] print(.format(card1, card2), end='') if rank1 > rank2: print('Player 1 takes the cards.') self.deck1.extend([card1, card2]) self.deck1.extend(self.pending) self.pending = [] elif rank1 < rank2: print('Player 2 takes the cards.') self.deck2.extend([card2, card1]) self.deck2.extend(self.pending) self.pending = [] else: print('Tie!') if len(self.deck1) == 0 or len(self.deck2) == 0: return self.gameover() card3, card4 = self.deck1.pop(0), self.deck2.pop(0) self.pending.extend([card1, card2, card3, card4]) print(.format(, ), 'Cards are face down.', sep='') return self.turn() return True def gameover(self): if len(self.deck2) == 0: if len(self.deck1) == 0: print('\nGame ends as a tie.') else: print('\nPlayer 1 wins the game.') else: print('\nPlayer 2 wins the game.') return False if __name__ == '__main__': WG = WarCardGame() while WG.turn(): continue
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 {}.", i + 1, if is_open {"open"} else {"closed"}); } }
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 @door = @door + 1 END
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 } } for (index, item) in enumerate(doorsStateList) { println("Door \(index+1) is \(item.rawValue)") }
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; } } } return Doors.filter(a => a.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 }; void diff(int j, int len, bool is_row, int res[3]) { int i, c, min1 = INT_MAX, min2 = min1, min_p = -1; for (i = 0; i < len; ++i) { if((is_row) ? col_done[i] : row_done[i]) continue; c = (is_row) ? costs[j][i] : costs[i][j]; if (c < min1) { min2 = min1; min1 = c; min_p = i; } else if (c < min2) min2 = c; } res[0] = min2 - min1; res[1] = min1; res[2] = min_p; } void max_penalty(int len1, int len2, bool is_row, int res[4]) { int i, pc = -1, pm = -1, mc = -1, md = INT_MIN; int res2[3]; for (i = 0; i < len1; ++i) { if((is_row) ? row_done[i] : col_done[i]) continue; diff(i, len2, is_row, res2); if (res2[0] > md) { md = res2[0]; pm = i; mc = res2[1]; pc = res2[2]; } } if (is_row) { res[0] = pm; res[1] = pc; } else { res[0] = pc; res[1] = pm; } res[2] = mc; res[3] = md; } void next_cell(int res[4]) { int i, res1[4], res2[4]; max_penalty(N_ROWS, N_COLS, TRUE, res1); max_penalty(N_COLS, N_ROWS, FALSE, res2); if (res1[3] == res2[3]) { if (res1[2] < res2[2]) for (i = 0; i < 4; ++i) res[i] = res1[i]; else for (i = 0; i < 4; ++i) res[i] = res2[i]; return; } if (res1[3] > res2[3]) for (i = 0; i < 4; ++i) res[i] = res2[i]; else for (i = 0; i < 4; ++i) res[i] = res1[i]; } int main() { int i, j, r, c, q, supply_left = 0, total_cost = 0, cell[4]; int results[N_ROWS][N_COLS] = { 0 }; for (i = 0; i < N_ROWS; ++i) supply_left += supply[i]; while (supply_left > 0) { next_cell(cell); r = cell[0]; c = cell[1]; q = (demand[c] <= supply[r]) ? demand[c] : supply[r]; demand[c] -= q; if (!demand[c]) col_done[c] = TRUE; supply[r] -= q; if (!supply[r]) row_done[r] = TRUE; results[r][c] = q; supply_left -= q; total_cost += q * costs[r][c]; } printf(); for (i = 0; i < N_ROWS; ++i) { printf(, 'W' + i); for (j = 0; j < N_COLS; ++j) printf(, results[i][j]); printf(); } printf(, total_cost); return 0; }
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() { costs[0] = []int{16, 16, 13, 22, 17} costs[1] = []int{14, 14, 13, 19, 15} costs[2] = []int{19, 19, 20, 23, 50} costs[3] = []int{50, 12, 50, 15, 11} for i := 0; i < len(results); i++ { results[i] = make([]int, nCols) } } func nextCell() []int { res1 := maxPenalty(nRows, nCols, true) res2 := maxPenalty(nCols, nRows, false) switch { case res1[3] == res2[3]: if res1[2] < res2[2] { return res1 } else { return res2 } case res1[3] > res2[3]: return res2 default: return res1 } } func diff(j, l int, isRow bool) []int { min1 := math.MaxInt32 min2 := min1 minP := -1 for i := 0; i < l; i++ { var done bool if isRow { done = colDone[i] } else { done = rowDone[i] } if done { continue } var c int if isRow { c = costs[j][i] } else { c = costs[i][j] } if c < min1 { min2, min1, minP = min1, c, i } else if c < min2 { min2 = c } } return []int{min2 - min1, min1, minP} } func maxPenalty(len1, len2 int, isRow bool) []int { md := math.MinInt32 pc, pm, mc := -1, -1, -1 for i := 0; i < len1; i++ { var done bool if isRow { done = rowDone[i] } else { done = colDone[i] } if done { continue } res := diff(i, len2, isRow) if res[0] > md { md = res[0]
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}, {19, 19, 20, 23, 50}, {50, 12, 50, 15, 11}}; final static int nRows = supply.length; final static int nCols = demand.length; static boolean[] rowDone = new boolean[nRows]; static boolean[] colDone = new boolean[nCols]; static int[][] result = new int[nRows][nCols]; static ExecutorService es = Executors.newFixedThreadPool(2); public static void main(String[] args) throws Exception { int supplyLeft = stream(supply).sum(); int totalCost = 0; while (supplyLeft > 0) { int[] cell = nextCell(); int r = cell[0]; int c = cell[1]; int quantity = Math.min(demand[c], supply[r]); demand[c] -= quantity; if (demand[c] == 0) colDone[c] = true; supply[r] -= quantity; if (supply[r] == 0) rowDone[r] = true; result[r][c] = quantity; supplyLeft -= quantity; totalCost += quantity * costs[r][c]; } stream(result).forEach(a -> System.out.println(Arrays.toString(a))); System.out.println("Total cost: " + totalCost); es.shutdown(); } static int[] nextCell() throws Exception { Future<int[]> f1 = es.submit(() -> maxPenalty(nRows, nCols, true)); Future<int[]> f2 = es.submit(() -> maxPenalty(nCols, nRows, false)); int[] res1 = f1.get(); int[] res2 = f2.get(); if (res1[3] == res2[3]) return res1[2] < res2[2] ? res1 : res2; return (res1[3] > res2[3]) ? res2 : res1; } static int[] diff(int j, int len, boolean isRow) { int min1 = Integer.MAX_VALUE, min2 = Integer.MAX_VALUE; int minP = -1; for (int i = 0; i < len; i++) { if (isRow ? colDone[i] : rowDone[i]) continue; int c = isRow ? costs[j][i] : costs[i][j]; if (c < min1) { min2 = min1; min1 = c; minP = i; } else if (c < min2) min2 = c; } return new int[]{min2 - min1, min1, minP}; } static int[] maxPenalty(int len1, int len2, boolean isRow) { int md = Integer.MIN_VALUE; int pc = -1, pm = -1, mc = -1; for (int i = 0; i < len1; i++) { if (isRow ? rowDone[i] : colDone[i]) continue; int[] res = diff(i, len2, isRow); if (res[0] > md) { md = res[0];
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 = { {16, 16, 13, 22, 17}, {14, 14, 13, 19, 15}, {19, 19, 20, 23, 50}, {50, 12, 50, 15, 11} } nRows = table.getn(supply) nCols = table.getn(demand) rowDone = initArray(nRows, false) colDone = initArray(nCols, false) results = initArray2(nRows, nCols, 0) function diff(j,le,isRow) local min1 = 100000000 local min2 = min1 local minP = -1 for i=1,le do local done = false if isRow then done = colDone[i] else done = rowDone[i] end if not done then local c = 0 if isRow then c = costs[j][i] else c = costs[i][j] end if c < min1 then min2 = min1 min1 = c minP = i elseif c < min2 then min2 = c end end end return {min2 - min1, min1, minP} end function maxPenalty(len1,len2,isRow) local md = -100000000 local pc = -1 local pm = -1 local mc = -1 for i=1,len1 do local done = false if isRow then done = rowDone[i] else done = colDone[i] end if not done then local res = diff(i, len2, isRow) if res[1] > md then md = res[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_BADOPEN; while (entry = readdir(d)) if (!regexec(&reg, entry->d_name, 0, NULL, 0)) puts(entry->d_name); closedir(d); regfree(&reg); return WALK_OK; } int main() { walker(, ); return 0; }
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 = $_; map "$_$t", '', 'A' .. 'E' } '' , 'W' .. 'Z'; my ($cost, %assign) = (0); while( $data =~ /\b\w=\d/ ) { my @penalty; for ( $data =~ /\b(\w)=\d/g ) { my @all = map /(\d+)/, nsort_by { /\d+/ && $& } grep { my ($t, $c) = /(.)(.)=/; $data =~ /\b$c=\d/ and $data =~ /\b$t=\d/ } $data =~ /$_\w=\d+|\w$_=\d+/g; push @penalty, [ $_, ($all[1] // 0) - $all[0] ]; } my $rc = (max_by { $_->[1] } nsort_by { my $x = $_->[0]; $data =~ /(?:$x\w|\w$x)=(\d+)/ && $1 } @penalty)->[0]; my @lowest = nsort_by { /\d+/ && $& } grep { my ($t, $c) = /(.)(.)=/; $data =~ /\b$c=\d/ and $data =~ /\b$t=\d/ } $data =~ /$rc\w=\d+|\w$rc=\d+/g; my ($t, $c) = $lowest[0] =~ /(.)(.)/; my $allocate = min $data =~ /\b[$t$c]=(\d+)/g; $table =~ s/$t$c/ sprintf "%2d", $allocate/e; $cost += $data =~ /$t$c=(\d+)/ && $1 * $allocate; $data =~ s/\b$_=\K\d+/ $& - $allocate || '' /e for $t, $c; } print "cost $cost\n\n", $table =~ s/[A-Z]{2}/--/gr;
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, 'D': 30, 'E': 60} cols = sorted(demand.iterkeys()) supply = {'W': 50, 'X': 60, 'Y': 50, 'Z': 50} res = dict((k, defaultdict(int)) for k in costs) g = {} for x in supply: g[x] = sorted(costs[x].iterkeys(), key=lambda g: costs[x][g]) for x in demand: g[x] = sorted(costs.iterkeys(), key=lambda g: costs[g][x]) while g: d = {} for x in demand: d[x] = (costs[g[x][1]][x] - costs[g[x][0]][x]) if len(g[x]) > 1 else costs[g[x][0]][x] s = {} for x in supply: s[x] = (costs[x][g[x][1]] - costs[x][g[x][0]]) if len(g[x]) > 1 else costs[x][g[x][0]] f = max(d, key=lambda n: d[n]) t = max(s, key=lambda n: s[n]) t, f = (f, g[f][0]) if d[f] > s[t] else (g[t][0], t) v = min(supply[f], demand[t]) res[f][t] += v demand[t] -= v if demand[t] == 0: for k, n in supply.iteritems(): if n != 0: g[k].remove(t) del g[t] del demand[t] supply[f] -= v if supply[f] == 0: for k, n in demand.iteritems(): if n != 0: g[k].remove(f) del g[f] del supply[f] for n in cols: print , n, print cost = 0 for g in sorted(costs): print g, , for n in cols: y = res[g][n] if y != 0: print y, cost += y * costs[g][n] print , print print , cost
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 = d, ret = k; } } return ret; } int at_edge(int *color, int y, int x) { int i, j, c = color[y * size_x + x]; for (i = y - 1; i <= y + 1; i++) { if (i < 0 || i >= size_y) continue; for (j = x - 1; j <= x + 1; j++) { if (j < 0 || j >= size_x) continue; if (color[i * size_x + j] != c) return 1; } } return 0; } void aa_color(unsigned char *pix, int y, int x) { int i, j, n; double r = 0, g = 0, b = 0, xx, yy; for (i = 0; i < AA_RES; i++) { yy = y + 1. / AA_RES * i + .5; for (j = 0; j < AA_RES; j++) { xx = x + 1. / AA_RES * j + .5; n = nearest_site(xx, yy); r += rgb[n][0]; g += rgb[n][1]; b += rgb[n][2]; } } pix[0] = r / (AA_RES * AA_RES); pix[1] = g / (AA_RES * AA_RES); pix[2] = b / (AA_RES * AA_RES); } void gen_map() { int i, j, k; int *nearest = malloc(sizeof(int) * size_y * size_x); unsigned char *ptr, *buf, color; ptr = buf = malloc(3 * size_x * size_y); for_i for_j nearest[i * size_x + j] = nearest_site(j, i); for_i for_j { if (!at_edge(nearest, i, j)) memcpy(ptr, rgb[nearest[i * size_x + j]], 3); else aa_color(ptr, i, j); ptr += 3; } for (k = 0; k < N_SITES; k++) { color = (rgb[k][0]*.25 + rgb[k][1]*.6 + rgb[k][2]*.15 > 80) ? 0 : 255; for (i = site[k][1] - 1; i <= site[k][1] + 1; i++) { if (i < 0 || i >= size_y) continue; for (j = site[k][0] - 1; j <= site[k][0] + 1; j++) { if (j < 0 || j >= size_x) continue; ptr = buf + 3 * (i * size_x + j); ptr[0] = ptr[1] = ptr[2] = color; } } } printf(, size_x, size_y); fflush(stdout); fwrite(buf, size_y * size_x * 3, 1, stdout); } int main() { int k; for_k { site[k][0] = frand(size_x); site[k][1] = frand(size_y); rgb [k][0] = frand(256); rgb [k][1] = frand(256); rgb [k][2] = frand(256); } gen_map(); return 0; }
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.each_key{|k| res[k] = Hash.new(0)} g = {}; supply.each_key{|x| g[x] = COSTS[x].keys.sort_by{|g| COSTS[x][g]}} demand.each_key{|x| g[x] = COSTS.keys.sort_by{|g| COSTS[g][x]}} until g.empty? d = demand.collect{|x,y| [x, z = COSTS[g[x][0]][x], g[x][1]? COSTS[g[x][1]][x] - z: z]} dmax = d.max_by{|n| n[2]} d = d.select{|x| x[2] == dmax[2]}.min_by{|n| n[1]} s = supply.collect{|x,y| [x, z = COSTS[x][g[x][0]], g[x][1]? COSTS[x][g[x][1]] - z: z]} dmax = s.max_by{|n| n[2]} s = s.select{|x| x[2] == dmax[2]}.min_by{|n| n[1]} t,f = d[2]==s[2]? [s[1], d[1]]: [d[2],s[2]] d,s = t > f? [d[0],g[d[0]][0]]: [g[s[0]][0],s[0]] v = [supply[s], demand[d]].min res[s][d] += v demand[d] -= v if demand[d] == 0 then supply.reject{|k, n| n == 0}.each_key{|x| g[x].delete(d)} g.delete(d) demand.delete(d) end supply[s] -= v if supply[s] == 0 then demand.reject{|k, n| n == 0}.each_key{|x| g[x].delete(s)} g.delete(s) supply.delete(s) end end COLS.each{|n| print , n} puts cost = 0 COSTS.each_key do |g| print g, COLS.each do |n| y = res[g][n] print y if y!= 0 cost += y * COSTS[g][n] print end puts end print , cost
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.09056, 0.02758, 0.00978, 0.02360, 0.00150, 0.01974, 0.00074 }; int best_match(const double *a, const double *b) { double sum = 0, fit, d, best_fit = 1e100; int i, rotate, best_rotate = 0; for (i = 0; i < 26; i++) sum += a[i]; for (rotate = 0; rotate < 26; rotate++) { fit = 0; for (i = 0; i < 26; i++) { d = a[(i + rotate) % 26] / sum - b[i]; fit += d * d / b[i]; } if (fit < best_fit) { best_fit = fit; best_rotate = rotate; } } return best_rotate; } double freq_every_nth(const int *msg, int len, int interval, char *key) { double sum, d, ret; double out[26], accu[26] = {0}; int i, j, rot; for (j = 0; j < interval; j++) { for (i = 0; i < 26; i++) out[i] = 0; for (i = j; i < len; i += interval) out[msg[i]]++; key[j] = rot = best_match(out, freq); key[j] += 'A'; for (i = 0; i < 26; i++) accu[i] += out[(i + rot) % 26]; } for (i = 0, sum = 0; i < 26; i++) sum += accu[i]; for (i = 0, ret = 0; i < 26; i++) { d = accu[i] / sum - freq[i]; ret += d * d / freq[i]; } key[interval] = '\0'; return ret; } int main() { int txt[strlen(encoded)]; int len = 0, j; char key[100]; double fit, best_fit = 1e100; for (j = 0; encoded[j] != '\0'; j++) if (isupper(encoded[j])) txt[len++] = encoded[j] - 'A'; for (j = 1; j < 30; j++) { fit = freq_every_nth(txt, len, j, key); printf(, fit, j, key); if (fit < best_fit) { best_fit = fit; printf(); } printf(); } return 0; }
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.Image {
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(i!=size-2 && arr[i]>arr[i+1]){ ref1 = i; for(j=ref1+1;j<size;j++){ if(arr[j]>=arr[ref1]){ ref2 = j; sum += getWater(arr,ref1+1,ref2-1,ref1); i = ref2; goto start; } else if(j!=size-1 && arr[j] < arr[j+1] && (markerSet==0||(arr[j+1]>=arr[marker]))){ marker = j+1; markerSet = 1; } } if(markerSet==1){ sum += getWater(arr,ref1+1,marker-1,marker); i = marker; markerSet = 0; goto start; } } } return sum; } int main(int argC,char* argV[]) { int *arr,i; if(argC==1) printf(); else{ arr = (int*)malloc((argC-1)*sizeof(int)); for(i=1;i<argC;i++) arr[i-1] = atoi(argV[i]); printf(,netWater(arr,argC-1)); } return 0; }
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 = fromListUnboxed (Z:. nCenters:. 2) $ take (2*nCenters) $ randomRs (0, fromIntegral nCells) (mkStdGen 1) applyReduce2 arr f = traverse arr (\(i:. j) -> i) $ \lookup (Z:.i) -> f (lookup (Z:.i:.0)) (lookup (Z:.i:.1)) minimize1D arr = foldS f h t where indexed arr = traverse arr id (\src idx@(Z:. i) -> (src idx, (fromIntegral i))) (Z:. n) = extent arr iarr = indexed arr h = iarr ! (Z:. 0) t = extract (Z:. 1) (Z:. (n-1)) iarr f min@(!valMin, !iMin ) x@(!val, !i) | val < valMin = x | otherwise = min voronoi :: Int -> Int -> Array D DIM2 Word32 voronoi nCenters nCells = let cellReducer = applyReduce2 (centers nCenters nCells) nearestCenterIndex = snd . (Repa.! Z) . minimize1D in Repa.fromFunction (Z:. nCells:. nCells :: DIM2) $ \ (Z:.i:.j) -> nearestCenterIndex $ cellReducer (sqDistance (fromIntegral i) (fromIntegral j)) genColorTable :: Int -> Array U DIM1 (Word8, Word8, Word8) genColorTable n = fromListUnboxed (Z:. n) $ zip3 l1 l2 l3 where randoms = randomRs (0,255) (mkStdGen 1) (l1, rest1) = splitAt n randoms (l2, rest2) = splitAt n rest1 l3 = take n rest2 colorize :: Array U DIM1 (Word8, Word8, Word8) -> Array D DIM2 Word32 -> Array D DIM2 (Word8, Word8, Word8) colorize ctable = Repa.map $ \x -> ctable Repa.! (Z:. fromIntegral x) main = do let nsites = 150 let ctable = genColorTable nsites voro <- computeP $ colorize ctable (voronoi nsites 512) :: IO (Array U DIM2 (Word8, Word8, Word8)) writeImageToBMP "out.bmp" voro
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 (root <= 1) return; if (tail && tail->str == slast) tail->str = snone; if (!tail) tail = head = &col; else tail->next = &col; while (root) { int r = 1 + (rand() % root); root -= r; col.str = root ? sdown : slast; tree(r, head); } tail->next = 0; } int main(int c, char**v) { int n; if (c < 2 || (n = atoi(v[1])) < 0) n = 8; tree(n, 0); return 0; }
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 VOELJ IKGJB XPHVG" + "ALWQC SNWBU BYHCU HKOCE XJEYK BQKVY KIIEH GRLGH XEOLW AWFOJ" + "ILOVV RHPKD WIHKN ATUHN VRYAQ DIVHX FHRZV QWMWV LGSHN NLVZS" + "JLAKI FHXUF XJLXM TBLQV RXXHR FZXGV LRAJI EXPRV OSMNP KEPDT" + "LPRWM JAZPK LQUZA ALGZX GVLKL GJTUI ITDSU REZXJ ERXZS HMPST" + "MTEOE PAPJH SMFNB YVQUZ AALGA YDNMP AQOWT UHDBV TSMUE UIMVH" + "QGVRW AEFSP EMPVE PKXZY WLKJA GWALT VYYOB YIXOK IHPDS EVLEV" + "RVSGB JOGYW FHKBL GLXYA MVKIS KIEHY IMAPX UOISK PVAGN MZHPW" + "TTZPV XFCCD TUHJH WLAPF YULTB UXJLN SIJVV YOVDJ SOLXG TGRVO" + "SFRII CTMKO JFCQF KTINQ BWVHG TENLH HOGCS PSFPV GJOKM SIFPR" + "ZPAAS ATPTZ FTPPD PORRF TAXZP KALQA WMIUD BWNCT LEFKO ZQDLX" + "BUXJL ASIMR PNMBF ZCYLV WAPVF QRHZV ZGZEF KBYIO OFXYE VOWGB" + "BXVCB XBAWG LQKCM ICRRX MACUO IKHQU AJEGL OIJHH XPVZW JEWBA" + "FWAML ZZRXJ EKAHV FASMU LVVUT TGK" var freq = [26]float64{ 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.09056, 0.02758, 0.00978, 0.02360, 0.00150, 0.01974, 0.00074, } func sum(a []float64) (sum float64) { for _, f := range a { sum += f } return } func bestMatch(a []float64) int { sum := sum(a) bestFit, bestRotate := 1e100, 0 for rotate := 0; rotate < 26; rotate++ { fit := 0.0 for i := 0; i < 26; i++ { d := a[(i+rotate)%26]/sum - freq[i] fit += d * d / freq[i] } if fit < bestFit { bestFit, bestRotate = fit, rotate } } return bestRotate } func freqEveryNth(msg []int, key []byte) float64 { l := len(msg) interval := len(key) out := make([]float64, 26) accu := make([]float64, 26) for j := 0; j < interval; j++ { for k := 0; k < 26; k++ { out[k] = 0.0 } for i := j; i < l; i += interval { out[msg[i]]++ } rot := bestMatch(out) key[j] = byte(rot + 65) for i := 0; i < 26; i++ { accu[i] += out[(i+rot)%26] } } sum := sum(accu) ret := 0.0 for i := 0; i < 26; i++ { d := accu[i]/sum - freq[i] ret += d * d / freq[i] } return ret } func decrypt(text, key string) string { var sb strings.Builder ki := 0 for _, c := range text { if c < 'A' || c > 'Z' { continue } ci := (c - rune(key[ki]) + 26) % 26 sb.WriteRune(ci + 65) ki = (ki + 1) % len(key) } return sb.String() } func main() { enc := strings.Replace(encoded, " ", "", -1) txt := make([]int, len(enc)) for i := 0; i < len(txt); i++ { txt[i] = int(enc[i] - 'A') } bestFit, bestKey := 1e100, "" fmt.Println(" Fit Length Key") for j := 1; j <= 26; j++ { key := make([]byte, j) fit := freqEveryNth(txt, key) sKey := string(key) fmt.Printf("%f %2d %s", fit, j, sKey) if fit < bestFit { bestFit, bestKey = fit, sKey fmt.Print(" <--- best so far") } fmt.Println() } fmt.Println("\nBest key:", bestKey) fmt.Printf("\nDecrypted text:\n%s\n", decrypt(enc, bestKey)) }
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; strcpy(fn, dname); fn[len++] = '/'; if (!(dir = opendir(dname))) { warn(, dname); return WALK_BADIO; } errno = 0; while ((dent = readdir(dir))) { if (!(spec & WS_DOTFILES) && dent->d_name[0] == '.') continue; if (!strcmp(dent->d_name, ) || !strcmp(dent->d_name, )) continue; strncpy(fn + len, dent->d_name, FILENAME_MAX - len); if (lstat(fn, &st) == -1) { warn(, fn); res = WALK_BADIO; continue; } if (S_ISLNK(st.st_mode) && !(spec & WS_FOLLOWLINK)) continue; if (S_ISDIR(st.st_mode)) { if ((spec & WS_RECURSIVE)) walk_recur(fn, reg, spec); if (!(spec & WS_MATCHDIRS)) continue; } if (!regexec(reg, fn, 0, 0, 0)) puts(fn); } if (dir) closedir(dir); return res ? res : errno ? WALK_BADIO : WALK_OK; } int walk_dir(char *dname, char *pattern, int spec) { regex_t r; int res; if (regcomp(&r, pattern, REG_EXTENDED | REG_NOSUB)) return WALK_BADPATTERN; res = walk_recur(dname, &r, spec); regfree(&r); return res; } int main() { int r = walk_dir(, , WS_DEFAULT|WS_MATCHDIRS); switch(r) { case WALK_OK: break; case WALK_BADIO: err(1, ); case WALK_BADPATTERN: err(1, ); case WALK_NAMETOOLONG: err(1, ); default: err(1, ); } return 0; }
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 + " matching '" + re_pattern +"':"); walkDirectoryFilter(dir.Subfolders, re_pattern); } 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(); } } walkDirectory(dir, '\\.txt$');
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 (+) . fmap (,1) breakup :: Int -> [a] -> [[a]] breakup _ [] = [] breakup n as = let (h, r) = splitAt n as in h:breakup n r distribute :: [a] -> Int -> [[a]] distribute as n = transpose $ breakup n as coincidence :: (Ord a, Fractional b) => [a] -> b coincidence str = let charCounts = snd <$> toList (countEntries str) strln = length str d = fromIntegral $ strln * (strln - 1) n = fromIntegral $ sum $ fmap (\cc -> cc * (cc-1)) charCounts in n / d rate :: (Ord a, Fractional b) => [[a]] -> b rate d = average (fmap coincidence d) - fromIntegral (length d) / 3000.0 dot :: Num a => [a] -> [a] -> a dot v0 v1 = sum $ zipWith (*) v0 v1 rotateAndDot :: Num a => [a] -> [a] -> Char -> a rotateAndDot v0 v1 letter = dot v0 (drop (ord letter - ord 'A') (cycle v1)) getKeyChar :: RealFrac a => [a] -> String -> Char getKeyChar expected sample = let charCounts = countEntries sample countInSample c = findWithDefault 0 c charCounts actual = fmap (fromIntegral . countInSample) ['A'..'Z'] in maximumBy (comparing $ rotateAndDot expected actual) ['A'..'Z'] main = do let cr = filter (/=' ') crypt distributions = fmap (distribute cr) [1..length cr `div` 20] bestDistribution = maximumBy (comparing rate) distributions key = fmap (getKeyChar englishFrequencies) bestDistribution alphaSum a b = ['A'..'Z'] !! ((ord b - ord a) `mod` 26) mapM_ putStrLn ["Key: " ++ key, "Decrypted Text: " ++ zipWith alphaSum (cycle key) cr] englishFrequencies = [ 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.09056, 0.02758, 0.00978, 0.02360, 0.00150, 0.01974, 0.00074 ] crypt = "\ \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 XJEYK BQKVY KIIEH GRLGH XEOLW AWFOJ\ \ILOVV RHPKD WIHKN ATUHN VRYAQ DIVHX FHRZV QWMWV LGSHN NLVZS\ \JLAKI FHXUF XJLXM TBLQV RXXHR FZXGV LRAJI EXPRV OSMNP KEPDT\ \LPRWM JAZPK LQUZA ALGZX GVLKL GJTUI ITDSU REZXJ ERXZS HMPST\ \MTEOE PAPJH SMFNB YVQUZ AALGA YDNMP AQOWT UHDBV TSMUE UIMVH\ \QGVRW AEFSP EMPVE PKXZY WLKJA GWALT VYYOB YIXOK IHPDS EVLEV\ \RVSGB JOGYW FHKBL GLXYA MVKIS KIEHY IMAPX UOISK PVAGN MZHPW\ \TTZPV XFCCD TUHJH WLAPF YULTB UXJLN SIJVV YOVDJ SOLXG TGRVO\ \SFRII CTMKO JFCQF KTINQ BWVHG TENLH HOGCS PSFPV GJOKM SIFPR\ \ZPAAS ATPTZ FTPPD PORRF TAXZP KALQA WMIUD BWNCT LEFKO ZQDLX\ \BUXJL ASIMR PNMBF ZCYLV WAPVF QRHZV ZGZEF KBYIO OFXYE VOWGB\ \BXVCB XBAWG LQKCM ICRRX MACUO IKHQU AJEGL OIJHH XPVZW JEWBA\ \FWAML ZZRXJ EKAHV FASMU LVVUT TGK\ \"
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 { static double p = 3; static BufferedImage I; static int px[], py[], color[], cells = 100, size = 1000; public Voronoi() { super("Voronoi Diagram"); setBounds(0, 0, size, size); setDefaultCloseOperation(EXIT_ON_CLOSE); int n = 0; Random rand = new Random(); I = new BufferedImage(size, size, BufferedImage.TYPE_INT_RGB); px = new int[cells]; py = new int[cells]; color = new int[cells]; for (int i = 0; i < cells; i++) { px[i] = rand.nextInt(size); py[i] = rand.nextInt(size); color[i] = rand.nextInt(16777215); } for (int x = 0; x < size; x++) { for (int y = 0; y < size; y++) { n = 0; for (byte i = 0; i < cells; i++) { if (distance(px[i], x, py[i], y) < distance(px[n], x, py[n], y)) { n = i; } } I.setRGB(x, y, color[n]); } } Graphics2D g = I.createGraphics(); g.setColor(Color.BLACK); for (int i = 0; i < cells; i++) { g.fill(new Ellipse2D .Double(px[i] - 2.5, py[i] - 2.5, 5, 5)); } try { ImageIO.write(I, "png", new File("voronoi.png")); } catch (IOException e) { } } public void paint(Graphics g) { g.drawImage(I, 0, 0, this); } static double distance(int x1, int x2, int y1, int y2) { double d; d = Math.sqrt((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2));
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 XJEYK BQKVY KIIEH GRLGH XEOLW AWFOJ ILOVV RHPKD WIHKN ATUHN VRYAQ DIVHX FHRZV QWMWV LGSHN NLVZS JLAKI FHXUF XJLXM TBLQV RXXHR FZXGV LRAJI EXPRV OSMNP KEPDT LPRWM JAZPK LQUZA ALGZX GVLKL GJTUI ITDSU REZXJ ERXZS HMPST MTEOE PAPJH SMFNB YVQUZ AALGA YDNMP AQOWT UHDBV TSMUE UIMVH QGVRW AEFSP EMPVE PKXZY WLKJA GWALT VYYOB YIXOK IHPDS EVLEV RVSGB JOGYW FHKBL GLXYA MVKIS KIEHY IMAPX UOISK PVAGN MZHPW TTZPV XFCCD TUHJH WLAPF YULTB UXJLN SIJVV YOVDJ SOLXG TGRVO SFRII CTMKO JFCQF KTINQ BWVHG TENLH HOGCS PSFPV GJOKM SIFPR ZPAAS ATPTZ FTPPD PORRF TAXZP KALQA WMIUD BWNCT LEFKO ZQDLX BUXJL ASIMR PNMBF ZCYLV WAPVF QRHZV ZGZEF KBYIO OFXYE VOWGB BXVCB XBAWG LQKCM ICRRX MACUO IKHQU AJEGL OIJHH XPVZW JEWBA FWAML ZZRXJ EKAHV FASMU LVVUT TGK"; final static 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.09056, 0.02758, 0.00978, 0.02360, 0.00150, 0.01974, 0.00074 }; public static void main(String[] args) { int lenghtOfEncodedMessage = encodedMessage.length(); char[] encoded = new char [lenghtOfEncodedMessage] ; char[] key = new char [lenghtOfEncodedMessage] ; encodedMessage.getChars(0, lenghtOfEncodedMessage, encoded, 0); int txt[] = new int[lenghtOfEncodedMessage]; int len = 0, j; double fit, best_fit = 1e100; for (j = 0; j < lenghtOfEncodedMessage; j++) if (Character.isUpperCase(encoded[j])) txt[len++] = encoded[j] - 'A'; for (j = 1; j < 30; j++) { fit = freq_every_nth(txt, len, j, key); System.out.printf("%f, key length:%2d ", fit, j); System.out.print(key); if (fit < best_fit) { best_fit = fit; System.out.print(" <--- best so far"); } System.out.print("\n"); } } 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; } static int best_match(final double []a, final double []b) { double sum = 0, fit, d, best_fit = 1e100; int i, rotate, best_rotate = 0; for (i = 0; i < 26; i++) sum += a[i]; for (rotate = 0; rotate < 26; rotate++) { fit = 0; for (i = 0; i < 26; i++) { d = a[(i + rotate) % 26] / sum - b[i]; fit += d * d / b[i]; } if (fit < best_fit) { best_fit = fit; best_rotate = rotate; } } return best_rotate; } static double freq_every_nth(final int []msg, int len, int interval, char[] key) { double sum, d, ret; double [] accu = new double [26]; double [] out = new double [26]; int i, j, rot; for (j = 0; j < interval; j++) { for (i = 0; i < 26; i++) out[i] = 0; for (i = j; i < len; i += interval) out[msg[i]]++; rot = best_match(out, freq); try{ key[j] = (char)(rot + 'A'); } catch (Exception e) { System.out.print(e.getMessage()); } for (i = 0; i < 26; i++) accu[i] += out[(i + rot) % 26]; } for (i = 0, sum = 0; i < 26; i++) sum += accu[i]; for (i = 0, ret = 0; i < 26; i++) { d = accu[i] / sum - freq[i]; ret += d * d / freq[i]; } key[interval] = '\0'; return ret; } }
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(sizeof(int), n); double ratio; while (i--) bins[gen() - 1]++; for (i = 0; i < n; i++) { ratio = bins[i] * n / (double)cnt - 1; if (ratio > -delta && ratio < delta) continue; printf(, i + 1, bins[i], ratio * 100, delta * 100); break; } free(bins); return i == n; } int main() { int cnt = 1; while ((cnt *= 10) <= 1000000) { printf(, cnt); printf(check(rand5_7, 7, cnt, 0.03) ? : ); } return 0; }
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 => 1.29, V => 0.98, K => 0.77, J => 0.15, X => 0.15, Q => 0.10, Z => 0.07 ); my @alphabet = sort keys %English_letter_freq; my $max_key_lengths = 5; sub myguess { my ($text) = (@_); my ($seqtext, @spacing, @factors, @sortedfactors, $pos, %freq, %Keys); $seqtext = $text; while ($seqtext =~ /(...).*\1/) { $seqtext = substr($seqtext, 1+index($seqtext, $1)); push @spacing, 1 + index($seqtext, $1); } for my $j (@spacing) { push @factors, grep { $j % $_ == 0 } 2..$j; } $freq{$_}++ for @factors; @sortedfactors = grep { $_ >= 4 } sort { $freq{$b} <=> $freq{$a} } keys %freq; for my $keylen ( @sortedfactors[0..$max_key_lengths-1] ) { my $keyguess = ''; for (my $i = 0; $i < $keylen; $i++) { my($mykey, %chi_values, $bestguess); for (my $j = 0; $j < length($text); $j += $keylen) { $mykey .= substr($text, ($j+$i) % length($text), 1); } for my $subkey (@alphabet) { my $decrypted = mycrypt($mykey, $subkey); my $length = length($decrypted); for my $char (@alphabet) { my $expected = $English_letter_freq{$char} * $length / 100; my $observed; ++$observed while $decrypted =~ /$char/g; $chi_values{$subkey} += ($observed - $expected)**2 / $expected if $observed; } } $Keys{$keylen}{score} = $chi_values{'A'}; for my $sk (sort keys %chi_values) { if ($chi_values{$sk} <= $Keys{$keylen}{score}) { $bestguess = $sk; $Keys{$keylen}{score} = $chi_values{$sk}; } } $keyguess .= $bestguess; } $Keys{$keylen}{key} = $keyguess; } map { $Keys{$_}{key} } sort { $Keys{$a}{score} <=> $Keys{$b}{score}} keys %Keys; } sub mycrypt { my ($text, $key) = @_; my ($new_text, %values_numbers); my $keylen = length($key); @values_numbers{@alphabet} = 0..25; my %values_letters = reverse %values_numbers; for (my $i = 0; $i < length($text); $i++) { my $val = -1 * $values_numbers{substr( $key, $i%$keylen, 1)} + $values_numbers{substr($text, $i, 1)}; $new_text .= $values_letters{ $val % 26 }; } return $new_text; } my $cipher_text = <<~'EOD'; 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 XJEYK BQKVY KIIEH GRLGH XEOLW AWFOJ ILOVV RHPKD WIHKN ATUHN VRYAQ DIVHX FHRZV QWMWV LGSHN NLVZS JLAKI FHXUF XJLXM TBLQV RXXHR FZXGV LRAJI EXPRV OSMNP KEPDT LPRWM JAZPK LQUZA ALGZX GVLKL GJTUI ITDSU REZXJ ERXZS HMPST MTEOE PAPJH SMFNB YVQUZ AALGA YDNMP AQOWT UHDBV TSMUE UIMVH QGVRW AEFSP EMPVE PKXZY WLKJA GWALT VYYOB YIXOK IHPDS EVLEV RVSGB JOGYW FHKBL GLXYA MVKIS KIEHY IMAPX UOISK PVAGN MZHPW TTZPV XFCCD TUHJH WLAPF YULTB UXJLN SIJVV YOVDJ SOLXG TGRVO SFRII CTMKO JFCQF KTINQ BWVHG TENLH HOGCS PSFPV GJOKM SIFPR ZPAAS ATPTZ FTPPD PORRF TAXZP KALQA WMIUD BWNCT LEFKO ZQDLX BUXJL ASIMR PNMBF ZCYLV WAPVF QRHZV ZGZEF KBYIO OFXYE VOWGB BXVCB XBAWG LQKCM ICRRX MACUO IKHQU AJEGL OIJHH XPVZW JEWBA FWAML ZZRXJ EKAHV FASMU LVVUT TGK EOD my $text = uc($cipher_text) =~ s/[^@{[join '', @alphabet]}]//gr; for my $key ( myguess($text) ) { say "Key $key\n" . "Key length " . length($key) . "\n" . "Plaintext " . substr(mycrypt($text, $key), 0, 80) . "...\n"; }
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)]))) (doseq [n [100 1000 10000] [num count okay?] (verify #(rand-int 7) n)] (println "Saw" num count "times:" (if okay? "that's" " not") "acceptable"))
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, 3, 2, 1, 0, 4}, {9, 8, 7, 6, 5, 4, 3, 2, 1, 0}, }; static const int inv[] = {0, 4, 3, 2, 1, 5, 6, 7, 8, 9}; static const int p[][10] = { {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}, {1, 5, 7, 6, 2, 8, 3, 0, 9, 4}, {5, 8, 0, 3, 7, 9, 6, 1, 4, 2}, {8, 9, 1, 6, 0, 4, 3, 5, 2, 7}, {9, 4, 5, 3, 1, 2, 6, 8, 7, 0}, {4, 2, 8, 6, 5, 7, 3, 9, 0, 1}, {2, 7, 9, 3, 8, 0, 6, 4, 1, 5}, {7, 0, 4, 6, 9, 1, 3, 2, 5, 8}, }; int verhoeff(const char* s, bool validate, bool verbose) { if (verbose) { const char* t = validate ? : ; printf(, t, s); puts(u8); puts(); } int len = strlen(s); if (validate) --len; int c = 0; for (int i = len; i >= 0; --i) { int ni = (i == len && !validate) ? 0 : s[i] - '0'; assert(ni >= 0 && ni < 10); int pi = p[(len - i) % 8][ni]; c = d[c][pi]; if (verbose) printf(, len - i, ni, pi, c); } if (verbose && !validate) printf(, c, inv[c]); return validate ? c == 0 : inv[c]; } int main() { const char* ss[3] = {, , }; for (int i = 0; i < 3; ++i) { const char* s = ss[i]; bool verbose = i < 2; int c = verhoeff(s, false, verbose); printf(, s, c); int len = strlen(s); char sc[len + 2]; strncpy(sc, s, len + 2); for (int j = 0; j < 2; ++j) { sc[len] = (j == 0) ? c + '0' : '9'; int v = verhoeff(sc, true, verbose); printf(, sc, v ? : ); } } return 0; }
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; encrypt = false; break; default: fprintf(stderr, , opt); fprintf(stderr, , usage); return 1; } } if (argc - optind != 1) { fprintf(stderr, , argv[0]); fprintf(stderr, , usage); return 1; } char const *const restrict key = argv[optind]; size_t const keylen = strlen(key); char shifts[keylen]; char const *restrict plaintext = NULL; for (size_t i = 0; i < keylen; i++) { if (!(isalpha(key[i]))) { fprintf(stderr, ); return 2; } char const charcase = (isupper(key[i])) ? 'A' : 'a'; shifts[i] = (key[i] - charcase) * sign; } do { fflush(stdout); printf(, (encrypt) ? plainmsg : cryptmsg); plaintext = get_input(); if (plaintext == NULL) { fprintf(stderr, ); return 4; } } while (strcmp(plaintext, ) == 0); size_t const plainlen = strlen(plaintext); char* const restrict ciphertext = calloc(plainlen + 1, sizeof *ciphertext); if (ciphertext == NULL) { fprintf(stderr, ); return 5; } for (size_t i = 0, j = 0; i < plainlen; i++) { if (!(isalpha(plaintext[i]))) { ciphertext[i] = plaintext[i]; continue; } char const charcase = (isupper(plaintext[i])) ? 'A' : 'a'; ciphertext[i] = ((plaintext[i] + shifts[j] - charcase + NUMLETTERS) % NUMLETTERS) + charcase; j = (j+1) % keylen; } ciphertext[plainlen] = '\0'; printf(, (encrypt) ? cryptmsg : plainmsg, ciphertext); free(ciphertext); free((char*) plaintext); return 0; } char *get_input(void) { char *const restrict buf = malloc(BUFSIZE * sizeof (char)); if (buf == NULL) { return NULL; } fgets(buf, BUFSIZE, stdin); size_t const len = strlen(buf); if (buf[len - 1] == '\n') buf[len - 1] = '\0'; return buf; }
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][1] += 1 return result def correlation(input): result = 0.0 freq = frequency(input) freq.sort(key=itemgetter(1)) for i, f in enumerate(freq): result += f[1] * sorted_targets[i] return result cleaned = [ord(c) for c in input.upper() if c.isupper()] best_len = 0 best_corr = -100.0 for i in xrange(2, len(cleaned) pieces = [[] for _ in xrange(i)] for j, c in enumerate(cleaned): pieces[j% i].append(c) corr = -0.5 * i + sum(correlation(p) for p in pieces) if corr > best_corr: best_len = i best_corr = corr if best_len == 0: return (, ) pieces = [[] for _ in xrange(best_len)] for i, c in enumerate(cleaned): pieces[i% best_len].append(c) freqs = [frequency(p) for p in pieces] key = for fr in freqs: fr.sort(key=itemgetter(1), reverse=True) m = 0 max_corr = 0.0 for j in xrange(nchars): corr = 0.0 c = ordA + j for frc in fr: d = (ord(frc[0]) - c + nchars)% nchars corr += frc[1] * target_freqs[d] if corr > max_corr: m = j max_corr = corr key += chr(m + ordA) r = (chr((c - ord(key[i% best_len]) + nchars)% nchars + ordA) for i, c in enumerate(cleaned)) return (key, .join(r)) def main(): encoded = english_frequences = [ 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.09056, 0.02758, 0.00978, 0.02360, 0.00150, 0.01974, 0.00074] (key, decoded) = vigenere_decrypt(english_frequences, encoded) print , key print , decoded main()
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, 1, 0, 4, 3}, {8, 7, 6, 5, 9, 3, 2, 1, 0, 4}, {9, 8, 7, 6, 5, 4, 3, 2, 1, 0}, } var inv = []int{0, 4, 3, 2, 1, 5, 6, 7, 8, 9} var p = [][]int{ {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}, {1, 5, 7, 6, 2, 8, 3, 0, 9, 4}, {5, 8, 0, 3, 7, 9, 6, 1, 4, 2}, {8, 9, 1, 6, 0, 4, 3, 5, 2, 7}, {9, 4, 5, 3, 1, 2, 6, 8, 7, 0}, {4, 2, 8, 6, 5, 7, 3, 9, 0, 1}, {2, 7, 9, 3, 8, 0, 6, 4, 1, 5}, {7, 0, 4, 6, 9, 1, 3, 2, 5, 8}, } func verhoeff(s string, validate, table bool) interface{} { if table { t := "Check digit" if validate { t = "Validation" } fmt.Printf("%s calculations for '%s':\n\n", t, s) fmt.Println(" i n p[i,n] c") fmt.Println("------------------") } if !validate { s = s + "0" } c := 0 le := len(s) - 1 for i := le; i >= 0; i-- { ni := int(s[i] - 48) pi := p[(le-i)%8][ni] c = d[c][pi] if table { fmt.Printf("%2d %d %d %d\n", le-i, ni, pi, c) } } if table && !validate { fmt.Printf("\ninv[%d] =%d\n", c, inv[c]) } if !validate { return inv[c] } return c == 0 } func main() { ss := []string{"236", "12345", "123456789012"} ts := []bool{true, true, false, true} for i, s := range ss { c := verhoeff(s, false, ts[i]).(int) fmt.Printf("\nThe check digit for '%s' is '%d'\n\n", s, c) for _, sc := range []string{s + string(c+48), s + "9"} { v := verhoeff(sc, true, ts[i]).(bool) ans := "correct" if !v { ans = "incorrect" } fmt.Printf("\nThe validation for '%s' is%s\n\n", sc, ans) } } }
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 XJEYK BQKVY KIIEH GRLGH XEOLW AWFOJ ILOVV RHPKD WIHKN ATUHN VRYAQ DIVHX FHRZV QWMWV LGSHN NLVZS JLAKI FHXUF XJLXM TBLQV RXXHR FZXGV LRAJI EXPRV OSMNP KEPDT LPRWM JAZPK LQUZA ALGZX GVLKL GJTUI ITDSU REZXJ ERXZS HMPST MTEOE PAPJH SMFNB YVQUZ AALGA YDNMP AQOWT UHDBV TSMUE UIMVH QGVRW AEFSP EMPVE PKXZY WLKJA GWALT VYYOB YIXOK IHPDS EVLEV RVSGB JOGYW FHKBL GLXYA MVKIS KIEHY IMAPX UOISK PVAGN MZHPW TTZPV XFCCD TUHJH WLAPF YULTB UXJLN SIJVV YOVDJ SOLXG TGRVO SFRII CTMKO JFCQF KTINQ BWVHG TENLH HOGCS PSFPV GJOKM SIFPR ZPAAS ATPTZ FTPPD PORRF TAXZP KALQA WMIUD BWNCT LEFKO ZQDLX BUXJL ASIMR PNMBF ZCYLV WAPVF QRHZV ZGZEF KBYIO OFXYE VOWGB BXVCB XBAWG LQKCM ICRRX MACUO IKHQU AJEGL OIJHH XPVZW JEWBA FWAML ZZRXJ EKAHV FASMU LVVUT TGK"; const FREQUENCIES: [f32; 26] = [ 0.08167, 0.01492, 0.02202, 0.04253, 0.12702, 0.02228, 0.02015, 0.06094, 0.06966, 0.00153, 0.01292, 0.04025, 0.02406, 0.06749, 0.07507, 0.01929, 0.00095, 0.05987, 0.06327, 0.09356, 0.02758, 0.00978, 0.02560, 0.00150, 0.01994, 0.00077, ]; fn best_match(a: &[f32]) -> u8 { let sum: f32 = a.iter().sum(); let mut best_fit = std::f32::MAX; let mut best_rotate = 0; for rotate in 0..=25 { let mut fit = 0.; for i in 0..=25 { let char_freq = FREQUENCIES[i]; let idx = (i + rotate as usize)% 26 as usize; let d = a[idx] / sum - char_freq; fit += d * d / char_freq; } if fit < best_fit { best_fit = fit; best_rotate = rotate; } } best_rotate } fn freq_every_nth(msg: &[u8], key: &mut [char]) -> f32 { let len = msg.len(); let interval = key.len(); let mut accu = [0.; 26]; for j in 0..interval { let mut out = [0.; 26]; for i in (j..len).step_by(interval) { let idx = msg[i] as usize; out[idx] += 1.; } let rot = best_match(&out); key[j] = char::from(rot + b'A'); for i in 0..=25 { let idx: usize = (i + rot as usize)% 26; accu[i] += out[idx]; } } let sum: f32 = accu.iter().sum(); let mut ret = 0.; for i in 0..=25 { let char_freq = FREQUENCIES[i]; let d = accu[i] / sum - char_freq; ret += d * d / char_freq; } ret } fn decrypt(text: &str, key: &str) -> String { let key_chars_cycle = key.as_bytes().iter().map(|b| *b as i32).cycle(); let is_ascii_uppercase = |c: &u8| (b'A'..=b'Z').contains(c); text.as_bytes() .iter() .filter(|c| is_ascii_uppercase(c)) .map(|b| *b as i32) .zip(key_chars_cycle) .fold(String::new(), |mut acc, (c, key_char)| { let ci: u8 = ((c - key_char + 26)% 26) as u8; acc.push(char::from(b'A' + ci)); acc }) } fn main() { let enc = CRYPTOGRAM .split_ascii_whitespace() .collect::<Vec<_>>() .join(""); let cryptogram: Vec<u8> = enc.as_bytes().iter().map(|b| u8::from(b - b'A')).collect(); let mut best_fit = std::f32::MAX; let mut best_key = String::new(); for j in 1..=26 { let mut key = vec!['\0'; j]; let fit = freq_every_nth(&cryptogram, &mut key); let s_key = String::from_iter(key);
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){ max = hm[i] } res[i] = max; } return res } func min(a,b []int) []int { res := make([]int,len(a)) for i := 0; i < len(a);i++{ if a[i] >= b[i]{ res[i] = b[i] }else { res[i] = a[i] } } return res } func diff(hm, min []int) []int { res := make([]int,len(hm)) for i := 0; i < len(hm);i++{ if min[i] > hm[i]{ res[i] = min[i] - hm[i] } } return res } func sum(a []int) int { res := 0 for i := 0; i < len(a);i++{ res += a[i] } return res } func waterCollected(hm []int) int { maxr := maxr(hm) maxl := maxl(hm) min := min(maxr,maxl) diff := diff(hm,min) sum := sum(diff) return sum } func main() { fmt.Println(waterCollected([]int{1, 5, 3, 7, 2})) fmt.Println(waterCollected([]int{5, 3, 7, 2, 6, 4, 5, 9, 1, 2})) fmt.Println(waterCollected([]int{2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1})) fmt.Println(waterCollected([]int{5, 5, 5, 5})) fmt.Println(waterCollected([]int{5, 6, 7, 8})) fmt.Println(waterCollected([]int{8, 7, 7, 6})) fmt.Println(waterCollected([]int{6, 7, 10, 7, 6})) }
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 }, ); my($xmax, $ymax) = (400, 400); my @domains; for (1..30) { push @domains, { x => int 5 + rand $xmax-10, y => int 5 + rand $ymax-10, rgb => [int rand 255, int rand 255, int rand 255] } } for my $type (keys %type) { our $img = Imager->new(xsize => $xmax, ysize => $ymax, channels => 3); voronoi($type, $xmax, $ymax, @domains); dot(1,@domains); $img->write(file => "voronoi-$type.png"); sub voronoi { my($type, $xmax, $ymax, @d) = @_; for my $x (0..$xmax) { for my $y (0..$ymax) { my $i = 0; my $d = 10e6; for (0..$ my $dd = &{$type{$type}}($d[$_]{'x'}, $d[$_]{'y'}, $x, $y); if ($dd < $d) { $d = $dd; $i = $_ } } $img->setpixel(x => $x, y => $y, color => $d[$i]{rgb} ); } } } sub dot { my($radius, @d) = @_; for (0..$ my $dx = $d[$_]{'x'}; my $dy = $d[$_]{'y'}; for my $x ($dx-$radius .. $dx+$radius) { for my $y ($dy-$radius .. $dy+$radius) { $img->setpixel(x => $x, y => $y, color => [0,0,0]); } } } } }
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; } double Gamma_Spouge( double z ) { int k; static double cspace[A]; static double *coefs = NULL; double accum; double a = A; if (!coefs) { double k1_factrl = 1.0; coefs = cspace; coefs[0] = sqrt(2.0*M_PI); for(k=1; k<A; k++) { coefs[k] = exp(a-k) * pow(a-k,k-0.5) / k1_factrl; k1_factrl *= -k; } } accum = coefs[0]; for (k=1; k<A; k++) { accum += coefs[k]/(z+k); } accum *= exp(-(z+a)) * pow(z+a, z+0.5); return accum/z; } double aa1; double f0( double t) { return pow(t, aa1)*exp(-t); } double GammaIncomplete_Q( double a, double x) { double y, h = 1.5e-2; y = aa1 = a-1; while((f0(y) * (x-y) > 2.0e-8) && (y < x)) y += .4; if (y>x) y=x; return 1.0 - Simpson3_8( &f0, 0, y, (int)(y/h))/Gamma_Spouge(a); }
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 (apply op (list (to-num text) (to-num key))))) (defn crypt [op text key] (let [xcrypt1 (partial #'crypt1 op)] (apply #'str (map xcrypt1 (to-normalized-seq text) (cycle (to-normalized-seq key)))))) (defn encrypt [plaintext key] (crypt #'+ plaintext key)) (defn decrypt [ciphertext key] (crypt #'- ciphertext key))
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 . waterCollected . V.fromList) [ [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
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 8 2 1 0 4 3 8 7 6 5 9 3 2 1 0 4 9 8 7 6 5 4 3 2 1 0 END my @p = map [ split ], split /\n/, <<END; 0 1 2 3 4 5 6 7 8 9 1 5 7 6 2 8 3 0 9 4 5 8 0 3 7 9 6 1 4 2 8 9 1 6 0 4 3 5 2 7 9 4 5 3 1 2 6 8 7 0 4 2 8 6 5 7 3 9 0 1 2 7 9 3 8 0 6 4 1 5 7 0 4 6 9 1 3 2 5 8 END my $debug; sub generate { local $_ = shift() . 0; my $c = my $i = 0; my ($n, $p); $debug and print "i ni d(c,p(i%8,ni)) c\n"; while( length ) { $c = $d[ $c ][ $p = $p[ $i % 8 ][ $n = chop ] ]; $debug and printf "%d%3d%7d%10d\n", $i, $n, $p, $c; $i++; } return $inv[ $c ]; } sub validate { shift =~ /(\d+)(\d)/ and $2 == generate($1) } for ( 236, 12345, 123456789012 ) { print "testing $_\n"; $debug = length() < 6; my $checkdigit = generate($_); print "check digit for $_ is $checkdigit\n"; $debug = 0; for my $cd ( $checkdigit, 9 ) { print "$_$cd is ", validate($_ . $cd) ? '' : 'not ', "valid\n"; } print "\n"; }
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}, }}}}, &Node{"b", nil}, &Node{"c", nil}, }} b, err := json.MarshalIndent(tree, "", " ") if err != nil { log.Fatal(err) } fmt.Println(string(b)) }
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) / fromIntegral (length group) ul = round $ (100 + fromIntegral d)/100 * avg ll = round $ (100 - fromIntegral d)/100 * avg return $ map (head &&& (id &&& liftM2 (&&) (>ll)(<ul)).length) group
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 ++ (" `" ++ r):map (" "++) rs where (r:rs) = treeIndent$right t ls = treeIndent$left t main = mapM_ putStrLn $ treeIndent tree
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, 5, 5, 5}, new int[]{5, 6, 7, 8}, new int[]{8, 7, 7, 6}, new int[]{6, 7, 10, 7, 6} }; for (int[] tea : tba) { int rht, wu = 0, bof; do { for (rht = tea.length - 1; rht >= 0; rht--) { if (tea[rht] > 0) { break; } } if (rht < 0) { break; } bof = 0; for (int col = 0; col <= rht; col++) { if (tea[col] > 0) { tea[col]--; bof += 1; } else if (bof > 0) { wu++; } } if (bof < 2) { break; } } while (true); System.out.printf("Block%d", i++); if (wu == 0) { System.out.print(" does not hold any"); } else { System.out.printf(" holds%d", wu); } System.out.println(" water units."); } } }
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, 7, 6, 5, 9, 3, 2, 1, 0, 4), (9, 8, 7, 6, 5, 4, 3, 2, 1, 0), ] INV = (0, 4, 3, 2, 1, 5, 6, 7, 8, 9) PERMUTATION_TABLE = [ (0, 1, 2, 3, 4, 5, 6, 7, 8, 9), (1, 5, 7, 6, 2, 8, 3, 0, 9, 4), (5, 8, 0, 3, 7, 9, 6, 1, 4, 2), (8, 9, 1, 6, 0, 4, 3, 5, 2, 7), (9, 4, 5, 3, 1, 2, 6, 8, 7, 0), (4, 2, 8, 6, 5, 7, 3, 9, 0, 1), (2, 7, 9, 3, 8, 0, 6, 4, 1, 5), (7, 0, 4, 6, 9, 1, 3, 2, 5, 8), ] def verhoeffchecksum(n, validate=True, terse=True, verbose=False): if verbose: print(f,\ f) c, dig = 0, list(str(n if validate else 10 * n)) for i, ni in enumerate(dig[::-1]): p = PERMUTATION_TABLE[i% 8][int(ni)] c = MULTIPLICATION_TABLE[c][p] if verbose: print(f) if verbose and not validate: print(f) if not terse: print(f\ if validate else f) return c == 0 if validate else INV[c] if __name__ == '__main__': for n, va, t, ve in [ (236, False, False, True), (2363, True, False, True), (2369, True, False, True), (12345, False, False, True), (123451, True, False, True), (123459, True, False, True), (123456789012, False, False, False), (1234567890120, True, False, False), (1234567890129, True, False, False)]: verhoeffchecksum(n, va, t, ve)
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.getAsInt(), (k, v) -> v == null ? 1 : v + 1); double target = nRepeats / (double) counts.size(); int deltaCount = (int) (delta / 100.0 * target); counts.forEach((k, v) -> { if (abs(target - v) >= deltaCount) System.out.printf("distribution potentially skewed " + "for '%s': '%d'%n", k, v); }); counts.keySet().stream().sorted().forEach(k -> System.out.printf("%d%d%n", k, counts.get(k))); } public static void main(String[] a) { distCheck(() -> (int) (Math.random() * 5) + 1, 1_000_000, 1); } }
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(random.randrange(imgy)) nr.append(random.randrange(256)) ng.append(random.randrange(256)) nb.append(random.randrange(256)) for y in range(imgy): for x in range(imgx): dmin = math.hypot(imgx-1, imgy-1) j = -1 for i in range(num_cells): d = math.hypot(nx[i]-x, ny[i]-y) if d < dmin: dmin = d j = i putpixel((x, y), (nr[j], ng[j], nb[j])) image.save(, ) image.show() generate_voronoi_diagram(500, 500, 25)
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 { sum += 3 * f(a+h1*float64(j)) } } return h * sum / 8 } func gammaIncQ(a, x float64) float64 { aa1 := a - 1 var f ifctn = func(t float64) float64 { return math.Pow(t, aa1) * math.Exp(-t) } y := aa1 h := 1.5e-2 for f(y)*(x-y) > 2e-8 && y < x { y += .4 } if y > x { y = x } return 1 - simpson38(f, 0, y, int(y/h/math.Gamma(a))) } func chi2ud(ds []int) float64 { var sum, expected float64 for _, d := range ds { expected += float64(d) } expected /= float64(len(ds)) for _, d := range ds { x := float64(d) - expected sum += x * x } return sum / expected } func chi2p(dof int, distance float64) float64 { return gammaIncQ(.5*float64(dof), .5*distance) } const sigLevel = .05 func main() { for _, dset := range [][]int{ {199809, 200665, 199607, 200270, 199649}, {522573, 244456, 139979, 71531, 21461}, } { utest(dset) } } func utest(dset []int) { fmt.Println("Uniform distribution test") var sum int for _, c := range dset { sum += c } fmt.Println(" dataset:", dset) fmt.Println(" samples: ", sum) fmt.Println(" categories: ", len(dset)) dof := len(dset) - 1 fmt.Println(" degrees of freedom: ", dof) dist := chi2ud(dset) fmt.Println(" chi square test statistic: ", dist) p := chi2p(dof, dist) fmt.Println(" p-value of test statistic: ", p) sig := p < sigLevel fmt.Printf(" significant at%2.0f%% level? %t\n", sigLevel*100, sig) fmt.Println(" uniform? ", !sig, "\n") }
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(val); } else count[val] ++; } vals.sort(function(a,b) {return a-b}); var target = times / vals.length; var tolerance = target * opts['delta'] / 100; for (var i = 0; i < vals.length; i++) { var val = vals[i]; if (Math.abs(count[val] - target) > tolerance) throw "distribution potentially skewed for " + val + ": expected result around " + target + ", got " +count[val]; else print(val + "\t" + count[val]); } } function has_property(obj, propname) { return typeof(obj[propname]) == "undefined" ? false : true; } try { distcheck(function() {return Math.floor(10 * Math.random())}, 100000); print(); distcheck(function() {return (Math.random() > 0.95 ? 1 : 0)}, 100000); } catch (e) { print(e); }
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((abs(x)^3 + abs(y)^3)^0.33333)} } pVoronoiD <- function(ns, fn="", ttl="",mt=1) { cat(" *** START VD:", date(), "\n"); if(mt<1||mt>3) {mt=1}; mts=""; if(mt>1) {mts=paste0(", mt - ",mt)}; m=640; i=j=k=m1=m-2; x=y=d=dm=0; if(fn=="") {pf=paste0("VDR", mt, ns, ".png")} else {pf=paste0(fn, ".png")}; if(ttl=="") {ttl=paste0("Voronoi diagram, sites - ", ns, mts)}; cat(" *** Plot file -", pf, "title:", ttl, "\n"); plot(NA, xlim=c(0,m), ylim=c(0,m), xlab="", ylab="", main=ttl); X=numeric(ns); Y=numeric(ns); C=numeric(ns); for(i in 1:ns) { X[i]=sample(0:m1, 1, replace=TRUE); Y[i]=sample(0:m1, 1, replace=TRUE); C[i]=randHclr(); } for(i in 0:m1) { for(j in 0:m1) { dm=Metric(m1,m1,mt); k=-1; for(n in 1:ns) { d=Metric(X[n]-j,Y[n]-i, mt); if(d<dm) {dm=d; k=n;} } clr=C[k]; segments(j, i, j, i, col=clr); } } points(X, Y, pch = 19, col = "black", bg = "white") dev.copy(png, filename=pf, width=m, height=m); dev.off(); graphics.off(); cat(" *** END VD:",date(),"\n"); } pVoronoiD(150) pVoronoiD(10,"","",2) pVoronoiD(10,"","",3)
54Voronoi diagram
13r
do5nt