code
stringlengths
1
46.1k
label
class label
1.18k classes
domain_label
class label
21 classes
index
stringlengths
4
5
func main() { inf: goto inf }
819Flow-control structures
0go
2bsl7
package main import ( "fmt" "strconv" )
817Floyd-Warshall algorithm
0go
o978q
null
815Forward difference
11kotlin
q3gx1
null
814Four bit adder
1lua
icbot
import Control.Monad import Control.Monad.Trans import Control.Monad.Exit main = do runExitTMaybe $ do forM_ [1..5] $ \x -> do forM_ [1..5] $ \y -> do lift $ print (x, y) when (x == 3 && y == 2) $ exitWith () putStrLn "Done."
819Flow-control structures
8haskell
ad91g
module NumberToWord NUMBERS = { 1 => 'one', 2 => 'two', 3 => 'three', 4 => 'four', 5 => 'five', 6 => 'six', 7 => 'seven', 8 => 'eight', 9 => 'nine', 10 => 'ten', 11 => 'eleven', 12 => 'twelve', 13 => 'thirteen', 14 => 'fourteen', 15 => 'fifteen', 16 => 'sixteen', 17 => 'seventeen', 18 => 'eighteen', 19 => 'nineteen', 20 => 'twenty', 30 => 'thirty', 40 => 'forty', 50 => 'fifty', 60 => 'sixty', 70 => 'seventy', 80 => 'eighty', 90 => 'ninety', 100 => 'hundred', 1000 => 'thousand', 10 ** 6 => 'million', 10 ** 9 => 'billion', 10 ** 12 => 'trillion', 10 ** 15 => 'quadrillion', 10 ** 18 => 'quintillion', 10 ** 21 => 'sextillion', 10 ** 24 => 'septillion', 10 ** 27 => 'octillion', 10 ** 30 => 'nonillion', 10 ** 33 => 'decillion'}.reverse_each.to_h refine Integer do def to_english return 'zero' if i.zero? words = self < 0? ['negative']: [] i = self.abs NUMBERS.each do |k, v| if k <= i then times = i/k words << times.to_english if k >= 100 words << v i -= times * k end return words.join() if i.zero? end end end end using NumberToWord def magic4(n) words = [] until n == 4 s = n.to_english n = s.size words << end words << words.join().capitalize end [0, 4, 6, 11, 13, 75, 337, -164, 9_876_543_209].each{|n| puts magic4(n) }
816Four is magic
14ruby
5aduj
class FloydWarshall { static void main(String[] args) { int[][] weights = [[1, 3, -2], [2, 1, 4], [2, 3, 3], [3, 4, 2], [4, 2, -1]] int numVertices = 4 floydWarshall(weights, numVertices) } static void floydWarshall(int[][] weights, int numVertices) { double[][] dist = new double[numVertices][numVertices] for (double[] row: dist) { Arrays.fill(row, Double.POSITIVE_INFINITY) } for (int[] w: weights) { dist[w[0] - 1][w[1] - 1] = w[2] } int[][] next = new int[numVertices][numVertices] for (int i = 0; i < next.length; i++) { for (int j = 0; j < next.length; j++) { if (i != j) { next[i][j] = j + 1 } } } for (int k = 0; k < numVertices; k++) { for (int i = 0; i < numVertices; i++) { for (int j = 0; j < numVertices; j++) { if (dist[i][k] + dist[k][j] < dist[i][j]) { dist[i][j] = dist[i][k] + dist[k][j] next[i][j] = next[i][k] } } } } printResult(dist, next) } static void printResult(double[][] dist, int[][] next) { println("pair dist path") for (int i = 0; i < next.length; i++) { for (int j = 0; j < next.length; j++) { if (i != j) { int u = i + 1 int v = j + 1 String path = String.format("%d ->%d %2d %s", u, v, (int) dist[i][j], u) boolean loop = true while (loop) { u = next[u - 1][v - 1] path += " -> " + u loop = u != v } println(path) } } } } }
817Floyd-Warshall algorithm
7groovy
xzuwl
mult <- function(a,b) a*b
808Function definition
13r
rx2gj
printf "%09.3f\n", 7.125;
813Formatted numeric output
2perl
tuwfg
(def burn-prob 0.1) (def new-tree-prob 0.5) (defn grow-new-tree? [] (> new-tree-prob (rand))) (defn burn-tree? [] (> burn-prob (rand))) (defn tree-maker [] (if (grow-new-tree?):tree:grass)) (defn make-forest ([] (make-forest 5)) ([size] (take size (repeatedly #(take size (repeatedly tree-maker)))))) (defn tree-at [forest row col] (try (-> forest (nth row) (nth col)) (catch Exception _ false))) (defn neighbores-burning? [forest row col] (letfn [(burnt? [row col] (=:burnt (tree-at forest row col)))] (or (burnt? (inc row) col) (burnt? (dec row) col) (burnt? row (inc col)) (burnt? row (dec col))))) (defn lightning-strike [forest] (map (fn [forest-row] (map #(if (and (= %:tree) (burn-tree?)) :fire! %) forest-row) ) forest)) (defn burn-out-trees [forest] (map (fn [forest-row] (map #(case % :burnt:grass :fire!:burnt %) forest-row)) forest)) (defn burn-neighbores [forest] (let [forest-size (count forest) indicies (partition forest-size (for [row (range forest-size) col (range forest-size)] (cons row (list col))))] (map (fn [forest-row indicies-row] (map #(if (and (=:tree %) (neighbores-burning? forest (first %2) (second %2))) :fire! %) forest-row indicies-row)) forest indicies))) (defn grow-new-trees [forest] (map (fn [forest-row] (map #(if (= %:grass) (tree-maker) %) forest-row)) forest)) (defn forest-fire ([] (forest-fire 5)) ([forest-size] (loop [forest (make-forest forest-size)] (pprint forest) (Thread/sleep 300) (-> forest (burn-out-trees) (lightning-strike) (burn-neighbores) (grow-new-trees) (recur))))) (forest-fire)
821Forest fire
6clojure
bozkz
package main import ( "fmt" "math/rand" "time" ) func main() { rand.Seed(time.Now().UnixNano()) var n int = 3
820Flipping bits game
0go
bo3kh
(def x 2.0) (def xi 0.5) (def y 4.0) (def yi 0.25) (def z (+ x y)) (def zi (/ 1.0 (+ x y))) (def numbers [x y z]) (def invers [xi yi zi]) (defn multiplier [a b] (fn [m] (* a b m))) > (for [[n i] (zipmap numbers invers)] ((multiplier n i) 0.5)) (0.5 0.5 0.5)
823First-class functions/Use numbers analogously
6clojure
nl5ik
fn main() { magic(4); magic(2_340); magic(765_000); magic(27_000_001); magic(999_123_090); magic(239_579_832_723_441); magic(std::u64::MAX); } fn magic(num: u64) { if num == 4 { println!("four is magic!"); println!(); return; } let name = number_name(num); let len = name.len() as u64; print!("{} is {}, ", name, number_name(len)); magic(len); } const LOW: &'static [&'static str] = &[ "zero", "one", "two", "three", "four", "five", "six", "seven", "eight","nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen" ]; const MED: &'static [&'static str] = &[ "twenty", "thirty", "forty", "fifty", "sixy", "seventy", "eighty", "ninety" ]; const HIGH: &'static [&'static str] = &[ "thousand", "million", "billion", "trillion", "quadrillion", "quintillion" ]; fn number_name(num: u64) -> String { if num < 20 { return LOW[num as usize].to_string(); } if num < 100 { let index = ((num / 10) - 2) as usize; let tens = MED[index].to_string(); let remainder = num% 10; if remainder > 0 { return format!("{}-{}", tens, number_name(remainder)); } return tens; } if num < 1000 { let hundreds = LOW[(num / 100) as usize]; let remainder = num% 100; if remainder > 0 { return format!("{} hundred {}", hundreds, number_name(remainder)); } return format!("{} hundred", hundreds); } let mut remainder = num% 1000; let mut cur = if remainder > 0 { number_name(remainder) } else { "".to_string() }; let mut n = num / 1000; for noun in HIGH.iter() { if n > 0 { remainder = n% 1000; if remainder > 0 {
816Four is magic
15rust
4ef5u
import Control.Monad (join) import Data.List (union) import Data.Map hiding (foldr, union) import Data.Maybe (fromJust, isJust) import Data.Semigroup import Prelude hiding (lookup, filter)
817Floyd-Warshall algorithm
8haskell
2b8ll
echo str_pad(7.125, 9, '0', STR_PAD_LEFT);
813Formatted numeric output
12php
k8lhv
import Data.List (intersperse) import System.Random (randomRIO) import Data.Array (Array, (!), (//), array, bounds) import Control.Monad (zipWithM_, replicateM, foldM, when) type Board = Array (Char, Char) Int flp :: Int -> Int flp 0 = 1 flp 1 = 0 numRows, numCols :: Board -> String numRows t = let ((a, _), (b, _)) = bounds t in [a .. b] numCols t = let ((_, a), (_, b)) = bounds t in [a .. b] flipRow, flipCol :: Board -> Char -> Board flipRow t r = let e = [ (ix, flp (t ! ix)) | ix <- zip (repeat r) (numCols t) ] in t // e flipCol t c = let e = [ (ix, flp (t ! ix)) | ix <- zip (numRows t) (repeat c) ] in t // e printBoard :: Board -> IO () printBoard t = do let rows = numRows t cols = numCols t f 0 = '0' f 1 = '1' p r xs = putStrLn $ [r, ' '] ++ intersperse ' ' (map f xs) putStrLn $ " " ++ intersperse ' ' cols zipWithM_ p rows [ [ t ! (y, x) | x <- cols ] | y <- rows ] setupGame :: Char -> Char -> IO (Board, Board) setupGame sizey sizex = do let mk rc = (\v -> (rc, v)) <$> randomRIO (0, 1) rows = ['a' .. sizey] cols = ['1' .. sizex] goal <- array (('a', '1'), (sizey, sizex)) <$> mapM mk [ (r, c) | r <- rows , c <- cols ] start <- do let change :: Board -> Int -> IO Board change t 0 = flipRow t <$> randomRIO ('a', sizey) change t 1 = flipCol t <$> randomRIO ('1', sizex) numMoves <- randomRIO (3, 15) moves <- replicateM numMoves $ randomRIO (0, 1) foldM change goal moves if goal /= start then return (goal, start) else setupGame sizey sizex main :: IO () main = do putStrLn "Select a board size (1 - 9).\nPress any other key to exit." sizec <- getChar when (sizec `elem` ['1' .. '9']) $ do let size = read [sizec] - 1 (g, s) <- setupGame (['a' ..] !! size) (['1' ..] !! size) turns g s 0 where turns goal current moves = do putStrLn "\nGoal:" printBoard goal putStrLn "\nBoard:" printBoard current when (moves > 0) $ putStrLn $ "\nYou've made " ++ show moves ++ " moves so far." putStrLn $ "\nFlip a row (" ++ numRows current ++ ") or a column (" ++ numCols current ++ ")" v <- getChar if v `elem` numRows current then check $ flipRow current v else if v `elem` numCols current then check $ flipCol current v else tryAgain where check t = if t == goal then putStrLn $ "\nYou've won in " ++ show (moves + 1) ++ " moves!" else turns goal t (moves + 1) tryAgain = do putStrLn ": Invalid row or column." turns goal current moves
820Flipping bits game
8haskell
d27n4
import Foundation func fourIsMagic(_ number: NSNumber) -> String { let formatter = NumberFormatter() formatter.numberStyle = .spellOut formatter.locale = Locale(identifier: "en_EN") var result: [String] = [] var numberString = formatter.string(from: number)! result.append(numberString.capitalized) while numberString!= "four" { numberString = formatter.string(from: NSNumber(value: numberString.count))! result.append(contentsOf: [" is ", numberString, ", ", numberString]) } result.append(" is magic.") return result.joined() } for testInput in [23, 1000000000, 20140, 100, 130, 151, -7] { print(fourIsMagic(testInput as NSNumber)) }
816Four is magic
17swift
u1nvg
function dif(a, b, ...) if(b) then return b-a, dif(b, ...) end end function dift(t) return {dif(unpack(t))} end print(unpack(dift{1,3,6,10,15}))
815Forward difference
1lua
s6rq8
switch (xx) { case 1: case 2: ... break; case 4: ... break; case 5: ... break; default: break; } for (int i = 0; i < 10; ++i) { ... if (some_condition) { break; } ... } _Time_: do { for (int i = 0; i < 10; ++i) { ... if (some_condition) { break _Time_; } ... } ... } while (thisCondition);
819Flow-control structures
9java
jst7c
$ jq -n '1, (2 | label $foo | debug | 3 | break $foo | debug), 4' 1 ["DEBUG:",2] 4
819Flow-control structures
10javascript
1nmp7
void t(int n) { int i, j, c, len; i = n * (n - 1) / 2; for (len = c = 1; c < i; c *= 10, len++); c -= i; char tmp[32], s[4096], *p; sprintf(tmp, , len, 0); inline void inc_numstr(void) { int k = len; redo: if (!k--) return; if (tmp[k] == '9') { tmp[k] = '0'; goto redo; } if (++tmp[k] == '!') tmp[k] = '1'; } for (p = s, i = 1; i <= n; i++) { for (j = 1; j <= i; j++) { inc_numstr(); __builtin_memcpy(p, tmp + 1 - (j >= c), len - (j < c)); p += len - (j < c); *(p++) = (i - j)? ' ' : '\n'; if (p - s + len >= 4096) { fwrite(s, 1, p - s, stdout); p = s; } } } fwrite(s, 1, p - s, stdout); int num; for (num = i = 1; i <= n; i++) for (j = 1; j <= i; j++) printf(, len - (j < c), num++, i - j ? ' ':'\n'); } int main(void) { t(5), t(14); return 0; }
824Floyd's triangle
5c
o9280
double median(double *x, int start, int end_inclusive) { int size = end_inclusive - start + 1; if (size <= 0) { printf(); exit(1); } int m = start + size / 2; if (size % 2) return x[m]; return (x[m - 1] + x[m]) / 2.0; } int compare (const void *a, const void *b) { double aa = *(double*)a; double bb = *(double*)b; if (aa > bb) return 1; if (aa < bb) return -1; return 0; } int fivenum(double *x, double *result, int x_len) { int i, m, lower_end; for (i = 0; i < x_len; i++) { if (x[i] != x[i]) { printf(); return 1; } } qsort(x, x_len, sizeof(double), compare); result[0] = x[0]; result[2] = median(x, 0, x_len - 1); result[4] = x[x_len - 1]; m = x_len / 2; lower_end = (x_len % 2) ? m : m - 1; result[1] = median(x, 0, lower_end); result[3] = median(x, m, x_len - 1); return 0; } int show(double *result, int places) { int i; char f[7]; sprintf(f, , places); printf(); for (i = 0; i < 5; i++) { printf(f, result[i]); if (i < 4) printf(); } printf(); } int main() { double result[5]; double x1[11] = {15.0, 6.0, 42.0, 41.0, 7.0, 36.0, 49.0, 40.0, 39.0, 47.0, 43.0}; if (!fivenum(x1, result, 11)) show(result, 1); double x2[6] = {36.0, 40.0, 7.0, 39.0, 41.0, 15.0}; if (!fivenum(x2, result, 6)) show(result, 1); double x3[20] = { 0.14082834, 0.09748790, 1.73131507, 0.87636009, -1.95059594, 0.73438555, -0.03035726, 1.46675970, -0.74621349, -0.72588772, 0.63905160, 0.61501527, -0.98983780, -1.00447874, -0.62759469, 0.66206163, 1.04312009, -0.10305385, 0.75775634, 0.32566578 }; if (!fivenum(x3, result, 20)) show(result, 9); return 0; }
825Fivenum
5c
1nfpj
typedef struct { int seq, cnt; } env_t; env_t env[JOBS] = {{0, 0}}; int *seq, *cnt; void hail() { printf(, *seq); if (*seq == 1) return; ++*cnt; *seq = (*seq & 1) ? 3 * *seq + 1 : *seq / 2; } void switch_to(int id) { seq = &env[id].seq; cnt = &env[id].cnt; } int main() { int i; jobs(i) { env[i].seq = i + 1; } again: jobs(i) { hail(); } jobs(i) { if (1 != *seq) goto again; } printf(); jobs(i) { printf(, *cnt); } return 0; }
826First class environments
5c
tu5f4
import java.awt.*; import java.awt.event.*; import java.util.*; import javax.swing.*; public class FlippingBitsGame extends JPanel { final int maxLevel = 7; final int minLevel = 3; private Random rand = new Random(); private int[][] grid, target; private Rectangle box; private int n = maxLevel; private boolean solved = true; FlippingBitsGame() { setPreferredSize(new Dimension(640, 640)); setBackground(Color.white); setFont(new Font("SansSerif", Font.PLAIN, 18)); box = new Rectangle(120, 90, 400, 400); startNewGame(); addMouseListener(new MouseAdapter() { @Override public void mousePressed(MouseEvent e) { if (solved) { startNewGame(); } else { int x = e.getX(); int y = e.getY(); if (box.contains(x, y)) return; if (x > box.x && x < box.x + box.width) { flipCol((x - box.x) / (box.width / n)); } else if (y > box.y && y < box.y + box.height) flipRow((y - box.y) / (box.height / n)); if (solved(grid, target)) solved = true; printGrid(solved ? "Solved!" : "The board", grid); } repaint(); } }); } void startNewGame() { if (solved) { n = (n == maxLevel) ? minLevel : n + 1; grid = new int[n][n]; target = new int[n][n]; do { shuffle(); for (int i = 0; i < n; i++) target[i] = Arrays.copyOf(grid[i], n); shuffle(); } while (solved(grid, target)); solved = false; printGrid("The target", target); printGrid("The board", grid); } } void printGrid(String msg, int[][] g) { System.out.println(msg); for (int[] row : g) System.out.println(Arrays.toString(row)); System.out.println(); } boolean solved(int[][] a, int[][] b) { for (int i = 0; i < n; i++) if (!Arrays.equals(a[i], b[i])) return false; return true; } void shuffle() { for (int i = 0; i < n * n; i++) { if (rand.nextBoolean()) flipRow(rand.nextInt(n)); else flipCol(rand.nextInt(n)); } } void flipRow(int r) { for (int c = 0; c < n; c++) { grid[r][c] ^= 1; } } void flipCol(int c) { for (int[] row : grid) { row[c] ^= 1; } } void drawGrid(Graphics2D g) { g.setColor(getForeground()); if (solved) g.drawString("Solved! Click here to play again.", 180, 600); else g.drawString("Click next to a row or a column to flip.", 170, 600); int size = box.width / n; for (int r = 0; r < n; r++) for (int c = 0; c < n; c++) { g.setColor(grid[r][c] == 1 ? Color.blue : Color.orange); g.fillRect(box.x + c * size, box.y + r * size, size, size); g.setColor(getBackground()); g.drawRect(box.x + c * size, box.y + r * size, size, size); g.setColor(target[r][c] == 1 ? Color.blue : Color.orange); g.fillRect(7 + box.x + c * size, 7 + box.y + r * size, 10, 10); } } @Override public void paintComponent(Graphics gg) { super.paintComponent(gg); Graphics2D g = (Graphics2D) gg; g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); drawGrid(g); } public static void main(String[] args) { SwingUtilities.invokeLater(() -> { JFrame f = new JFrame(); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); f.setTitle("Flipping Bits Game"); f.setResizable(false); f.add(new FlippingBitsGame(), BorderLayout.CENTER); f.pack(); f.setLocationRelativeTo(null); f.setVisible(true); }); } }
820Flipping bits game
9java
s6vq0
import static java.lang.String.format; import java.util.Arrays; public class FloydWarshall { public static void main(String[] args) { int[][] weights = {{1, 3, -2}, {2, 1, 4}, {2, 3, 3}, {3, 4, 2}, {4, 2, -1}}; int numVertices = 4; floydWarshall(weights, numVertices); } static void floydWarshall(int[][] weights, int numVertices) { double[][] dist = new double[numVertices][numVertices]; for (double[] row : dist) Arrays.fill(row, Double.POSITIVE_INFINITY); for (int[] w : weights) dist[w[0] - 1][w[1] - 1] = w[2]; int[][] next = new int[numVertices][numVertices]; for (int i = 0; i < next.length; i++) { for (int j = 0; j < next.length; j++) if (i != j) next[i][j] = j + 1; } for (int k = 0; k < numVertices; k++) for (int i = 0; i < numVertices; i++) for (int j = 0; j < numVertices; j++) if (dist[i][k] + dist[k][j] < dist[i][j]) { dist[i][j] = dist[i][k] + dist[k][j]; next[i][j] = next[i][k]; } printResult(dist, next); } static void printResult(double[][] dist, int[][] next) { System.out.println("pair dist path"); for (int i = 0; i < next.length; i++) { for (int j = 0; j < next.length; j++) { if (i != j) { int u = i + 1; int v = j + 1; String path = format("%d ->%d %2d %s", u, v, (int) dist[i][j], u); do { u = next[u - 1][v - 1]; path += " -> " + u; } while (u != v); System.out.println(path); } } } } }
817Floyd-Warshall algorithm
9java
6ge3z
from math import pi, exp r = exp(pi)-pi print r print %(r,r,r,r,r,r) print %(-r,-r,-r) print %(r,r,r) print %(r,r,r) print %(-r,-r,-r) print %(r,r,r) print %(r,r,r)
813Formatted numeric output
3python
z5xtt
(def hailstone-src "(defn hailstone-step [env] (let [{:keys[n cnt]} env] (cond (= n 1) {:n 1:cnt cnt} (even? n) {:n (/ n 2):cnt (inc cnt)} :else {:n (inc (* n 3)):cnt (inc cnt)})))") (defn create-hailstone-table [f-src] (let [done? (fn [e] (= (:n e) 1)) print-step (fn [envs] (println (map #(format "%4d" (:n %)) envs))) print-counts (fn [envs] (println "Counts:\n" (map #(format "%4d" (:cnt %)) envs)))] (loop [f (eval (read-string f-src)) envs (for [n (range 12)] {:n (inc n):cnt 0})] (if (every? done? envs) (print-counts envs) (do (print-step envs) (recur f (map f envs)))))))
826First class environments
6clojure
m7jyq
typedef struct list_t list_t, *list; struct list_t{ int is_list, ival; list *lst; }; list new_list() { list x = malloc(sizeof(list_t)); x->ival = 0; x->is_list = 1; x->lst = 0; return x; } void append(list parent, list child) { parent->lst = realloc(parent->lst, sizeof(list) * (parent->ival + 1)); parent->lst[parent->ival++] = child; } list from_string(char *s, char **e, list parent) { list ret = 0; if (!parent) parent = new_list(); while (*s != '\0') { if (*s == ']') { if (e) *e = s + 1; return parent; } if (*s == '[') { ret = new_list(); ret->is_list = 1; ret->ival = 0; append(parent, ret); from_string(s + 1, &s, ret); continue; } if (*s >= '0' && *s <= '9') { ret = new_list(); ret->is_list = 0; ret->ival = strtol(s, &s, 10); append(parent, ret); continue; } s++; } if (e) *e = s; return parent; } void show_list(list l) { int i; if (!l) return; if (!l->is_list) { printf(, l->ival); return; } printf(); for (i = 0; i < l->ival; i++) { show_list(l->lst[i]); if (i < l->ival - 1) printf(); } printf(); } list flatten(list from, list to) { int i; list t; if (!to) to = new_list(); if (!from->is_list) { t = new_list(); *t = *from; append(to, t); } else for (i = 0; i < from->ival; i++) flatten(from->lst[i], to); return to; } void delete_list(list l) { int i; if (!l) return; if (l->is_list && l->ival) { for (i = 0; i < l->ival; i++) delete_list(l->lst[i]); free(l->lst); } free(l); } int main() { list l = from_string(, 0, 0); printf(); show_list(l); printf(); list flat = flatten(l, 0); printf(); show_list(flat); return 0; }
827Flatten a list
5c
2bblo
function numOfRows(board) { return board.length; } function numOfCols(board) { return board[0].length; } function boardToString(board) {
820Flipping bits game
10javascript
nlriy
package main import "fmt" func main() { x := 2. xi := .5 y := 4. yi := .25 z := x + y zi := 1 / (x + y)
823First-class functions/Use numbers analogously
0go
vpw2m
null
819Flow-control structures
11kotlin
5aoua
i = 0 while true do i = i + 1 if i > 10 then break end end
819Flow-control structures
1lua
4ei5c
var graph = []; for (i = 0; i < 10; ++i) { graph.push([]); for (j = 0; j < 10; ++j) graph[i].push(i == j ? 0 : 9999999); } for (i = 1; i < 10; ++i) { graph[0][i] = graph[i][0] = parseInt(Math.random() * 9 + 1); } for (k = 0; k < 10; ++k) { for (i = 0; i < 10; ++i) { for (j = 0; j < 10; ++j) { if (graph[i][j] > graph[i][k] + graph[k][j]) graph[i][j] = graph[i][k] + graph[k][j] } } } console.log(graph);
817Floyd-Warshall algorithm
10javascript
lk0cf
> sprintf("%f", pi) [1] "3.141593" > sprintf("%.3f", pi) [1] "3.142" > sprintf("%1.0f", pi) [1] "3" > sprintf("%5.1f", pi) [1] " 3.1" > sprintf("%05.1f", pi) [1] "003.1" > sprintf("%+f", pi) [1] "+3.141593" > sprintf("% f", pi) [1] " 3.141593" > sprintf("%-10f", pi) [1] "3.141593 " > sprintf("%e", pi) [1] "3.141593e+00" > sprintf("%E", pi) [1] "3.141593E+00" > sprintf("%g", pi) [1] "3.14159" > sprintf("%g", 1e6 * pi) [1] "3.14159e+06" > sprintf("%.9g", 1e6 * pi) [1] "3141592.65" > sprintf("%G", 1e-6 * pi) [1] "3.14159E-06"
813Formatted numeric output
13r
nl1i2
package main import ( "fmt" "math" "time" ) const ld10 = math.Ln2 / math.Ln10 func commatize(n uint64) string { s := fmt.Sprintf("%d", n) le := len(s) for i := le - 3; i >= 1; i -= 3 { s = s[0:i] + "," + s[i:] } return s } func p(L, n uint64) uint64 { i := L digits := uint64(1) for i >= 10 { digits *= 10 i /= 10 } count := uint64(0) for i = 0; count < n; i++ { e := math.Exp(math.Ln10 * math.Mod(float64(i)*ld10, 1)) if uint64(math.Trunc(e*float64(digits))) == L { count++ } } return i - 1 } func main() { start := time.Now() params := [][2]uint64{{12, 1}, {12, 2}, {123, 45}, {123, 12345}, {123, 678910}} for _, param := range params { fmt.Printf("p(%d,%d) =%s\n", param[0], param[1], commatize(p(param[0], param[1]))) } fmt.Printf("\nTook%s\n", time.Since(start)) }
822First power of 2 that has leading decimal digits of 12
0go
5asul
def multiplier = { n1, n2 -> { m -> n1 * n2 * m } } def = 0.00000001
823First-class functions/Use numbers analogously
7groovy
m7by5
module Main where import Text.Printf x = 2.0 xi = 0.5 y = 4.0 yi = 0.25 z = x + y zi = 1.0 / ( x + y ) multiplier :: Double -> Double -> Double -> Double multiplier a b = \m -> a * b * m main :: IO () main = do let numbers = [x, y, z] inverses = [xi, yi, zi] pairs = zip numbers inverses print_pair (number, inverse) = let new_function = multiplier number inverse in printf "%f *%f * 0.5 =%f\n" number inverse (new_function 0.5) mapM_ print_pair pairs
823First-class functions/Use numbers analogously
8haskell
ef6ai
(defn TriangleList [n] (let [l (map inc (range))] (loop [l l x 1 nl []] (if (= n (count nl)) nl (recur (drop x l) (inc x) (conj nl (take x l))))))) (defn TrianglePrint [n] (let [t (TriangleList n) m (count (str (last (last t)))) f (map #(map str %) t) l (map #(map (fn [x] (if (> m (count x)) (str (apply str (take (- m (count x)) (repeat " "))) x) x)) %) f) e (map #(map (fn [x] (str " " x)) %) l)] (map #(println (apply str %)) e)))
824Floyd's triangle
6clojure
tugfv
def multiply(a, b) a * b end
808Function definition
14ruby
pirbh
fn multiply(a: i32, b: i32) -> i32 { a * b }
808Function definition
15rust
1n7pu
void toBaseN(char buffer[], long long num, int base) { char *ptr = buffer; char *tmp; while (num >= 1) { int rem = num % base; num /= base; *ptr++ = [rem]; } *ptr-- = 0; for (tmp = buffer; tmp < ptr; tmp++, ptr--) { char c = *tmp; *tmp = *ptr; *ptr = c; } } int countUnique(char inBuf[]) { char buffer[BUFF_SIZE]; int count = 0; int pos, nxt; strcpy_s(buffer, BUFF_SIZE, inBuf); for (pos = 0; buffer[pos] != 0; pos++) { if (buffer[pos] != 1) { count++; for (nxt = pos + 1; buffer[nxt] != 0; nxt++) { if (buffer[nxt] == buffer[pos]) { buffer[nxt] = 1; } } } } return count; } void find(int base) { char nBuf[BUFF_SIZE]; char sqBuf[BUFF_SIZE]; long long n, s; for (n = 2; ; n++) { s = n * n; toBaseN(sqBuf, s, base); if (strlen(sqBuf) >= base && countUnique(sqBuf) == base) { toBaseN(nBuf, n, base); toBaseN(sqBuf, s, base); printf(, base, nBuf, sqBuf); break; } } } int main() { int i; for (i = 2; i <= 15; i++) { find(i); } return 0; }
828First perfect square in base n with n unique digits
5c
pioby
package main import "fmt" const jobs = 12 type environment struct{ seq, cnt int } var ( env [jobs]environment seq, cnt *int ) func hail() { fmt.Printf("% 4d", *seq) if *seq == 1 { return } (*cnt)++ if *seq&1 != 0 { *seq = 3*(*seq) + 1 } else { *seq /= 2 } } func switchTo(id int) { seq = &env[id].seq cnt = &env[id].cnt } func main() { for i := 0; i < jobs; i++ { switchTo(i) env[i].seq = i + 1 } again: for i := 0; i < jobs; i++ { switchTo(i) hail() } fmt.Println() for j := 0; j < jobs; j++ { switchTo(j) if *seq != 1 { goto again } } fmt.Println() fmt.Println("COUNTS:") for i := 0; i < jobs; i++ { switchTo(i) fmt.Printf("% 4d", *cnt) } fmt.Println() }
826First class environments
0go
h08jq
null
820Flipping bits game
11kotlin
adm13
import Control.Monad (guard) import Text.Printf (printf) p :: Int -> Int -> Int p l n = calc !! pred n where digitCount = floor $ logBase 10 (fromIntegral l :: Float) log10pwr = logBase 10 2 calc = do raised <- [-1 ..] let firstDigits = floor $ 10 ** (snd (properFraction $ log10pwr * realToFrac raised) + realToFrac digitCount) guard (firstDigits == l) [raised] main :: IO () main = mapM_ (\(l, n) -> printf "p(%d,%d) =%d\n" l n (p l n)) [(12, 1), (12, 2), (123, 45), (123, 12345), (123, 678910)]
822First power of 2 that has leading decimal digits of 12
8haskell
xz9w4
hailstone n | n == 1 = 1 | even n = n `div` 2 | odd n = 3*n + 1
826First class environments
8haskell
iclor
target, board, moves, W, H = {}, {}, 0, 3, 3 function getIndex( i, j ) return i + j * W - W end function flip( d, r ) function invert( a ) if a == 1 then return 0 end return 1 end local idx if d == 1 then for i = 1, W do idx = getIndex( i, r ) board[idx] = invert( board[idx] ) end else for i = 1, H do idx = getIndex( r, i ) board[idx] = invert( board[idx] ) end end moves = moves + 1 end function createTarget() target, board = {}, {} local idx for j = 1, H do for i = 1, W do idx = getIndex( i, j ) if math.random() < .5 then target[idx] = 0 else target[idx] = 1 end board[idx] = target[idx] end end for i = 1, 103 do if math.random() < .5 then flip( 1, math.random( H ) ) else flip( 2, math.random( W ) ) end end moves = 0 end function getUserInput() io.write( "Input row and/or column: " ); local r = io.read() local a for i = 1, #r do a = string.byte( r:sub( i, i ):lower() ) if a >= 48 and a <= 57 then flip( 2, a - 48 ) end if a >= 97 and a <= string.byte( 'z' ) then flip( 1, a - 96 ) end end end function solved() local idx for j = 1, H do for i = 1, W do idx = getIndex( i, j ) if target[idx] ~= board[idx] then return false end end end return true end function display() local idx io.write( "\nTARGET\n " ) for i = 1, W do io.write( string.format( "%d ", i ) ) end; print() for j = 1, H do io.write( string.format( "%s ", string.char( 96 + j ) ) ) for i = 1, W do idx = getIndex( i, j ) io.write( string.format( "%d ", target[idx] ) ) end; io.write( "\n" ) end io.write( "\nBOARD\n " ) for i = 1, W do io.write( string.format( "%d ", i ) ) end; print() for j = 1, H do io.write( string.format( "%s ", string.char( 96 + j ) ) ) for i = 1, W do idx = getIndex( i, j ) io.write( string.format( "%d ", board[idx] ) ) end; io.write( "\n" ) end io.write( string.format( "Moves:%d\n", moves ) ) end function play() while true do createTarget() repeat display() getUserInput() until solved() display() io.write( "Very well!\nPlay again(Y/N)? " ); if io.read():lower() ~= "y" then return end end end
820Flipping bits game
1lua
ef9ac
public class FirstPowerOfTwo { public static void main(String[] args) { runTest(12, 1); runTest(12, 2); runTest(123, 45); runTest(123, 12345); runTest(123, 678910); } private static void runTest(int l, int n) { System.out.printf("p(%d,%d) =%,d%n", l, n, p(l, n)); } public static int p(int l, int n) { int test = 0; double log = Math.log(2) / Math.log(10); int factor = 1; int loop = l; while ( loop > 10 ) { factor *= 10; loop /= 10; } while ( n > 0) { test++; int val = (int) (factor * Math.pow(10, test * log % 1)); if ( val == l ) { n--; } } return test; } }
822First power of 2 that has leading decimal digits of 12
9java
botk3
const x = 2.0; const xi = 0.5; const y = 4.0; const yi = 0.25; const z = x + y; const zi = 1.0 / (x + y); const pairs = [[x, xi], [y, yi], [z, zi]]; const testVal = 0.5; const multiplier = (a, b) => m => a * b * m; const test = () => { return pairs.map(([a, b]) => { const f = multiplier(a, b); const result = f(testVal); return `${a} * ${b} * ${testVal} = ${result}`; }); } test().join('\n');
823First-class functions/Use numbers analogously
10javascript
ad310
null
817Floyd-Warshall algorithm
11kotlin
d2knz
def multiply(a: Int, b: Int) = a * b
808Function definition
16scala
wtkes
r = 7.125 printf , r printf , r printf , -r printf , r puts % r puts % r puts % -r puts % r
813Formatted numeric output
14ruby
6gs3t
sub dec2bin { sprintf "%04b", shift } sub bin2dec { oct "0b".shift } sub bin2bits { reverse split(//, substr(shift,0,shift)); } sub bits2bin { join "", map { 0+$_ } reverse @_ } sub bxor { my($a, $b) = @_; (!$a & $b) | ($a & !$b); } sub half_adder { my($a, $b) = @_; ( bxor($a,$b), $a & $b ); } sub full_adder { my($a, $b, $c) = @_; my($s1, $c1) = half_adder($a, $c); my($s2, $c2) = half_adder($s1, $b); ($s2, $c1 | $c2); } sub four_bit_adder { my($a, $b) = @_; my @abits = bin2bits($a,4); my @bbits = bin2bits($b,4); my($s0,$c0) = full_adder($abits[0], $bbits[0], 0); my($s1,$c1) = full_adder($abits[1], $bbits[1], $c0); my($s2,$c2) = full_adder($abits[2], $bbits[2], $c1); my($s3,$c3) = full_adder($abits[3], $bbits[3], $c2); (bits2bin($s0, $s1, $s2, $s3), $c3); } print " A B A B C S sum\n"; for my $a (0 .. 15) { for my $b (0 .. 15) { my($abin, $bbin) = map { dec2bin($_) } $a,$b; my($s,$c) = four_bit_adder( $abin, $bbin ); printf "%2d +%2d =%s +%s =%s%s =%2d\n", $a, $b, $abin, $bbin, $c, $s, bin2dec($c.$s); } }
814Four bit adder
2perl
gw34e
(defn flatten [coll] (lazy-seq (when-let [s (seq coll)] (if (coll? (first s)) (concat (flatten (first s)) (flatten (rest s))) (cons (first s) (flatten (rest s)))))))
827Flatten a list
6clojure
gww4f
null
823First-class functions/Use numbers analogously
11kotlin
4es57
function printResult(dist, nxt) print("pair dist path") for i=0, #nxt do for j=0, #nxt do if i ~= j then u = i + 1 v = j + 1 path = string.format("%d ->%d %2d %s", u, v, dist[i][j], u) repeat u = nxt[u-1][v-1] path = path .. " -> " .. u until (u == v) print(path) end end end end function floydWarshall(weights, numVertices) dist = {} for i=0, numVertices-1 do dist[i] = {} for j=0, numVertices-1 do dist[i][j] = math.huge end end for _,w in pairs(weights) do
817Floyd-Warshall algorithm
1lua
fvbdp
fn main() { let x = 7.125; println!("{:9}", x); println!("{:09}", x); println!("{:9}", -x); println!("{:09}", -x); }
813Formatted numeric output
15rust
yr068
package main import ( "fmt" "math" "sort" ) func fivenum(a []float64) (n5 [5]float64) { sort.Float64s(a) n := float64(len(a)) n4 := float64((len(a)+3)/2) / 2 d := []float64{1, n4, (n + 1) / 2, n + 1 - n4, n} for e, de := range d { floor := int(de - 1) ceil := int(math.Ceil(de - 1)) n5[e] = .5 * (a[floor] + a[ceil]) } return } var ( x1 = []float64{36, 40, 7, 39, 41, 15} x2 = []float64{15, 6, 42, 41, 7, 36, 49, 40, 39, 47, 43} x3 = []float64{ 0.14082834, 0.09748790, 1.73131507, 0.87636009, -1.95059594, 0.73438555, -0.03035726, 1.46675970, -0.74621349, -0.72588772, 0.63905160, 0.61501527, -0.98983780, -1.00447874, -0.62759469, 0.66206163, 1.04312009, -0.10305385, 0.75775634, 0.32566578, } ) func main() { fmt.Println(fivenum(x1)) fmt.Println(fivenum(x2)) fmt.Println(fivenum(x3)) }
825Fivenum
0go
yrj64
null
826First class environments
11kotlin
pinb6
import kotlin.math.ln import kotlin.math.pow fun main() { runTest(12, 1) runTest(12, 2) runTest(123, 45) runTest(123, 12345) runTest(123, 678910) } private fun runTest(l: Int, n: Int) {
822First power of 2 that has leading decimal digits of 12
11kotlin
rxogo
null
823First-class functions/Use numbers analogously
1lua
gw04j
object FormattedNumeric { val r = 7.125
813Formatted numeric output
16scala
chi93
class Fivenum { static double median(double[] x, int start, int endInclusive) { int size = endInclusive - start + 1 if (size <= 0) { throw new IllegalArgumentException("Array slice cannot be empty") } int m = start + (int) (size / 2) return (size % 2 == 1) ? x[m]: (x[m - 1] + x[m]) / 2.0 } static double[] fivenum(double[] x) { for (Double d: x) { if (d.isNaN()) { throw new IllegalArgumentException("Unable to deal with arrays containing NaN") } } double[] result = new double[5] Arrays.sort(x) result[0] = x[0] result[2] = median(x, 0, x.length - 1) result[4] = x[x.length - 1] int m = (int) (x.length / 2) int lowerEnd = (x.length % 2 == 1) ? m: m - 1 result[1] = median(x, 0, lowerEnd) result[3] = median(x, m, x.length - 1) return result } static void main(String[] args) { double[][] xl = [ [15.0, 6.0, 42.0, 41.0, 7.0, 36.0, 49.0, 40.0, 39.0, 47.0, 43.0], [36.0, 40.0, 7.0, 39.0, 41.0, 15.0], [ 0.14082834, 0.09748790, 1.73131507, 0.87636009, -1.95059594, 0.73438555, -0.03035726, 1.46675970, -0.74621349, -0.72588772, 0.63905160, 0.61501527, -0.98983780, -1.00447874, -0.62759469, 0.66206163, 1.04312009, -0.10305385, 0.75775634, 0.32566578 ] ] for (double[] x: xl) { println("${fivenum(x)}") } } }
825Fivenum
7groovy
fv5dn
typedef double (*Class2Func)(double); double functionA( double v) { return v*v*v; } double functionB(double v) { return exp(log(v)/3); } double Function1( Class2Func f2, double val ) { return f2(val); } Class2Func WhichFunc( int idx) { return (idx < 4) ? &functionA : &functionB; } Class2Func funcListA[] = {&functionA, &sin, &cos, &tan }; Class2Func funcListB[] = {&functionB, &asin, &acos, &atan }; double InvokeComposed( Class2Func f1, Class2Func f2, double val ) { return f1(f2(val)); } typedef struct sComposition { Class2Func f1; Class2Func f2; } *Composition; Composition Compose( Class2Func f1, Class2Func f2) { Composition comp = malloc(sizeof(struct sComposition)); comp->f1 = f1; comp->f2 = f2; return comp; } double CallComposed( Composition comp, double val ) { return comp->f1( comp->f2(val) ); } int main(int argc, char *argv[]) { int ix; Composition c; printf(, Function1(WhichFunc(0), 3.0)); for (ix=0; ix<4; ix++) { c = Compose(funcListA[ix], funcListB[ix]); printf(, ix, CallComposed(c, 0.9)); } return 0; }
829First-class functions
5c
wtdec
local envs = { } for i = 1, 12 do
826First class environments
1lua
1ndpo
sub dif { my @s = @_; map { $s[$_+1] - $s[$_] } 0 .. $ } @a = qw<90 47 58 29 22 32 55 5 55 73>; while (@a) { printf('%6d', $_) for @a = dif @a; print "\n" }
815Forward difference
2perl
vpn20
import Data.List (sort) fivenum :: [Double] -> [Double] fivenum [] = [] fivenum xs | l >= 5 = fmap ( (/ 2) . ( (+) . (!!) s . floor <*> (!!) s . ceiling ) . pred ) [1, q, succ l / 2, succ l - q, l] | otherwise = s where l = realToFrac $ length xs q = realToFrac (floor $ (l + 3) / 2) / 2 s = sort xs main :: IO () main = print $ fivenum [ 0.14082834, 0.09748790, 1.73131507, 0.87636009, -1.95059594, 0.73438555, -0.03035726, 1.46675970, -0.74621349, -0.72588772, 0.63905160, 0.61501527, -0.98983780, -1.00447874, -0.62759469, 0.66206163, 1.04312009, -0.10305385, 0.75775634, 0.32566578 ]
825Fivenum
8haskell
h0oju
use strict; use warnings; use Safe; sub hail_next { my $n = shift; return 1 if $n == 1; return $n * 3 + 1 if $n % 2; $n / 2; }; my @enviornments; for my $initial ( 1..12 ) { my $env = Safe->new; ${ $env->varglob('value') } = $initial; ${ $env->varglob('count') } = 0; $env->share('&hail_next'); $env->reval(q{ sub task { return if $value == 1; $value = hail_next( $value ); ++$count; } }); push @enviornments, $env; } my @value_refs = map $_->varglob('value'), @enviornments; my @tasks = map $_->varglob('task'), @enviornments; while( grep { $$_ != 1 } @value_refs ) { printf "%4s", $$_ for @value_refs; print "\n"; $_->() for @tasks; } print "Counts\n"; printf "%4s", ${$_->varglob('count')} for @enviornments; print "\n";
826First class environments
2perl
yr76u
FORK: goto FORK;
819Flow-control structures
2perl
o9g8x
import java.util.Arrays; public class Fivenum { static double median(double[] x, int start, int endInclusive) { int size = endInclusive - start + 1; if (size <= 0) throw new IllegalArgumentException("Array slice cannot be empty"); int m = start + size / 2; return (size % 2 == 1) ? x[m] : (x[m - 1] + x[m]) / 2.0; } static double[] fivenum(double[] x) { for (Double d : x) { if (d.isNaN()) throw new IllegalArgumentException("Unable to deal with arrays containing NaN"); } double[] result = new double[5]; Arrays.sort(x); result[0] = x[0]; result[2] = median(x, 0, x.length - 1); result[4] = x[x.length - 1]; int m = x.length / 2; int lowerEnd = (x.length % 2 == 1) ? m : m - 1; result[1] = median(x, 0, lowerEnd); result[3] = median(x, m, x.length - 1); return result; } public static void main(String[] args) { double xl[][] = { {15.0, 6.0, 42.0, 41.0, 7.0, 36.0, 49.0, 40.0, 39.0, 47.0, 43.0}, {36.0, 40.0, 7.0, 39.0, 41.0, 15.0}, { 0.14082834, 0.09748790, 1.73131507, 0.87636009, -1.95059594, 0.73438555, -0.03035726, 1.46675970, -0.74621349, -0.72588772, 0.63905160, 0.61501527, -0.98983780, -1.00447874, -0.62759469, 0.66206163, 1.04312009, -0.10305385, 0.75775634, 0.32566578 } }; for (double[] x : xl) System.out.printf("%s\n\n", Arrays.toString(fivenum(x))); } }
825Fivenum
9java
5awuf
package main import ( "fmt" "math/big" "strconv" "time" ) const maxBase = 27 const minSq36 = "1023456789abcdefghijklmnopqrstuvwxyz" const minSq36x = "10123456789abcdefghijklmnopqrstuvwxyz" var bigZero = new(big.Int) var bigOne = new(big.Int).SetUint64(1) func containsAll(sq string, base int) bool { var found [maxBase]byte le := len(sq) reps := 0 for _, r := range sq { d := r - 48 if d > 38 { d -= 39 } found[d]++ if found[d] > 1 { reps++ if le-reps < base { return false } } } return true } func sumDigits(n, base *big.Int) *big.Int { q := new(big.Int).Set(n) r := new(big.Int) sum := new(big.Int).Set(bigZero) for q.Cmp(bigZero) == 1 { q.QuoRem(q, base, r) sum.Add(sum, r) } return sum } func digitalRoot(n *big.Int, base int) int { root := new(big.Int) b := big.NewInt(int64(base)) for i := new(big.Int).Set(n); i.Cmp(b) >= 0; i.Set(root) { root.Set(sumDigits(i, b)) } return int(root.Int64()) } func minStart(base int) (string, uint64, int) { nn := new(big.Int) ms := minSq36[:base] nn.SetString(ms, base) bdr := digitalRoot(nn, base) var drs []int var ixs []uint64 for n := uint64(1); n < uint64(2*base); n++ { nn.SetUint64(n * n) dr := digitalRoot(nn, base) if dr == 0 { dr = int(n * n) } if dr == bdr { ixs = append(ixs, n) } if n < uint64(base) && dr >= bdr { drs = append(drs, dr) } } inc := uint64(1) if len(ixs) >= 2 && base != 3 { inc = ixs[1] - ixs[0] } if len(drs) == 0 { return ms, inc, bdr } min := drs[0] for _, dr := range drs[1:] { if dr < min { min = dr } } rd := min - bdr if rd == 0 { return ms, inc, bdr } if rd == 1 { return minSq36x[:base+1], 1, bdr } ins := string(minSq36[rd]) return (minSq36[:rd] + ins + minSq36[rd:])[:base+1], inc, bdr } func main() { start := time.Now() var nb, nn big.Int for n, k, base := uint64(2), uint64(1), 2; ; n += k { if base > 2 && n%uint64(base) == 0 { continue } nb.SetUint64(n) sq := nb.Mul(&nb, &nb).Text(base) if !containsAll(sq, base) { continue } ns := strconv.FormatUint(n, base) tt := time.Since(start).Seconds() fmt.Printf("Base%2d:%15s =%-27s in%8.3fs\n", base, ns, sq, tt) if base == maxBase { break } base++ ms, inc, bdr := minStart(base) k = inc nn.SetString(ms, base) nb.Sqrt(&nn) if nb.Uint64() < n+1 { nb.SetUint64(n + 1) } if k != 1 { for { nn.Mul(&nb, &nb) dr := digitalRoot(&nn, base) if dr == bdr { n = nb.Uint64() - k break } nb.Add(&nb, bigOne) } } else { n = nb.Uint64() - k } } }
828First perfect square in base n with n unique digits
0go
6g43p
package main import ( "fmt" "math/rand" "strings" ) const ( rows = 20 cols = 30 p = .01 f = .001 ) const rx = rows + 2 const cx = cols + 2 func main() { odd := make([]byte, rx*cx) even := make([]byte, rx*cx) for r := 1; r <= rows; r++ { for c := 1; c <= cols; c++ { if rand.Intn(2) == 1 { odd[r*cx+c] = 'T' } } } for { print(odd) step(even, odd) fmt.Scanln() print(even) step(odd, even) fmt.Scanln() } } func print(model []byte) { fmt.Println(strings.Repeat("__", cols)) fmt.Println() for r := 1; r <= rows; r++ { for c := 1; c <= cols; c++ { if model[r*cx+c] == 0 { fmt.Print(" ") } else { fmt.Printf("%c", model[r*cx+c]) } } fmt.Println() } } func step(dst, src []byte) { for r := 1; r <= rows; r++ { for c := 1; c <= cols; c++ { x := r*cx + c dst[x] = src[x] switch dst[x] { case '#':
821Forest fire
0go
nlgi1
use strict; use warnings qw(FATAL all); my $n = shift(@ARGV) || 4; if( $n < 2 or $n > 26 ) { die "You can't play a size $n game\n"; } my $n2 = $n*$n; my (@rows, @cols); for my $i ( 0 .. $n-1 ) { my $row = my $col = "\x00" x $n2; vec($row, $i * $n + $_, 8) ^= 1 for 0 .. $n-1; vec($col, $i + $_ * $n, 8) ^= 1 for 0 .. $n-1; push @rows, $row; push @cols, $col; } my $goal = "0" x $n2; int(rand(2)) or (vec($goal, $_, 8) ^= 1) for 0 .. $n2-1; my $start = $goal; { for(@rows, @cols) { $start ^= $_ if int rand 2; } redo if $start eq $goal; } my @letters = ('a'..'z')[0..$n-1]; sub to_strings { my $board = shift; my @result = join(" ", " ", @letters); for( 0 .. $n-1 ) { my $res = sprintf("%2d ",$_+1); $res .= join " ", split //, substr $board, $_*$n, $n; push @result, $res; } \@result; } my $fmt; my ($stext, $etext) = ("Starting board", "Ending board"); my $re = join "|", reverse 1 .. $n, @letters; my $moves_so_far = 0; while( 1 ) { my ($from, $to) = (to_strings($start), to_strings($goal)); unless( $fmt ) { my $len = length $from->[0]; $len = length($stext) if $len < length $stext; $fmt = join($len, "%", "s%", "s\n"); } printf $fmt, $stext, $etext; printf $fmt, $from->[$_], $to->[$_] for 0 .. $n; last if $start eq $goal; INPUT_LOOP: { printf "Move $moves_so_far+1; my $input = <>; die unless defined $input; my $did_one; for( $input =~ /($re)/gi ) { $did_one = 1; if( /\d/ ) { $start ^= $rows[$_-1]; } else { $_ = ord(lc) - ord('a'); $start ^= $cols[$_]; } ++$moves_so_far; } redo INPUT_LOOP unless $did_one; } } print "You won after $moves_so_far moves.\n";
820Flipping bits game
2perl
9jemn
use strict; use warnings; use feature 'say'; use feature 'state'; use POSIX qw(fmod); use Perl6::GatherTake; use constant ln2ln10 => log(2) / log(10); sub comma { reverse ((reverse shift) =~ s/(.{3})/$1,/gr) =~ s/^,//r } sub ordinal_digit { my($d) = $_[0] =~ /(.)$/; $d eq '1' ? 'st' : $d eq '2' ? 'nd' : $d eq '3' ? 'rd' : 'th' } sub startswith12 { my($nth) = @_; state $i = 0; state $n = 0; while (1) { next unless '1.2' eq substr(( 10 ** fmod(++$i * ln2ln10, 1) ), 0, 3); return $i if ++$n eq $nth; } } sub startswith123 { my $pre = '1.23'; my ($this, $count) = (0, 0); gather { while (1) { if ($this == 196) { $this = 289; $this = 485 unless $pre eq substr(( 10 ** fmod(($count+$this) * ln2ln10, 1) ), 0, 4); } elsif ($this == 485) { $this = 196; $this = 485 unless $pre eq substr(( 10 ** fmod(($count+$this) * ln2ln10, 1) ), 0, 4); } elsif ($this == 289) { $this = 196 } elsif ($this == 90) { $this = 289 } elsif ($this == 0) { $this = 90; } take $count += $this; } } } my $start_123 = startswith123(); sub p { my($prefix,$nth) = @_; $prefix eq '12' ? startswith12($nth) : $start_123->[$nth-1]; } for ([12, 1], [12, 2], [123, 45], [123, 12345], [123, 678910]) { my($prefix,$nth) = @$_; printf "%-15s%9s power of two (2^n) that starts with%5s is at n =%s\n", "p($prefix, $nth):", comma($nth) . ordinal_digit($nth), "'$prefix'", comma p($prefix, $nth); }
822First power of 2 that has leading decimal digits of 12
2perl
d2gnw
<?php goto a; echo 'Foo'; a: echo 'Bar'; ?>
819Flow-control structures
12php
gwn42
<?php function forwardDiff($anArray, $times = 1) { if ($times <= 0) { return $anArray; } for ($accumilation = array(), $i = 1, $j = count($anArray); $i < $j; ++$i) { $accumilation[] = $anArray[$i] - $anArray[$i - 1]; } if ($times === 1) { return $accumilation; } return forwardDiff($accumilation, $times - 1); } class ForwardDiffExample extends PweExample { function _should_run_empty_array_for_single_elem() { $expected = array($this->rand()->int()); $this->spec(forwardDiff($expected))->shouldEqual(array()); } function _should_give_diff_of_two_elem_as_single_elem() { $twoNums = array($this->rand()->int(), $this->rand()->int()); $expected = array($twoNums[1] - $twoNums[0]); $this->spec(forwardDiff($twoNums))->shouldEqual($expected); } function _should_compute_correct_forward_diff_for_longer_arrays() { $diffInput = array(10, 2, 9, 6, 5); $expected = array(-8, 7, -3, -1); $this->spec(forwardDiff($diffInput))->shouldEqual($expected); } function _should_apply_more_than_once_if_specified() { $diffInput = array(4, 6, 9, 3, 4); $expectedAfter1 = array(2, 3, -6, 1); $expectedAfter2 = array(1, -9, 7); $this->spec(forwardDiff($diffInput, 1))->shouldEqual($expectedAfter1); $this->spec(forwardDiff($diffInput, 2))->shouldEqual($expectedAfter2); } function _should_return_array_unaltered_if_no_times() { $this->spec(forwardDiff($expected = array(1,2,3), 0))->shouldEqual($expected); } }
815Forward difference
12php
0y7sp
DECLARE @n INT SELECT @n=123 SELECT SUBSTRING(CONVERT(CHAR(5), 10000+@n),2,4) AS FourDigits SET @n=5 print + SUBSTRING(CONVERT(CHAR(3), 100+@n),2,2) --Output: 05
813Formatted numeric output
19sql
vpf2y
function median(arr) { let mid = Math.floor(arr.length / 2); return (arr.length % 2 == 0) ? (arr[mid-1] + arr[mid]) / 2 : arr[mid]; } Array.prototype.fiveNums = function() { this.sort(function(a, b) { return a - b} ); let mid = Math.floor(this.length / 2), loQ = (this.length % 2 == 0) ? this.slice(0, mid) : this.slice(0, mid+1), hiQ = this.slice(mid); return [ this[0], median(loQ), median(this), median(hiQ), this[this.length-1] ]; }
825Fivenum
10javascript
js87n
static const char *months[] = {, , , , , , , , , , , }; static int long_months[] = {0, 2, 4, 6, 7, 9, 11}; int main() { int n = 0, y, i, m; struct tm t = {0}; printf(); for (y = 1900; y <= 2100; y++) { for (i = 0; i < 7; i++) { m = long_months[i]; t.tm_year = y-1900; t.tm_mon = m; t.tm_mday = 1; if (mktime(&t) == -1) { printf(, y, months[m]); continue; } if (t.tm_wday == 5) { printf(, y, months[m]); n++; } } } printf(, n); return 0; }
830Five weekends
5c
chr9c
import Control.Monad (guard) import Data.List (find, unfoldr) import Data.Char (intToDigit) import qualified Data.Set as Set import Text.Printf (printf) digits :: Integral a => a -> a -> [a] digits b = unfoldr (((>>) . guard . (0 /=)) <*> (pure . ((,) <$> (`mod` b) <*> (`div` b)))) sequenceForBaseN :: Integral a => a -> [a] sequenceForBaseN b = unfoldr (\(v, n) -> Just (v, (v + n, n + 2))) (i ^ 2, i * 2 + 1) where i = succ (round $ sqrt (realToFrac (b ^ pred b))) searchSequence :: Integral a => a -> Maybe a searchSequence b = find ((digitsSet ==) . Set.fromList . digits b) (sequenceForBaseN b) where digitsSet = Set.fromList [0 .. pred b] display :: Integer -> Integer -> String display b n = map (intToDigit . fromIntegral) $ reverse $ digits b n main :: IO () main = mapM_ (\b -> case searchSequence b of Just n -> printf "Base%2d:%8s ->%16s\n" b (display b (squareRootValue n)) (display b n) Nothing -> pure ()) [2 .. 16] where squareRootValue = round . sqrt . realToFrac
828First perfect square in base n with n unique digits
8haskell
jsq7g
(use 'clojure.contrib.math) (let [fns [#(Math/sin %) #(Math/cos %) (fn [x] (* x x x))] inv [#(Math/asin %) #(Math/acos %) #(expt % 1/3)]] (map #(% 0.5) (map #(comp %1 %2) fns inv)))
829First-class functions
6clojure
8m605
import Control.Monad (replicateM, unless) import Data.List (tails, transpose) import System.Random (randomRIO) data Cell = Empty | Tree | Fire deriving (Eq) instance Show Cell where show Empty = " " show Tree = "T" show Fire = "$" randomCell :: IO Cell randomCell = fmap ([Empty, Tree] !!) (randomRIO (0, 1) :: IO Int) randomChance :: IO Double randomChance = randomRIO (0, 1.0) :: IO Double rim :: a -> [[a]] -> [[a]] rim b = fmap (fb b) . (fb =<< rb) where fb = (.) <$> (:) <*> (flip (++) . return) rb = fst . unzip . zip (repeat b) . head take3x3 :: [[a]] -> [[[a]]] take3x3 = concatMap (transpose . fmap take3) . take3 where take3 = init . init . takeWhile (not . null) . fmap (take 3) . tails list2Mat :: Int -> [a] -> [[a]] list2Mat n = takeWhile (not . null) . fmap (take n) . iterate (drop n) evolveForest :: Int -> Int -> Int -> IO () evolveForest m n k = do let s = m * n fs <- replicateM s randomCell let nextState xs = do ts <- replicateM s randomChance vs <- replicateM s randomChance let rv [r1, [l, c, r], r3] newTree fire | c == Fire = Empty | c == Tree && Fire `elem` concat [r1, [l, r], r3] = Fire | c == Tree && 0.01 >= fire = Fire | c == Empty && 0.1 >= newTree = Tree | otherwise = c return $ zipWith3 rv xs ts vs evolve i xs = unless (i > k) $ do let nfs = nextState $ take3x3 $ rim Empty $ list2Mat n xs putStrLn ("\n>>>>>> " ++ show i ++ ":") mapM_ (putStrLn . concatMap show) $ list2Mat n xs nfs >>= evolve (i + 1) evolve 1 fs main :: IO () main = evolveForest 6 50 3
821Forest fire
8haskell
u1sv2
environments = [{'cnt':0, 'seq':i+1} for i in range(12)] code = ''' print('% 4d'% seq, end='') if seq!= 1: cnt += 1 seq = 3 * seq + 1 if seq & 1 else seq ''' while any(env['seq'] > 1 for env in environments): for env in environments: exec(code, globals(), env) print() print('Counts') for env in environments: print('% 4d'% env['cnt'], end='') print()
826First class environments
3python
m7jyh
code <- quote( if (n == 1) n else { count <- count + 1; n <- if (n%% 2 == 1) 3 * n + 1 else n/2 }) eprint <- function(envs, var="n") cat(paste(sprintf("%4d", sapply(envs, `[[`, var)), collapse=" "), "\n") envs <- mapply(function(...) list2env(list(...)), n=1:12, count=0) while (any(sapply(envs, eval, expr=code) > 1)) {eprint(envs)} eprint(envs) cat("\nCounts:\n") eprint(envs, "count")
826First class environments
13r
z54th
null
825Fivenum
11kotlin
chb98
import java.math.BigInteger; import java.time.Duration; import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Set; public class Program { static final String ALPHABET = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz|"; static byte base, bmo, blim, ic; static long st0; static BigInteger bllim, threshold; static Set<Byte> hs = new HashSet<>(); static Set<Byte> o = new HashSet<>(); static final char[] chars = ALPHABET.toCharArray(); static List<BigInteger> limits; static String ms; static int indexOf(char c) { for (int i = 0; i < chars.length; ++i) { if (chars[i] == c) { return i; } } return -1; }
828First perfect square in base n with n unique digits
9java
u1pvv
from random import randrange from copy import deepcopy from string import ascii_lowercase try: input = raw_input except: pass N = 3 board = [[0]* N for i in range(N)] def setbits(board, count=1): for i in range(count): board[randrange(N)][randrange(N)] ^= 1 def shuffle(board, count=1): for i in range(count): if randrange(0, 2): fliprow(randrange(N)) else: flipcol(randrange(N)) def pr(board, comment=''): print(str(comment)) print(' ' + ' '.join(ascii_lowercase[i] for i in range(N))) print(' ' + '\n '.join(' '.join(['%2s'% j] + [str(i) for i in line]) for j, line in enumerate(board, 1))) def init(board): setbits(board, count=randrange(N)+1) target = deepcopy(board) while board == target: shuffle(board, count=2 * N) prompt = ' X, T, or 1-%i /%s-%s to flip: '% (N, ascii_lowercase[0], ascii_lowercase[N-1]) return target, prompt def fliprow(i): board[i-1][:] = [x ^ 1 for x in board[i-1] ] def flipcol(i): for row in board: row[i] ^= 1 if __name__ == '__main__': print(__doc__% (N, N)) target, prompt = init(board) pr(target, 'Target configuration is:') print('') turns = 0 while board != target: turns += 1 pr(board, '%i:'% turns) ans = input(prompt).strip() if (len(ans) == 1 and ans in ascii_lowercase and ascii_lowercase.index(ans) < N): flipcol(ascii_lowercase.index(ans)) elif ans and all(ch in '0123456789' for ch in ans) and 1 <= int(ans) <= N: fliprow(int(ans)) elif ans == 'T': pr(target, 'Target configuration is:') turns -= 1 elif ans == 'X': break else: print( % ans[:9]) turns -= 1 else: print('\nWell done!\nBye.')
820Flipping bits game
3python
chw9q
from math import log, modf, floor def p(l, n, pwr=2): l = int(abs(l)) digitcount = floor(log(l, 10)) log10pwr = log(pwr, 10) raised, found = -1, 0 while found < n: raised += 1 firstdigits = floor(10**(modf(log10pwr * raised)[0] + digitcount)) if firstdigits == l: found += 1 return raised if __name__ == '__main__': for l, n in [(12, 1), (12, 2), (123, 45), (123, 12345), (123, 678910)]: print(f, p(l, n))
822First power of 2 that has leading decimal digits of 12
3python
fvrde
for i in range(n): if (n%2) == 0: continue if (n%i) == 0: result = i break else: result = None print
819Flow-control structures
3python
icrof
def xor(a, b): return (a and not b) or (b and not a) def ha(a, b): return xor(a, b), a and b def fa(a, b, ci): s0, c0 = ha(ci, a) s1, c1 = ha(s0, b) return s1, c0 or c1 def fa4(a, b): width = 4 ci = [None] * width co = [None] * width s = [None] * width for i in range(width): s[i], co[i] = fa(a[i], b[i], co[i-1] if i else 0) return s, co[-1] def int2bus(n, width=4): return [int(c) for c in .format(n, width)[::-1]] def bus2int(b): return sum(1 << i for i, bit in enumerate(b) if bit) def test_fa4(): width = 4 tot = [None] * (width + 1) for a in range(2**width): for b in range(2**width): tot[:width], tot[width] = fa4(int2bus(a), int2bus(b)) assert a + b == bus2int(tot), % (a, b, tot) if __name__ == '__main__': test_fa4()
814Four bit adder
3python
rx6gq
function slice(tbl, low, high) local copy = {} for i=low or 1, high or #tbl do copy[#copy+1] = tbl[i] end return copy end
825Fivenum
1lua
lkpck
typedef struct{ double x,y; }point; double lineSlope(point a,point b){ if(a.x-b.x == 0.0) return NAN; else return (a.y-b.y)/(a.x-b.x); } point extractPoint(char* str){ int i,j,start,end,length; char* holder; point c; for(i=0;str[i]!=00;i++){ if(str[i]=='(') start = i; if(str[i]==','||str[i]==')') { end = i; length = end - start; holder = (char*)malloc(length*sizeof(char)); for(j=0;j<length-1;j++) holder[j] = str[start + j + 1]; holder[j] = 00; if(str[i]==','){ start = i; c.x = atof(holder); } else c.y = atof(holder); } } return c; } point intersectionPoint(point a1,point a2,point b1,point b2){ point c; double slopeA = lineSlope(a1,a2), slopeB = lineSlope(b1,b2); if(slopeA==slopeB){ c.x = NAN; c.y = NAN; } else if(isnan(slopeA) && !isnan(slopeB)){ c.x = a1.x; c.y = (a1.x-b1.x)*slopeB + b1.y; } else if(isnan(slopeB) && !isnan(slopeA)){ c.x = b1.x; c.y = (b1.x-a1.x)*slopeA + a1.y; } else{ c.x = (slopeA*a1.x - slopeB*b1.x + b1.y - a1.y)/(slopeA - slopeB); c.y = slopeB*(c.x - b1.x) + b1.y; } return c; } int main(int argC,char* argV[]) { point c; if(argC < 5) printf(,argV[0]); else{ c = intersectionPoint(extractPoint(argV[1]),extractPoint(argV[2]),extractPoint(argV[3]),extractPoint(argV[4])); if(isnan(c.x)) printf(); else printf(,c.x,c.y); } return 0; }
831Find the intersection of two lines
5c
lkrcy
typedef struct{ double x,y,z; }vector; vector addVectors(vector a,vector b){ return (vector){a.x+b.x,a.y+b.y,a.z+b.z}; } vector subVectors(vector a,vector b){ return (vector){a.x-b.x,a.y-b.y,a.z-b.z}; } double dotProduct(vector a,vector b){ return a.x*b.x + a.y*b.y + a.z*b.z; } vector scaleVector(double l,vector a){ return (vector){l*a.x,l*a.y,l*a.z}; } vector intersectionPoint(vector lineVector, vector linePoint, vector planeNormal, vector planePoint){ vector diff = subVectors(linePoint,planePoint); return addVectors(addVectors(diff,planePoint),scaleVector(-dotProduct(diff,planeNormal)/dotProduct(lineVector,planeNormal),lineVector)); } int main(int argC,char* argV[]) { vector lV,lP,pN,pP,iP; if(argC!=5) printf(); else{ sscanf(argV[1],,&lV.x,&lV.y,&lV.z); sscanf(argV[3],,&pN.x,&pN.y,&pN.z); if(dotProduct(lV,pN)==0) printf(); else{ sscanf(argV[2],,&lP.x,&lP.y,&lP.z); sscanf(argV[4],,&pP.x,&pP.y,&pP.z); iP = intersectionPoint(lV,lP,pN,pP); printf(,iP.x,iP.y,iP.z); } } return 0; }
832Find the intersection of a line with a plane
5c
z5ctx
(() => { 'use strict';
828First perfect square in base n with n unique digits
10javascript
7qxrd
sub multiplier { my ( $n1, $n2 ) = @_; sub { $n1 * $n2 * $_[0]; }; } my $x = 2.0; my $xi = 0.5; my $y = 4.0; my $yi = 0.25; my $z = $x + $y; my $zi = 1.0 / ( $x + $y ); my %zip; @zip{ $x, $y, $z } = ( $xi, $yi, $zi ); while ( my ( $number, $inverse ) = each %zip ) { print multiplier( $number, $inverse )->(0.5), "\n"; }
823First-class functions/Use numbers analogously
2perl
icuo3
sub FloydWarshall{ my $edges = shift; my (@dist, @seq); my $num_vert = 0; map { $dist[$_->[0] - 1][$_->[1] - 1] = $_->[2]; $num_vert = $_->[0] if $num_vert < $_->[0]; $num_vert = $_->[1] if $num_vert < $_->[1]; } @$edges; my @vertices = 0..($num_vert - 1); for my $i(@vertices){ for my $j(@vertices){ $seq[$i][$j] = $j if $i != $j; } } for my $k(@vertices){ for my $i(@vertices){ next unless defined $dist[$i][$k]; for my $j(@vertices){ next unless defined $dist[$k][$j]; if($i != $j && (!defined($dist[$i][$j]) || $dist[$i][$j] > $dist[$i][$k] + $dist[$k][$j])){ $dist[$i][$j] = $dist[$i][$k] + $dist[$k][$j]; $seq[$i][$j] = $seq[$i][$k]; } } } } print "pair dist path\n"; for my $i(@vertices){ for my $j(@vertices){ next if $i == $j; my @path = ($i + 1); while($seq[$path[-1] - 1][$j] != $j){ push @path, $seq[$path[-1] - 1][$j] + 1; } push @path, $j + 1; printf "%d ->%d %4d %s\n", $path[0], $path[-1], $dist[$i][$j], join(' -> ', @path); } } } my $graph = [[1, 3, -2], [2, 1, 4], [2, 3, 3], [3, 4, 2], [4, 2, -1]]; FloydWarshall($graph);
817Floyd-Warshall algorithm
2perl
js37f
func multiply(a: Double, b: Double) -> Double { return a * b }
808Function definition
17swift
bogkd
(import java.util.GregorianCalendar java.text.DateFormatSymbols) (->> (for [year (range 1900 2101) month [0 2 4 6 7 9 11] :let [cal (GregorianCalendar. year month 1) day (.get cal GregorianCalendar/DAY_OF_WEEK)] :when (= day GregorianCalendar/FRIDAY)] (println month "-" year)) count (println "Total Months: " ,))
830Five weekends
6clojure
5abuz
import java.math.BigInteger import java.time.Duration import java.util.ArrayList import java.util.HashSet import kotlin.math.sqrt const val ALPHABET = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz|" var base: Byte = 0 var bmo: Byte = 0 var blim: Byte = 0 var ic: Byte = 0 var st0: Long = 0 var bllim: BigInteger? = null var threshold: BigInteger? = null var hs: MutableSet<Byte> = HashSet() var o: MutableSet<Byte> = HashSet() val chars = ALPHABET.toCharArray() var limits: MutableList<BigInteger?>? = null var ms: String? = null fun indexOf(c: Char): Int { for (i in chars.indices) { if (chars[i] == c) { return i } } return -1 }
828First perfect square in base n with n unique digits
11kotlin
9j7mh
import 'dart:math' as Math; cube(x) => x*x*x; cuberoot(x) => Math.pow(x, 1/3); compose(f,g) => ((x)=>f(g(x))); main(){ var functions = [Math.sin, Math.exp, cube]; var inverses = [Math.asin, Math.log, cuberoot]; for (int i = 0; i < 3; i++){ print(compose(functions[i], inverses[i])(0.5)); } }
829First-class functions
18dart
k8shj
envs = (1..12).map do |n| Object.new.instance_eval {@n = n; @cnt = 0; self} end until envs.all? {|e| e.instance_eval{@n} == 1} envs.each do |e| e.instance_eval do printf , @n if @n > 1 @cnt += 1 @n = if @n.odd? @n * 3 + 1 else @n / 2 end end end end puts end puts '=' * 48 envs.each do |e| e.instance_eval do printf , @cnt end end puts
826First class environments
14ruby
chk9k