code
stringlengths
1
46.1k
label
class label
1.18k classes
domain_label
class label
21 classes
index
stringlengths
4
5
public class McNuggets { public static void main(String... args) { int[] SIZES = new int[] { 6, 9, 20 }; int MAX_TOTAL = 100;
585McNuggets problem
9java
kzqhm
import org.bouncycastle.crypto.digests.MD4Digest; import org.bouncycastle.util.encoders.Hex; public class RosettaMD4 { public static void main (String[] argv) throws Exception { byte[] r = "Rosetta Code".getBytes("US-ASCII"); MD4Digest d = new MD4Digest(); d.update (r, 0, r.length); byte[] o = new byte[d.getDigestSize()]; d.doFinal (o, 0); Hex.encode (o, System.out); System.out.println(); } }
586MD4
9java
e9oa5
(() => { 'use strict';
585McNuggets problem
10javascript
e9iao
size_t base20(unsigned int n, uint8_t *out) { uint8_t *start = out; do {*out++ = n % 20;} while (n /= 20); size_t length = out - start; while (out > start) { uint8_t x = *--out; *out = *start; *start++ = x; } return length; } void make_digit(int n, char *place, size_t line_length) { static const char *parts[] = {,,,,,}; int i; for (i=4; i>0; i--, n -= 5) memcpy(place + i*line_length, parts[MAX(0, MIN(5, n))], 4); if (n == -20) place[4 * line_length + 1] = '@'; } char *mayan(unsigned int n) { if (n == 0) return NULL; uint8_t digits[15]; size_t n_digits = base20(n, digits); size_t line_length = n_digits*5 + 2; char *str = malloc(line_length * 6 + 1); if (str == NULL) return NULL; str[line_length * 6] = 0; char *ptr; unsigned int i; for (ptr=str, i=0; i<line_length; i+=5, ptr+=5) memcpy(ptr, , 5); memcpy(ptr-5, , 2); memcpy(str+5*line_length, str, line_length); for (ptr=str+line_length, i=0; i<line_length; i+=5, ptr+=5) memcpy(ptr, , 5); memcpy(ptr-5, , 2); memcpy(str+2*line_length, str+line_length, line_length); memcpy(str+3*line_length, str+line_length, 2*line_length); for (i=0; i<n_digits; i++) make_digit(digits[i], str+1+5*i, line_length); return str; } int main(int argc, char **argv) { if (argc != 2) { fprintf(stderr, ); return 1; } int i = atoi(argv[1]); if (i <= 0) { fprintf(stderr, ); return 1; } char *m = mayan(i); printf(,m); free(m); return 0; }
589Mayan numerals
5c
y1l6f
const md4func = () => { const hexcase = 0; const b64pad = ""; const chrsz = 8; const tab = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; const hex_tab = hexcase ? "0123456789ABCDEF" : "0123456789abcdef"; const safe_add = (x, y) => { const lsw = (x & 0xFFFF) + (y & 0xFFFF); const msw = (x >> 16) + (y >> 16) + (lsw >> 16); return (msw << 16) | (lsw & 0xFFFF); }; const rol = (num, cnt) => (num << cnt) | (num >>> (32 - cnt)); const str2binl = str => { const bin = Array(); const mask = (1 << chrsz) - 1; for (let i = 0; i < str.length * chrsz; i += chrsz) bin[i >> 5] |= (str.charCodeAt(i / chrsz) & mask) << (i % 32); return bin; }; const binl2str = bin => { let str = ""; const mask = (1 << chrsz) - 1; for (let i = 0; i < bin.length * 32; i += chrsz) str += String.fromCharCode((bin[i >> 5] >>> (i % 32)) & mask); return str; }; const binl2hex = binarray => { let str = ""; for (let i = 0; i < binarray.length * 4; i++) { str += hex_tab.charAt((binarray[i >> 2] >> ((i % 4) * 8 + 4)) & 0xF) + hex_tab.charAt((binarray[i >> 2] >> ((i % 4) * 8)) & 0xF); } return str; }; const binl2b64 = binarray => { let str = ""; for (let i = 0; i < binarray.length * 4; i += 3) { const triplet = (((binarray[i >> 2] >> 8 * (i % 4)) & 0xFF) << 16) | (((binarray[i + 1 >> 2] >> 8 * ((i + 1) % 4)) & 0xFF) << 8) | ((binarray[i + 2 >> 2] >> 8 * ((i + 2) % 4)) & 0xFF); for (let j = 0; j < 4; j++) { if (i * 8 + j * 6 > binarray.length * 32) str += b64pad; else str += tab.charAt((triplet >> 6 * (3 - j)) & 0x3F); } } return str; }; const core_md4 = (x, len) => { x[len >> 5] |= 0x80 << (len % 32); x[(((len + 64) >>> 9) << 4) + 14] = len; let a = 1732584193; let b = -271733879; let c = -1732584194; let d = 271733878; for (let i = 0; i < x.length; i += 16) { const olda = a; const oldb = b; const oldc = c; const oldd = d; a = md4_ff(a, b, c, d, x[i], 3); d = md4_ff(d, a, b, c, x[i + 1], 7); c = md4_ff(c, d, a, b, x[i + 2], 11); b = md4_ff(b, c, d, a, x[i + 3], 19); a = md4_ff(a, b, c, d, x[i + 4], 3); d = md4_ff(d, a, b, c, x[i + 5], 7); c = md4_ff(c, d, a, b, x[i + 6], 11); b = md4_ff(b, c, d, a, x[i + 7], 19); a = md4_ff(a, b, c, d, x[i + 8], 3); d = md4_ff(d, a, b, c, x[i + 9], 7); c = md4_ff(c, d, a, b, x[i + 10], 11); b = md4_ff(b, c, d, a, x[i + 11], 19); a = md4_ff(a, b, c, d, x[i + 12], 3); d = md4_ff(d, a, b, c, x[i + 13], 7); c = md4_ff(c, d, a, b, x[i + 14], 11); b = md4_ff(b, c, d, a, x[i + 15], 19); a = md4_gg(a, b, c, d, x[i], 3); d = md4_gg(d, a, b, c, x[i + 4], 5); c = md4_gg(c, d, a, b, x[i + 8], 9); b = md4_gg(b, c, d, a, x[i + 12], 13); a = md4_gg(a, b, c, d, x[i + 1], 3); d = md4_gg(d, a, b, c, x[i + 5], 5); c = md4_gg(c, d, a, b, x[i + 9], 9); b = md4_gg(b, c, d, a, x[i + 13], 13); a = md4_gg(a, b, c, d, x[i + 2], 3); d = md4_gg(d, a, b, c, x[i + 6], 5); c = md4_gg(c, d, a, b, x[i + 10], 9); b = md4_gg(b, c, d, a, x[i + 14], 13); a = md4_gg(a, b, c, d, x[i + 3], 3); d = md4_gg(d, a, b, c, x[i + 7], 5); c = md4_gg(c, d, a, b, x[i + 11], 9); b = md4_gg(b, c, d, a, x[i + 15], 13); a = md4_hh(a, b, c, d, x[i], 3); d = md4_hh(d, a, b, c, x[i + 8], 9); c = md4_hh(c, d, a, b, x[i + 4], 11); b = md4_hh(b, c, d, a, x[i + 12], 15); a = md4_hh(a, b, c, d, x[i + 2], 3); d = md4_hh(d, a, b, c, x[i + 10], 9); c = md4_hh(c, d, a, b, x[i + 6], 11); b = md4_hh(b, c, d, a, x[i + 14], 15); a = md4_hh(a, b, c, d, x[i + 1], 3); d = md4_hh(d, a, b, c, x[i + 9], 9); c = md4_hh(c, d, a, b, x[i + 5], 11); b = md4_hh(b, c, d, a, x[i + 13], 15); a = md4_hh(a, b, c, d, x[i + 3], 3); d = md4_hh(d, a, b, c, x[i + 11], 9); c = md4_hh(c, d, a, b, x[i + 7], 11); b = md4_hh(b, c, d, a, x[i + 15], 15); a = safe_add(a, olda); b = safe_add(b, oldb); c = safe_add(c, oldc); d = safe_add(d, oldd); } return Array(a, b, c, d); }; const md4_cmn = (q, a, b, x, s, t) => safe_add( rol(safe_add(safe_add(a, q), safe_add(x, t)), s), b); const md4_ff = (a, b, c, d, x, s) => md4_cmn( (b & c) | ((~b) & d), a, 0, x, s, 0); const md4_gg = (a, b, c, d, x, s) => md4_cmn( (b & c) | (b & d) | (c & d), a, 0, x, s, 1518500249); const md4_hh = (a, b, c, d, x, s) => md4_cmn( b ^ c ^ d, a, 0, x, s, 1859775393); const core_hmac_md4 = (key, data) => { let bkey = str2binl(key); if (bkey.length > 16) { bkey = core_md4(bkey, key.length * chrsz) } const ipad = Array(16); const opad = Array(16); for (let i = 0; i < 16; i++) { ipad[i] = bkey[i] ^ 0x36363636; opad[i] = bkey[i] ^ 0x5C5C5C5C; } const hash = core_md4( ipad.concat(str2binl(data)), 512 + data.length * chrsz); return core_md4(opad.concat(hash), 512 + 128); }; return { hex_md4: s => binl2hex(core_md4(str2binl(s), s.length * chrsz)), b64_md4: s => binl2b64(core_md4(str2binl(s), s.length * chrsz)), str_md4: s => binl2str(core_md4(str2binl(s), s.length * chrsz)), hex_hmac_md4: (key, data) => binl2hex(core_hmac_md4(key, data)), b64_hmac_md4: (key, data) => binl2b64(core_hmac_md4(key, data)), str_hmac_md4: (key, data) => binl2str(core_hmac_md4(key, data)), }; }; const md4 = md4func(); console.log(md4.hex_md4('Rosetta Code'));
586MD4
10javascript
0utsz
(ns clojure.examples.rosetta (:gen-class) (:require [clojure.string:as string])) (def rosetta "55 94 48 95 30 96 77 71 26 67 97 13 76 38 45 07 36 79 16 37 68 48 07 09 18 70 26 06 18 72 79 46 59 79 29 90 20 76 87 11 32 07 07 49 18 27 83 58 35 71 11 25 57 29 85 14 64 36 96 27 11 58 56 92 18 55 02 90 03 60 48 49 41 46 33 36 47 23 92 50 48 02 36 59 42 79 72 20 82 77 42 56 78 38 80 39 75 02 71 66 66 01 03 55 72 44 25 67 84 71 67 11 61 40 57 58 89 40 56 36 85 32 25 85 57 48 84 35 47 62 17 01 01 99 89 52 06 71 28 75 94 48 37 10 23 51 06 48 53 18 74 98 15 27 02 92 23 08 71 76 84 15 52 92 63 81 10 44 10 69 93") (defn parse-int [s] " Convert digits to a number (finds digits when could be surrounded by non-digits" (Integer. (re-find #"\d+" s))) (defn data-int-array [s] " Convert string to integer array" (map parse-int (string/split (string/trim s) #"\s+"))) (defn nested-triangle [s] " Convert triangle to nested vector, with each inner vector containing one triangle row" (loop [lst s n 1 newlist nil] (if (empty? lst) (reverse newlist) (recur (drop n lst) (inc n) (cons (take n lst) newlist))))) (def nested-list (nested-triangle (data-int-array rosetta))) (defn max-sum [s] " Compute maximum path sum using a technique described here: http://mishadoff.com/blog/clojure-euler-problem-018/" (reduce (fn [a b] (map + b (map max a (rest a)))) (reverse s))) (println (max-sum nested-list))
588Maximum triangle path sum
6clojure
o4t8j
def middle_three_digits(num) num = num.abs length = (str = num.to_s).length raise ArgumentError, if length < 3 raise ArgumentError, if length.even? return str[length/2 - 1, 3].to_i end
581Middle three digits
14ruby
vs12n
const char *string = ; int main() { int i; unsigned char result[MD5_DIGEST_LENGTH]; MD5(string, strlen(string), result); for(i = 0; i < MD5_DIGEST_LENGTH; i++) printf(, result[i]); printf(); return EXIT_SUCCESS; }
590MD5
5c
vs42o
null
585McNuggets problem
11kotlin
gi14d
null
586MD4
11kotlin
kzxh3
fn middle_three_digits(x: i32) -> Result<String, String> { let s: String = x.abs().to_string(); let len = s.len(); if len < 3 { Err("Too short".into()) } else if len% 2 == 0 { Err("Even number of digits".into()) } else { Ok(s[len/2 - 1 .. len/2 + 2].to_owned()) } } fn print_result(x: i32) { print!("middle_three_digits({}) returned: ", x); match middle_three_digits(x) { Ok(s) => println!("Success, {}", s), Err(s) => println!("Failure, {}", s) } } fn main() { let passing = [123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345]; let failing = [1, 2, -1, -10, 2002, -2002, 0]; for i in passing.iter() { print_result(*i); } for i in failing.iter() { print_result(*i); } }
581Middle three digits
15rust
u0avj
function range(A,B) return function() return coroutine.wrap(function() for i = A, B do coroutine.yield(i) end end) end end function filter(stream, f) return function() return coroutine.wrap(function() for i in stream() do if f(i) then coroutine.yield(i) end end end) end end function triple(s1, s2, s3) return function() return coroutine.wrap(function() for x in s1() do for y in s2() do for z in s3() do coroutine.yield{x,y,z} end end end end) end end function apply(f, stream) return function() return coroutine.wrap(function() for T in stream() do coroutine.yield(f(table.unpack(T))) end end) end end function exclude(s1, s2) local exlusions = {} for x in s1() do exlusions[x] = true end return function() return coroutine.wrap(function() for x in s2() do if not exlusions[x] then coroutine.yield(x) end end end) end end function maximum(stream) local M = math.mininteger for x in stream() do M = math.max(M, x) end return M end local N = 100 local A, B, C = 6, 9, 20 local Xs = filter(range(0, N), function(x) return x % A == 0 end) local Ys = filter(range(0, N), function(x) return x % B == 0 end) local Zs = filter(range(0, N), function(x) return x % C == 0 end) local sum = filter(apply(function(x, y, z) return x + y + z end, triple(Xs, Ys, Zs)), function(x) return x <= N end) print(maximum(exclude(sum, range(1, N))))
585McNuggets problem
1lua
rnaga
package main import ( "fmt" "strconv" ) const ( ul = "" uc = "" ur = "" ll = "" lc = "" lr = "" hb = "" vb = "" ) var mayan = [5]string{ " ", " ", " ", " ", "", } const ( m0 = " " m5 = "" ) func dec2vig(n uint64) []uint64 { vig := strconv.FormatUint(n, 20) res := make([]uint64, len(vig)) for i, d := range vig { res[i], _ = strconv.ParseUint(string(d), 20, 64) } return res } func vig2quin(n uint64) [4]string { if n >= 20 { panic("Cant't convert a number >= 20") } res := [4]string{mayan[0], mayan[0], mayan[0], mayan[0]} if n == 0 { res[3] = m0 return res } fives := n / 5 rem := n % 5 res[3-fives] = mayan[rem] for i := 3; i > 3-int(fives); i-- { res[i] = m5 } return res } func draw(mayans [][4]string) { lm := len(mayans) fmt.Print(ul) for i := 0; i < lm; i++ { for j := 0; j < 4; j++ { fmt.Print(hb) } if i < lm-1 { fmt.Print(uc) } else { fmt.Println(ur) } } for i := 1; i < 5; i++ { fmt.Print(vb) for j := 0; j < lm; j++ { fmt.Print(mayans[j][i-1]) fmt.Print(vb) } fmt.Println() } fmt.Print(ll) for i := 0; i < lm; i++ { for j := 0; j < 4; j++ { fmt.Print(hb) } if i < lm-1 { fmt.Print(lc) } else { fmt.Println(lr) } } } func main() { numbers := []uint64{4005, 8017, 326205, 886205, 1081439556} for _, n := range numbers { fmt.Printf("Converting%d to Mayan:\n", n) vigs := dec2vig(n) lv := len(vigs) mayans := make([][4]string, lv) for i, vig := range vigs { mayans[i] = vig2quin(vig) } draw(mayans) fmt.Println() } }
589Mayan numerals
0go
1yxp5
#!/usr/bin/lua require "crypto" print(crypto.digest("MD4", "Rosetta Code"))
586MD4
1lua
b3qka
def middleThree( s:Int ) : Option[Int] = s.abs.toString match { case v if v.length % 2 == 0 => None
581Middle three digits
16scala
gix4i
import Data.Bool (bool) import Data.List (intercalate, transpose) import qualified Data.Map.Strict as M import Data.Maybe (maybe) main :: IO () main = (putStrLn . unlines) $ mayanFramed <$> [ 4005, 8017, 326205, 886205, 1081439556, 1000000, 1000000000 ] mayanGlyph :: Int -> [[String]] mayanGlyph = filter (any (not . null)) . transpose . leftPadded . flip (showIntAtBaseS 20 mayanDigit) [] mayanDigit :: Int -> [String] mayanDigit n | 0 /= n = replicate (rem n 5) mayaOne: concat ( replicate (quot n 5) [mayaFive] ) | otherwise = [[mayaZero]] mayanFramed :: Int -> String mayanFramed = ("Mayan " <>) . ( (<>) <$> show <*> ( (":\n\n" <>) . wikiTable ( M.fromList [ ( "style", concat [ "text-align:center;", "background-color:#F0EDDE;", "color:#605B4B;", "border:2px solid silver;" ] ), ("colwidth", "3em;") ] ) . mayanGlyph ) ) mayaZero, mayaOne :: Char mayaZero = '\920' mayaOne = '\9679' mayaFive :: String mayaFive = "\9473\9473" showIntAtBaseS :: Integral a => a -> (Int -> [String]) -> a -> [[String]] -> [[String]] showIntAtBaseS base toStr n0 r0 = let go (n, d) r = seq s $ case n of 0 -> r_ _ -> go (quotRem n base) r_ where s = toStr (fromIntegral d) r_ = s: r in go (quotRem n0 base) r0 wikiTable :: M.Map String String -> [[String]] -> String wikiTable opts rows | null rows = [] | otherwise = "{| " <> foldr ( \k a -> maybe a ( ((a <> k <> "=\"") <>) . ( <> "\" " ) ) (M.lookup k opts) ) [] ["class", "style"] <> ( '\n': intercalate "|-\n" ( zipWith renderedRow rows [0 ..] ) ) <> "|}\n\n" where renderedRow row i = unlines ( fmap ( ( bool [] ( maybe "|" (("|style=\"width:" <>) . (<> "\"")) (M.lookup "colwidth" opts) ) (0 == i) <> ) . ('|':) ) row ) leftPadded :: [[String]] -> [[String]] leftPadded xs = let w = maximum (length <$> xs) in ((<>) =<< flip replicate [] . (-) w . length) <$> xs
589Mayan numerals
8haskell
thyf7
(apply str (map (partial format "%02x") (.digest (doto (java.security.MessageDigest/getInstance "MD5") .reset (.update (.getBytes "The quick brown fox jumps over the lazy dog"))))))
590MD5
6clojure
rnhg2
import java.math.BigInteger; public class MayanNumerals { public static void main(String[] args) { for ( long base10 : new long[] {4005, 8017, 326205, 886205, 1000000000, 1081439556L, 26960840421L, 503491211079L }) { displayMyan(BigInteger.valueOf(base10)); System.out.printf("%n"); } } private static char[] digits = "0123456789ABCDEFGHJK".toCharArray(); private static BigInteger TWENTY = BigInteger.valueOf(20); private static void displayMyan(BigInteger numBase10) { System.out.printf("As base 10: %s%n", numBase10); String numBase20 = ""; while ( numBase10.compareTo(BigInteger.ZERO) > 0 ) { numBase20 = digits[numBase10.mod(TWENTY).intValue()] + numBase20; numBase10 = numBase10.divide(TWENTY); } System.out.printf("As base 20: %s%nAs Mayan:%n", numBase20); displayMyanLine1(numBase20); displayMyanLine2(numBase20); displayMyanLine3(numBase20); displayMyanLine4(numBase20); displayMyanLine5(numBase20); displayMyanLine6(numBase20); } private static char boxUL = Character.toChars(9556)[0]; private static char boxTeeUp = Character.toChars(9574)[0]; private static char boxUR = Character.toChars(9559)[0]; private static char boxHorz = Character.toChars(9552)[0]; private static char boxVert = Character.toChars(9553)[0]; private static char theta = Character.toChars(952)[0]; private static char boxLL = Character.toChars(9562)[0]; private static char boxLR = Character.toChars(9565)[0]; private static char boxTeeLow = Character.toChars(9577)[0]; private static char bullet = Character.toChars(8729)[0]; private static char dash = Character.toChars(9472)[0]; private static void displayMyanLine1(String base20) { char[] chars = base20.toCharArray(); StringBuilder sb = new StringBuilder(); for ( int i = 0 ; i < chars.length ; i++ ) { if ( i == 0 ) { sb.append(boxUL); } for ( int j = 0 ; j < 4 ; j++ ) { sb.append(boxHorz); } sb.append(i < chars.length-1 ? boxTeeUp : boxUR); } System.out.println(sb.toString()); } private static String getBullet(int count) { StringBuilder sb = new StringBuilder(); switch ( count ) { case 1: sb.append(" " + bullet + " "); break; case 2: sb.append(" " + bullet + bullet + " "); break; case 3: sb.append("" + bullet + bullet + bullet + " "); break; case 4: sb.append("" + bullet + bullet + bullet + bullet); break; default: throw new IllegalArgumentException("Must be 1-4: " + count); } return sb.toString(); } private static void displayMyanLine2(String base20) { char[] chars = base20.toCharArray(); StringBuilder sb = new StringBuilder(); for ( int i = 0 ; i < chars.length ; i++ ) { if ( i == 0 ) { sb.append(boxVert); } switch ( chars[i] ) { case 'G': sb.append(getBullet(1)); break; case 'H': sb.append(getBullet(2)); break; case 'J': sb.append(getBullet(3)); break; case 'K': sb.append(getBullet(4)); break; default : sb.append(" "); } sb.append(boxVert); } System.out.println(sb.toString()); } private static String DASH = getDash(); private static String getDash() { StringBuilder sb = new StringBuilder(); for ( int i = 0 ; i < 4 ; i++ ) { sb.append(dash); } return sb.toString(); } private static void displayMyanLine3(String base20) { char[] chars = base20.toCharArray(); StringBuilder sb = new StringBuilder(); for ( int i = 0 ; i < chars.length ; i++ ) { if ( i == 0 ) { sb.append(boxVert); } switch ( chars[i] ) { case 'B': sb.append(getBullet(1)); break; case 'C': sb.append(getBullet(2)); break; case 'D': sb.append(getBullet(3)); break; case 'E': sb.append(getBullet(4)); break; case 'F': case 'G': case 'H': case 'J': case 'K': sb.append(DASH); break; default : sb.append(" "); } sb.append(boxVert); } System.out.println(sb.toString()); } private static void displayMyanLine4(String base20) { char[] chars = base20.toCharArray(); StringBuilder sb = new StringBuilder(); for ( int i = 0 ; i < chars.length ; i++ ) { if ( i == 0 ) { sb.append(boxVert); } switch ( chars[i] ) { case '6': sb.append(getBullet(1)); break; case '7': sb.append(getBullet(2)); break; case '8': sb.append(getBullet(3)); break; case '9': sb.append(getBullet(4)); break; case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': case 'G': case 'H': case 'J': case 'K': sb.append(DASH); break; default : sb.append(" "); } sb.append(boxVert); } System.out.println(sb.toString()); } private static void displayMyanLine5(String base20) { char[] chars = base20.toCharArray(); StringBuilder sb = new StringBuilder(); for ( int i = 0 ; i < chars.length ; i++ ) { if ( i == 0 ) { sb.append(boxVert); } switch ( chars[i] ) { case '0': sb.append(" " + theta + " "); break; case '1': sb.append(getBullet(1)); break; case '2': sb.append(getBullet(2)); break; case '3': sb.append(getBullet(3)); break; case '4': sb.append(getBullet(4)); break; case '5': case '6': case '7': case '8': case '9': case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': case 'G': case 'H': case 'J': case 'K': sb.append(DASH); break; default : sb.append(" "); } sb.append(boxVert); } System.out.println(sb.toString()); } private static void displayMyanLine6(String base20) { char[] chars = base20.toCharArray(); StringBuilder sb = new StringBuilder(); for ( int i = 0 ; i < chars.length ; i++ ) { if ( i == 0 ) { sb.append(boxLL); } for ( int j = 0 ; j < 4 ; j++ ) { sb.append(boxHorz); } sb.append(i < chars.length-1 ? boxTeeLow : boxLR); } System.out.println(sb.toString()); } }
589Mayan numerals
9java
85d06
typedef struct squareMtxStruct { int dim; double *cells; double **m; } *SquareMtx; typedef void (*FillFunc)( double *cells, int r, int dim, void *ff_data); SquareMtx NewSquareMtx( int dim, FillFunc fillFunc, void *ff_data ) { SquareMtx sm = malloc(sizeof(struct squareMtxStruct)); if (sm) { int rw; sm->dim = dim; sm->cells = malloc(dim*dim * sizeof(double)); sm->m = malloc( dim * sizeof(double *)); if ((sm->cells != NULL) && (sm->m != NULL)) { for (rw=0; rw<dim; rw++) { sm->m[rw] = sm->cells + dim*rw; fillFunc( sm->m[rw], rw, dim, ff_data ); } } else { free(sm->m); free(sm->cells); free(sm); printf(); return NULL; } } else { printf(); } return sm; } void ffMatxSquare( double *cells, int rw, int dim, SquareMtx m0 ) { int col, ix; double sum; double *m0rw = m0->m[rw]; for (col = 0; col < dim; col++) { sum = 0.0; for (ix=0; ix<dim; ix++) sum += m0rw[ix] * m0->m[ix][col]; cells[col] = sum; } } void ffMatxMulply( double *cells, int rw, int dim, SquareMtx mplcnds[] ) { SquareMtx mleft = mplcnds[0]; SquareMtx mrigt = mplcnds[1]; double sum; double *m0rw = mleft->m[rw]; int col, ix; for (col = 0; col < dim; col++) { sum = 0.0; for (ix=0; ix<dim; ix++) sum += m0rw[ix] * mrigt->m[ix][col]; cells[col] = sum; } } void MatxMul( SquareMtx mr, SquareMtx left, SquareMtx rigt) { int rw; SquareMtx mplcnds[2]; mplcnds[0] = left; mplcnds[1] = rigt; for (rw = 0; rw < left->dim; rw++) ffMatxMulply( mr->m[rw], rw, left->dim, mplcnds); } void ffIdentity( double *cells, int rw, int dim, void *v ) { int col; for (col=0; col<dim; col++) cells[col] = 0.0; cells[rw] = 1.0; } void ffCopy(double *cells, int rw, int dim, SquareMtx m1) { int col; for (col=0; col<dim; col++) cells[col] = m1->m[rw][col]; } void FreeSquareMtx( SquareMtx m ) { free(m->m); free(m->cells); free(m); } SquareMtx SquareMtxPow( SquareMtx m0, int exp ) { SquareMtx v0 = NewSquareMtx(m0->dim, ffIdentity, NULL); SquareMtx v1 = NULL; SquareMtx base0 = NewSquareMtx( m0->dim, ffCopy, m0); SquareMtx base1 = NULL; SquareMtx mplcnds[2], t; while (exp) { if (exp % 2) { if (v1) MatxMul( v1, v0, base0); else { mplcnds[0] = v0; mplcnds[1] = base0; v1 = NewSquareMtx(m0->dim, ffMatxMulply, mplcnds); } {t = v0; v0=v1; v1 = t;} } if (base1) MatxMul( base1, base0, base0); else base1 = NewSquareMtx( m0->dim, ffMatxSquare, base0); t = base0; base0 = base1; base1 = t; exp = exp/2; } if (base0) FreeSquareMtx(base0); if (base1) FreeSquareMtx(base1); if (v1) FreeSquareMtx(v1); return v0; } FILE *fout; void SquareMtxPrint( SquareMtx mtx, const char *mn ) { int rw, col; int d = mtx->dim; fprintf(fout, , mn, mtx->dim); for (rw=0; rw<d; rw++) { fprintf(fout, ); for(col=0; col<d; col++) fprintf(fout, ,mtx->m[rw][col] ); fprintf(fout, ); } fprintf(fout, ); } void fillInit( double *cells, int rw, int dim, void *data) { double theta = 3.1415926536/6.0; double c1 = cos( theta); double s1 = sin( theta); switch(rw) { case 0: cells[0]=c1; cells[1]=s1; cells[2]=0.0; break; case 1: cells[0]=-s1; cells[1]=c1; cells[2]=0; break; case 2: cells[0]=0.0; cells[1]=0.0; cells[2]=1.0; break; } } int main() { SquareMtx m0 = NewSquareMtx( 3, fillInit, NULL); SquareMtx m1 = SquareMtxPow( m0, 5); SquareMtx m2 = SquareMtxPow( m0, 9); SquareMtx m3 = SquareMtxPow( m0, 2); fout = fopen(, ); SquareMtxPrint(m0, ); FreeSquareMtx(m0); SquareMtxPrint(m1, ); FreeSquareMtx(m1); SquareMtxPrint(m2, ); FreeSquareMtx(m2); SquareMtxPrint(m3, ); FreeSquareMtx(m3); fclose(fout); return 0; }
591Matrix-exponentiation operator
5c
u04v4
int **m; int **s; void optimal_matrix_chain_order(int *dims, int n) { int len, i, j, k, temp, cost; n--; m = (int **)malloc(n * sizeof(int *)); for (i = 0; i < n; ++i) { m[i] = (int *)calloc(n, sizeof(int)); } s = (int **)malloc(n * sizeof(int *)); for (i = 0; i < n; ++i) { s[i] = (int *)calloc(n, sizeof(int)); } for (len = 1; len < n; ++len) { for (i = 0; i < n - len; ++i) { j = i + len; m[i][j] = INT_MAX; for (k = i; k < j; ++k) { temp = dims[i] * dims[k + 1] * dims[j + 1]; cost = m[i][k] + m[k + 1][j] + temp; if (cost < m[i][j]) { m[i][j] = cost; s[i][j] = k; } } } } } void print_optimal_chain_order(int i, int j) { if (i == j) printf(, i + 65); else { printf(); print_optimal_chain_order(i, s[i][j]); print_optimal_chain_order(s[i][j] + 1, j); printf(); } } int main() { int i, j, n; int a1[4] = {5, 6, 3, 1}; int a2[13] = {1, 5, 25, 30, 100, 70, 2, 1, 100, 250, 1, 1000, 2}; int a3[12] = {1000, 1, 500, 12, 1, 700, 2500, 3, 2, 5, 14, 10}; int *dims_list[3] = {a1, a2, a3}; int sizes[3] = {4, 13, 12}; for (i = 0; i < 3; ++i) { printf(); n = sizes[i]; for (j = 0; j < n; ++j) { printf(, dims_list[i][j]); if (j < n - 1) printf(); else printf(); } optimal_matrix_chain_order(dims_list[i], n); printf(); print_optimal_chain_order(0, n - 2); printf(, m[0][n - 2]); for (j = 0; j <= n - 2; ++j) free(m[j]); free(m); for (j = 0; j <= n - 2; ++j) free(s[j]); free(s); } return 0; }
592Matrix chain multiplication
5c
gir45
package main import ( "bytes" "fmt" "math/rand" "time" ) type maze struct { c2 [][]byte
587Maze solving
0go
9e5mt
(() => { 'use strict'; const main = () => unlines( map(mayanFramed, [4005, 8017, 326205, 886205, 1081439556, 1000000, 1000000000] ) );
589Mayan numerals
10javascript
fj6dg
#!/usr/bin/runhaskell import Data.Maybe (fromMaybe) average :: (Int, Int) -> (Int, Int) -> (Int, Int) average (x, y) (x_, y_) = ((x + x_) `div` 2, (y + y_) `div` 2) notBlocked :: [String] -> ((Int, Int), (Int, Int)) -> Bool notBlocked maze (_, (x, y)) = ' ' == (maze !! y) !! x substitute :: [a] -> Int -> a -> [a] substitute orig pos el = let (before, after) = splitAt pos orig in before ++ [el] ++ tail after draw :: [String] -> (Int, Int) -> [String] draw maze (x, y) = let row = maze !! y in substitute maze y $ substitute row x '*' tryMoves :: [String] -> (Int, Int) -> [((Int, Int), (Int, Int))] -> Maybe [String] tryMoves _ _ [] = Nothing tryMoves maze prevPos ((newPos, wallPos):more) = case solve_ maze newPos prevPos of Nothing -> tryMoves maze prevPos more Just maze_ -> Just $ foldl draw maze_ [newPos, wallPos] solve_ :: [String] -> (Int, Int) -> (Int, Int) -> Maybe [String] solve_ maze (2, 1) _ = Just maze solve_ maze pos@(x, y) prevPos = let newPositions = [(x, y - 2), (x + 4, y), (x, y + 2), (x - 4, y)] notPrev pos_ = pos_ /= prevPos newPositions_ = filter notPrev newPositions wallPositions = map (average pos) newPositions_ zipped = zip newPositions_ wallPositions legalMoves = filter (notBlocked maze) zipped in tryMoves maze pos legalMoves solve :: [String] -> Maybe [String] solve maze = solve_ (draw maze start) start (-1, -1) where startx = length (head maze) - 3 starty = length maze - 2 start = (startx, starty) main = let main_ = unlines . fromMaybe ["can_t solve"] . solve . lines in interact main_
587Maze solving
8haskell
b3xk2
;WITH DATA AS (SELECT CAST(ABS(NUMBER) AS NVARCHAR(MAX)) charNum, NUMBER, LEN(CAST(ABS(NUMBER) AS NVARCHAR(MAX))) LcharNum FROM TABLE1) SELECT CASE WHEN ( LCHARNUM >= 3 AND LCHARNUM% 2 = 1 ) THEN SUBSTRING(CHARNUM, LCHARNUM / 2, 3) ELSE 'Error!' END Output, NUMBER INPUT FROM DATA
581Middle three digits
19sql
jf07e
sub md4(@) { my @input = grep { defined && length > 0 } split /(.{64})/s, join '', @_; push @input, '' if !@input || length($input[$ my @A = (0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476); my @T = (0, 0x5A827999, 0x6ED9EBA1); my @L = qw(3 7 11 19 3 5 9 13 3 9 11 15); my @O = (1, 4, 4, 4, 1, 1, 0, 0, 1); my @I = map { my $z = int $_/16; my $x = $_%4; my $y = int $_%16/4; ($x,$y) = (R($x),R($y)) if $O[6+$z]; $O[$z] * $x + $O[3+$z] * $y } 0..47; my ($a,$b,$c,$d); my($l,$p) = (0,0); foreach (@input) { my $r = length($_); $l += $r; $r++, $_.="\x80" if $r<64 && !$p++; my @W = unpack 'V16', $_ . "\0"x7; push @W, (0)x16 if @W < 16; $W[14] = $l*8 if $r < 57; ($a,$b,$c,$d) = @A; for (0..47) { my $z = int $_/16; $a = L($L[4*($_>>4) + $_%4], M(&{(sub{$b&$c|~$b&$d}, sub{$b&$c|$b&$d|$c&$d}, sub{$b^$c^$d} )[$z]} + $a + $W[$I[$_]] + $T[$z])); ($a,$b,$c,$d) = ($d,$a,$b,$c); } my @v = ($a, $b, $c, $d); $A[$_] = M($A[$_] + $v[$_]) for 0..3; } pack 'V4', @A; } sub L { my ($n, $x) = @_; $x<<$n | 2**$n - 1 & $x>>(32-$n); } sub M { no integer; my ($x) = @_; my $m = 1+0xffffffff; $x - $m * int $x/$m; } sub R { my $n = pop; ($n&1)*2 + ($n&2)/2; } sub md4_hex(@) { unpack 'H*', &md4; } print "Rosetta Code => " . md4_hex( "Rosetta Code" ) . "\n";
586MD4
2perl
3b2zs
var num:Int = \\enter your number here if num<0{num = -num} var numArray:[Int]=[] while num>0{ var temp:Int=num%10 numArray.append(temp) num=num/10 } var i:Int=numArray.count if i<3||i%2==0{ print("Invalid Input") } else{ i=i/2 print("\(numArray[i+1]),\(numArray[i]),\(numArray[i-1])") }
581Middle three digits
17swift
2qplj
use ntheory qw/forperm gcd vecmin/; sub Mcnugget_number { my $counts = shift; return 'No maximum' if 1 < gcd @$counts; my $min = vecmin @$counts; my @meals; my @min; my $a = -1; while (1) { $a++; for my $b (0..$a) { for my $c (0..$b) { my @s = ($a, $b, $c); forperm { $meals[ $s[$_[0]] * $counts->[0] + $s[$_[1]] * $counts->[1] + $s[$_[2]] * $counts->[2] ] = 1; } @s; } } for my $i (0..$ next unless $meals[$i]; if ($min[-1] and $i == ($min[-1] + 1)) { push @min, $i; last if $min == @min } else { @min = $i; } } last if $min == @min } $min[0] ? $min[0] - 1 : 0 } for my $counts ([6,9,20], [6,7,20], [1,3,20], [10,5,18], [5,17,44], [2,4,6], [3,6,15]) { print 'Maximum non-Mcnugget number using ' . join(', ', @$counts) . ' is: ' . Mcnugget_number($counts) . "\n" }
585McNuggets problem
2perl
nrmiw
$ sudo apt install libncurses5-dev
593Matrix digital rain
5c
2q2lo
package main import "fmt"
592Matrix chain multiplication
0go
ignog
use ntheory qw/fromdigits todigitstring/; my $t_style = '"border-collapse: separate; text-align: center; border-spacing: 3px 0px;"'; my $c_style = '"border: solid black 2px;background-color: 'border-radius: 1em;-moz-border-radius: 1em;-webkit-border-radius: 1em;'. 'vertical-align: bottom;width: 3.25em;"'; sub cartouches { my($num, @digits) = @_; my $render; for my $d (@digits) { $render .= "| style=$c_style | $_\n" for glyphs(@$d); } chomp $render; join "\n", "\{| style=$t_style", "|+ $num", '|-', $render, '|}' } sub glyphs { return '' unless $_[0] || $_[1]; join '<br>', '' x $_[0], ('') x $_[1]; } sub mmod { my($n,$b) = @_; my @nb; return 0 unless $n; push @nb, fromdigits($_, $b) for split '', todigitstring($n, $b); return @nb; } for $n (qw<4005 8017 326205 886205 26960840421>) { push @output, cartouches($n, map { [reverse mmod($_,5)] } mmod($n,20) ); } print join "\n<br>\n", @output;
589Mayan numerals
2perl
lx5c5
import Data.List (elemIndex) import Data.Char (chr, ord) import Data.Maybe (fromJust) mats :: [[Int]] mats = [ [5, 6, 3, 1] , [1, 5, 25, 30, 100, 70, 2, 1, 100, 250, 1, 1000, 2] , [1000, 1, 500, 12, 1, 700, 2500, 3, 2, 5, 14, 10] ] cost :: [Int] -> Int -> Int -> (Int, Int) cost a i j | i < j = let m = [ fst (cost a i k) + fst (cost a (k + 1) j) + (a !! i) * (a !! (j + 1)) * (a !! (k + 1)) | k <- [i .. j - 1] ] mm = minimum m in (mm, fromJust (elemIndex mm m) + i) | otherwise = (0, -1) optimalOrder :: [Int] -> Int -> Int -> String optimalOrder a i j | i < j = let c = cost a i j in "(" ++ optimalOrder a i (snd c) ++ optimalOrder a (snd c + 1) j ++ ")" | otherwise = [chr ((+ i) $ ord 'a')] printBlock :: [Int] -> IO () printBlock v = let c = cost v 0 (length v - 2) in putStrLn ("for " ++ show v ++ " we have " ++ show (fst c) ++ " possibilities, z.B " ++ optimalOrder v 0 (length v - 2)) main :: IO () main = mapM_ printBlock mats
592Matrix chain multiplication
8haskell
vsu2k
import java.io.*; import java.util.*; public class MazeSolver { private static String[] readLines (InputStream f) throws IOException { BufferedReader r = new BufferedReader (new InputStreamReader (f, "US-ASCII")); ArrayList<String> lines = new ArrayList<String>(); String line; while ((line = r.readLine()) != null) lines.add (line); return lines.toArray(new String[0]); } private static char[][] decimateHorizontally (String[] lines) { final int width = (lines[0].length() + 1) / 2; char[][] c = new char[lines.length][width]; for (int i = 0 ; i < lines.length ; i++) for (int j = 0 ; j < width ; j++) c[i][j] = lines[i].charAt (j * 2); return c; } private static boolean solveMazeRecursively (char[][] maze, int x, int y, int d) { boolean ok = false; for (int i = 0 ; i < 4 && !ok ; i++) if (i != d) switch (i) {
587Maze solving
9java
gib4m
echo hash('md4', ), ;
586MD4
12php
p6sba
package main import ( gc "github.com/rthornton128/goncurses" "log" "math/rand" "time" )
593Matrix digital rain
0go
q2qxz
import java.util.Arrays; public class MatrixChainMultiplication { public static void main(String[] args) { runMatrixChainMultiplication(new int[] {5, 6, 3, 1}); runMatrixChainMultiplication(new int[] {1, 5, 25, 30, 100, 70, 2, 1, 100, 250, 1, 1000, 2}); runMatrixChainMultiplication(new int[] {1000, 1, 500, 12, 1, 700, 2500, 3, 2, 5, 14, 10}); } private static void runMatrixChainMultiplication(int[] dims) { System.out.printf("Array Dimension =%s%n", Arrays.toString(dims)); System.out.printf("Cost =%d%n", matrixChainOrder(dims)); System.out.printf("Optimal Multiply =%s%n%n", getOptimalParenthesizations()); } private static int[][]cost; private static int[][]order; public static int matrixChainOrder(int[] dims) { int n = dims.length - 1; cost = new int[n][n]; order = new int[n][n]; for (int lenMinusOne = 1 ; lenMinusOne < n ; lenMinusOne++) { for (int i = 0; i < n - lenMinusOne; i++) { int j = i + lenMinusOne; cost[i][j] = Integer.MAX_VALUE; for (int k = i; k < j; k++) { int currentCost = cost[i][k] + cost[k+1][j] + dims[i]*dims[k+1]*dims[j+1]; if (currentCost < cost[i][j]) { cost[i][j] = currentCost; order[i][j] = k; } } } } return cost[0][n-1]; } private static String getOptimalParenthesizations() { return getOptimalParenthesizations(order, 0, order.length - 1); } private static String getOptimalParenthesizations(int[][]s, int i, int j) { if (i == j) { return String.format("%c", i+65); } else { StringBuilder sb = new StringBuilder(); sb.append("("); sb.append(getOptimalParenthesizations(s, i, s[i][j])); sb.append(" * "); sb.append(getOptimalParenthesizations(s, s[i][j] + 1, j)); sb.append(")"); return sb.toString(); } } }
592Matrix chain multiplication
9java
y1m6g
var ctx, wid, hei, cols, rows, maze, stack = [], start = {x:-1, y:-1}, end = {x:-1, y:-1}, grid = 8; function drawMaze() { for( var i = 0; i < cols; i++ ) { for( var j = 0; j < rows; j++ ) { switch( maze[i][j] ) { case 0: ctx.fillStyle = "black"; break; case 1: ctx.fillStyle = "green"; break; case 2: ctx.fillStyle = "red"; break; case 3: ctx.fillStyle = "yellow"; break; case 4: ctx.fillStyle = "#500000"; break; } ctx.fillRect( grid * i, grid * j, grid, grid ); } } } function getFNeighbours( sx, sy, a ) { var n = []; if( sx - 1 > 0 && maze[sx - 1][sy] == a ) { n.push( { x:sx - 1, y:sy } ); } if( sx + 1 < cols - 1 && maze[sx + 1][sy] == a ) { n.push( { x:sx + 1, y:sy } ); } if( sy - 1 > 0 && maze[sx][sy - 1] == a ) { n.push( { x:sx, y:sy - 1 } ); } if( sy + 1 < rows - 1 && maze[sx][sy + 1] == a ) { n.push( { x:sx, y:sy + 1 } ); } return n; } function solveMaze() { if( start.x == end.x && start.y == end.y ) { for( var i = 0; i < cols; i++ ) { for( var j = 0; j < rows; j++ ) { switch( maze[i][j] ) { case 2: maze[i][j] = 3; break; case 4: maze[i][j] = 0; break; } } } drawMaze(); return; } var neighbours = getFNeighbours( start.x, start.y, 0 ); if( neighbours.length ) { stack.push( start ); start = neighbours[0]; maze[start.x][start.y] = 2; } else { maze[start.x][start.y] = 4; start = stack.pop(); } drawMaze(); requestAnimationFrame( solveMaze ); } function getCursorPos( event ) { var rect = this.getBoundingClientRect(); var x = Math.floor( ( event.clientX - rect.left ) / grid ), y = Math.floor( ( event.clientY - rect.top ) / grid ); if( maze[x][y] ) return; if( start.x == -1 ) { start = { x: x, y: y }; } else { end = { x: x, y: y }; maze[start.x][start.y] = 2; solveMaze(); } } function getNeighbours( sx, sy, a ) { var n = []; if( sx - 1 > 0 && maze[sx - 1][sy] == a && sx - 2 > 0 && maze[sx - 2][sy] == a ) { n.push( { x:sx - 1, y:sy } ); n.push( { x:sx - 2, y:sy } ); } if( sx + 1 < cols - 1 && maze[sx + 1][sy] == a && sx + 2 < cols - 1 && maze[sx + 2][sy] == a ) { n.push( { x:sx + 1, y:sy } ); n.push( { x:sx + 2, y:sy } ); } if( sy - 1 > 0 && maze[sx][sy - 1] == a && sy - 2 > 0 && maze[sx][sy - 2] == a ) { n.push( { x:sx, y:sy - 1 } ); n.push( { x:sx, y:sy - 2 } ); } if( sy + 1 < rows - 1 && maze[sx][sy + 1] == a && sy + 2 < rows - 1 && maze[sx][sy + 2] == a ) { n.push( { x:sx, y:sy + 1 } ); n.push( { x:sx, y:sy + 2 } ); } return n; } function createArray( c, r ) { var m = new Array( c ); for( var i = 0; i < c; i++ ) { m[i] = new Array( r ); for( var j = 0; j < r; j++ ) { m[i][j] = 1; } } return m; } function createMaze() { var neighbours = getNeighbours( start.x, start.y, 1 ), l; if( neighbours.length < 1 ) { if( stack.length < 1 ) { drawMaze(); stack = []; start.x = start.y = -1; document.getElementById( "canvas" ).addEventListener( "mousedown", getCursorPos, false ); return; } start = stack.pop(); } else { var i = 2 * Math.floor( Math.random() * ( neighbours.length / 2 ) ) l = neighbours[i]; maze[l.x][l.y] = 0; l = neighbours[i + 1]; maze[l.x][l.y] = 0; start = l stack.push( start ) } drawMaze(); requestAnimationFrame( createMaze ); } function createCanvas( w, h ) { var canvas = document.createElement( "canvas" ); wid = w; hei = h; canvas.width = wid; canvas.height = hei; canvas.id = "canvas"; ctx = canvas.getContext( "2d" ); ctx.fillStyle = "black"; ctx.fillRect( 0, 0, wid, hei ); document.body.appendChild( canvas ); } function init() { cols = 73; rows = 53; createCanvas( grid * cols, grid * rows ); maze = createArray( cols, rows ); start.x = Math.floor( Math.random() * ( cols / 2 ) ); start.y = Math.floor( Math.random() * ( rows / 2 ) ); if( !( start.x & 1 ) ) start.x++; if( !( start.y & 1 ) ) start.y++; maze[start.x][start.y] = 0; createMaze(); }
587Maze solving
10javascript
kzwhq
null
592Matrix chain multiplication
11kotlin
fjtdo
package main import ( "fmt" "strconv" "strings" ) const t = ` 55 94 48 95 30 96 77 71 26 67 97 13 76 38 45 07 36 79 16 37 68 48 07 09 18 70 26 06 18 72 79 46 59 79 29 90 20 76 87 11 32 07 07 49 18 27 83 58 35 71 11 25 57 29 85 14 64 36 96 27 11 58 56 92 18 55 02 90 03 60 48 49 41 46 33 36 47 23 92 50 48 02 36 59 42 79 72 20 82 77 42 56 78 38 80 39 75 02 71 66 66 01 03 55 72 44 25 67 84 71 67 11 61 40 57 58 89 40 56 36 85 32 25 85 57 48 84 35 47 62 17 01 01 99 89 52 06 71 28 75 94 48 37 10 23 51 06 48 53 18 74 98 15 27 02 92 23 08 71 76 84 15 52 92 63 81 10 44 10 69 93` func main() { lines := strings.Split(t, "\n") f := strings.Fields(lines[len(lines)-1]) d := make([]int, len(f)) var err error for i, s := range f { if d[i], err = strconv.Atoi(s); err != nil { panic(err) } } d1 := d[1:] var l, r, u int for row := len(lines) - 2; row >= 0; row-- { l = d[0] for i, s := range strings.Fields(lines[row]) { if u, err = strconv.Atoi(s); err != nil { panic(err) } if r = d1[i]; l > r { d[i] = u + l } else { d[i] = u + r } l = r } } fmt.Println(d[0]) }
588Maximum triangle path sum
0go
lx4cw
import hashlib print hashlib.new(,raw_input().encode('utf-16le')).hexdigest().upper()
586MD4
3python
6pv3w
var tileSize = 20;
593Matrix digital rain
10javascript
y1y6r
package main import ( "errors" "flag" "fmt" "log" "math/rand" "strings" "time" ) func main() { log.SetPrefix("mastermind: ") log.SetFlags(0) colours := flag.Int("colours", 6, "number of colours to use (2-20)") flag.IntVar(colours, "colors", 6, "alias for colours") holes := flag.Int("holes", 4, "number of holes (the code length, 4-10)") guesses := flag.Int("guesses", 12, "number of guesses allowed (7-20)") unique := flag.Bool("unique", false, "disallow duplicate colours in the code") flag.Parse() rand.Seed(time.Now().UnixNano()) m, err := NewMastermind(*colours, *holes, *guesses, *unique) if err != nil { log.Fatal(err) } err = m.Play() if err != nil { log.Fatal(err) } } type mastermind struct { colours int holes int guesses int unique bool code string past []string
594Mastermind
0go
ri4gm
null
592Matrix chain multiplication
1lua
thzfn
null
587Maze solving
11kotlin
2qrli
parse = map (map read . words) . lines f x y z = x + max y z g xs ys = zipWith3 f xs ys $ tail ys solve = head . foldr1 g main = readFile "triangle.txt" >>= print . solve . parse
588Maximum triangle path sum
8haskell
1yqps
>>> from itertools import product >>> nuggets = set(range(101)) >>> for s, n, t in product(range(100 nuggets.discard(6*s + 9*n + 20*t) >>> max(nuggets) 43 >>>
585McNuggets problem
3python
d79n1
'''Mayan numerals''' from functools import (reduce) def mayanNumerals(n): '''Rows of Mayan digit cells, representing the integer n. ''' return showIntAtBase(20)( mayanDigit )(n)([]) def mayanDigit(n): '''List of strings representing a Mayan digit.''' if 0 < n: r = n% 5 return [ (['' * r] if 0 < r else []) + ([''] * (n ] else: return [''] def mayanFramed(n): '''Mayan integer in the form of a Wiki table source string. ''' return 'Mayan ' + str(n) + ':\n\n' + ( wikiTable({ 'class': 'wikitable', 'style': cssFromDict({ 'text-align': 'center', 'background-color': ' 'color': ' 'border': '2px solid silver' }), 'colwidth': '3em', 'cell': 'vertical-align: bottom;' })([[ '<br>'.join(col) for col in mayanNumerals(n) ]]) ) def main(): '''Mayan numeral representations of various integers''' print( main.__doc__ + ':\n\n' + '\n'.join(mayanFramed(n) for n in [ 4005, 8017, 326205, 886205, 1081439556, 1000000, 1000000000 ]) ) def wikiTable(opts): '''Source text for wiki-table display of rows of cells, using CSS key-value pairs in the opts dictionary. ''' def colWidth(): return 'width:' + opts['colwidth'] + '; ' if ( 'colwidth' in opts ) else '' def cellStyle(): return opts['cell'] if 'cell' in opts else '' return lambda rows: '{| ' + reduce( lambda a, k: ( a + k + '= ' if ( k in opts ) else a ), ['class', 'style'], '' ) + '\n' + '\n|-\n'.join( '\n'.join( ('|' if ( 0 != i and ('cell' not in opts) ) else ( '|style=|' )) + ( str(x) or ' ' ) for x in row ) for i, row in enumerate(rows) ) + '\n|}\n\n' def cssFromDict(dct): '''CSS string from a dictinary of key-value pairs''' return reduce( lambda a, k: a + k + ':' + dct[k] + '; ', dct.keys(), '' ) def showIntAtBase(base): '''String representation of an integer in a given base, using a supplied function for the string representation of digits. ''' def wrap(toChr, n, rs): def go(nd, r): n, d = nd r_ = toChr(d) + r return go(divmod(n, base), r_) if 0 != n else r_ return 'unsupported base' if 1 >= base else ( 'negative number' if 0 > n else ( go(divmod(n, base), rs)) ) return lambda toChr: lambda n: lambda rs: ( wrap(toChr, n, rs) ) if __name__ == '__main__': main()
589Mayan numerals
3python
2q4lz
int main (int argc, char **argv) { char *str, *s; struct stat statBuf; if (argc != 2) { fprintf (stderr, , basename (argv[0])); exit (1); } s = argv[1]; while ((str = strtok (s, )) != NULL) { if (str != s) { str[-1] = '/'; } if (stat (argv[1], &statBuf) == -1) { mkdir (argv[1], 0); } else { if (! S_ISDIR (statBuf.st_mode)) { fprintf (stderr, , argv[1]); exit (1); } } s = NULL; } return 0; }
595Make directory path
5c
jdg70
class Mastermind { constructor() { this.colorsCnt; this.rptColors; this.codeLen; this.guessCnt; this.guesses; this.code; this.selected; this.game_over; this.clear = (el) => { while (el.hasChildNodes()) { el.removeChild(el.firstChild); } }; this.colors = ["", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "" ]; } newGame() { this.selected = null; this.guessCnt = parseInt(document.getElementById("gssCnt").value); this.colorsCnt = parseInt(document.getElementById("clrCnt").value); this.codeLen = parseInt(document.getElementById("codeLen").value); if (this.codeLen > this.colorsCnt) { document.getElementById("rptClr").selectedIndex = 1; } this.rptColors = document.getElementById("rptClr").value === "yes"; this.guesses = 0; this.game_over = false; const go = document.getElementById("gameover"); go.innerText = ""; go.style.visibility = "hidden"; this.clear(document.getElementById("code")); this.buildPalette(); this.buildPlayField(); } buildPalette() { const pal = document.getElementById("palette"), z = this.colorsCnt / 5, h = Math.floor(z) != z ? Math.floor(z) + 1 : z; this.clear(pal); pal.style.height = `${44 * h + 3 * h}px`; const clrs = []; for (let c = 0; c < this.colorsCnt; c++) { clrs.push(c); const b = document.createElement("div"); b.className = "bucket"; b.clr = c; b.innerText = this.colors[c]; b.addEventListener("click", () => { this.palClick(b); }); pal.appendChild(b); } this.code = []; while (this.code.length < this.codeLen) { const r = Math.floor(Math.random() * clrs.length); this.code.push(clrs[r]); if (!this.rptColors) { clrs.splice(r, 1); } } } buildPlayField() { const brd = document.getElementById("board"); this.clear(brd); const w = 49 * this.codeLen + 7 * this.codeLen + 5; brd.active = 0; brd.style.width = `${w}px`; document.querySelector(".column").style.width = `${w + 20}px`; this.addGuessLine(brd); } addGuessLine(brd) { const z = document.createElement("div"); z.style.clear = "both"; brd.appendChild(z); brd.active += 10; for (let c = 0; c < this.codeLen; c++) { const d = document.createElement("div"); d.className = "bucket"; d.id = `brd${brd.active+ c}`; d.clr = -1; d.addEventListener("click", () => { this.playClick(d); }) brd.appendChild(d); } } palClick(bucket) { if (this.game_over) return; if (null === this.selected) { bucket.classList.add("selected"); this.selected = bucket; return; } if (this.selected !== bucket) { this.selected.classList.remove("selected"); bucket.classList.add("selected"); this.selected = bucket; return; } this.selected.classList.remove("selected"); this.selected = null; } vibrate() { const brd = document.getElementById("board"); let timerCnt = 0; const exp = setInterval(() => { if ((timerCnt++) > 60) { clearInterval(exp); brd.style.top = "0px"; brd.style.left = "0px"; } let x = Math.random() * 4, y = Math.random() * 4; if (Math.random() < .5) x = -x; if (Math.random() < .5) y = -y; brd.style.top = y + "px"; brd.style.left = x + "px"; }, 10); } playClick(bucket) { if (this.game_over) return; if (this.selected) { bucket.innerText = this.selected.innerText; bucket.clr = this.selected.clr; } else { this.vibrate(); } } check() { if (this.game_over) return; let code = []; const brd = document.getElementById("board"); for (let b = 0; b < this.codeLen; b++) { const h = document.getElementById(`brd${brd.active + b}`).clr; if (h < 0) { this.vibrate(); return; } code.push(h); } this.guesses++; if (this.compareCode(code)) { this.gameOver(true); return; } if (this.guesses >= this.guessCnt) { this.gameOver(false); return; } this.addGuessLine(brd); } compareCode(code) { let black = 0, white = 0, b_match = new Array(this.codeLen).fill(false), w_match = new Array(this.codeLen).fill(false); for (let i = 0; i < this.codeLen; i++) { if (code[i] === this.code[i]) { b_match[i] = true; w_match[i] = true; black++; } } for (let i = 0; i < this.codeLen; i++) { if (b_match[i]) continue; for (let j = 0; j < this.codeLen; j++) { if (i == j || w_match[j]) continue; if (code[i] === this.code[j]) { w_match[j] = true; white++; break; } } } const brd = document.getElementById("board"); let d; for (let i = 0; i < black; i++) { d = document.createElement("div"); d.className = "pin"; d.style.backgroundColor = "#a00"; brd.appendChild(d); } for (let i = 0; i < white; i++) { d = document.createElement("div"); d.className = "pin"; d.style.backgroundColor = "#eee"; brd.appendChild(d); } return (black == this.codeLen); } gameOver(win) { if (this.game_over) return; this.game_over = true; const cd = document.getElementById("code"); for (let c = 0; c < this.codeLen; c++) { const d = document.createElement("div"); d.className = "bucket"; d.innerText = this.colors[this.code[c]]; cd.appendChild(d); } const go = document.getElementById("gameover"); go.style.visibility = "visible"; go.innerText = win ? "GREAT!" : "YOU FAILED!"; const i = setInterval(() => { go.style.visibility = "hidden"; clearInterval(i); }, 3000); } } const mm = new Mastermind(); document.getElementById("newGame").addEventListener("click", () => { mm.newGame() }); document.getElementById("giveUp").addEventListener("click", () => { mm.gameOver(); }); document.getElementById("check").addEventListener("click", () => { mm.check() });
594Mastermind
10javascript
s2xqz
allInputs <- expand.grid(x = 0:(100 %/% 6), y = 0:(100 %/% 9), z = 0:(100 %/% 20)) mcNuggets <- do.call(function(x, y, z) 6 * x + 9 * y + 20 * z, allInputs)
585McNuggets problem
13r
8530x
(defn mkdirp [path] (let [dir (java.io.File. path)] (if (.exists dir) true (.mkdirs dir))))
595Make directory path
6clojure
16kpy
static unsigned char const k8[16] = { 14, 4, 13, 1, 2, 15, 11, 8, 3, 10, 6, 12, 5, 9, 0, 7 }; static unsigned char const k7[16] = { 15, 1, 8, 14, 6, 11, 3, 4, 9, 7, 2, 13, 12, 0, 5, 10 }; static unsigned char const k6[16] = { 10, 0, 9, 14, 6, 3, 15, 5, 1, 13, 12, 7, 11, 4, 2, 8 }; static unsigned char const k5[16] = { 7, 13, 14, 3, 0, 6, 9, 10, 1, 2, 8, 5, 11, 12, 4, 15 }; static unsigned char const k4[16] = { 2, 12, 4, 1, 7, 10, 11, 6, 8, 5, 3, 15, 13, 0, 14, 9 }; static unsigned char const k3[16] = { 12, 1, 10, 15, 9, 2, 6, 8, 0, 13, 3, 4, 14, 7, 5, 11 }; static unsigned char const k2[16] = { 4, 11, 2, 14, 15, 0, 8, 13, 3, 12, 9, 7, 5, 10, 6, 1 }; static unsigned char const k1[16] = { 13, 2, 8, 4, 6, 15, 11, 1, 10, 9, 3, 14, 5, 0, 12, 7 }; static unsigned char k87[256]; static unsigned char k65[256]; static unsigned char k43[256]; static unsigned char k21[256]; void kboxinit(void) { int i; for (i = 0; i < 256; i++) { k87[i] = k8[i >> 4] << 4 | k7[i & 15]; k65[i] = k6[i >> 4] << 4 | k5[i & 15]; k43[i] = k4[i >> 4] << 4 | k3[i & 15]; k21[i] = k2[i >> 4] << 4 | k1[i & 15]; } } static word32 f(word32 x) { x = k87[x>>24 & 255] << 24 | k65[x>>16 & 255] << 16 | k43[x>> 8 & 255] << 8 | k21[x & 255]; return x<<11 | x>>(32-11); }
596Main step of GOST 28147-89
5c
ayk11
wchar_t glyph[] = LSPCSPC; typedef unsigned char byte; enum { N = 1, S = 2, W = 4, E = 8, V = 16 }; byte **cell; int w, h, avail; int irand(int n) { int r, rmax = n * (RAND_MAX / n); while ((r = rand()) >= rmax); return r / (RAND_MAX/n); } void show() { int i, j, c; each(i, 0, 2 * h) { each(j, 0, 2 * w) { c = cell[i][j]; if (c > V) printf(); printf(, glyph[c]); if (c > V) printf(); } putchar('\n'); } } inline int max(int a, int b) { return a >= b ? a : b; } inline int min(int a, int b) { return b >= a ? a : b; } static int dirs[4][2] = {{-2, 0}, {0, 2}, {2, 0}, {0, -2}}; void walk(int x, int y) { int i, t, x1, y1, d[4] = { 0, 1, 2, 3 }; cell[y][x] |= V; avail--; for (x1 = 3; x1; x1--) if (x1 != (y1 = irand(x1 + 1))) i = d[x1], d[x1] = d[y1], d[y1] = i; for (i = 0; avail && i < 4; i++) { x1 = x + dirs[ d[i] ][0], y1 = y + dirs[ d[i] ][1]; if (cell[y1][x1] & V) continue; if (x1 == x) { t = (y + y1) / 2; cell[t][x+1] &= ~W, cell[t][x] &= ~(E|W), cell[t][x-1] &= ~E; } else if (y1 == y) { t = (x + x1)/2; cell[y-1][t] &= ~S, cell[y][t] &= ~(N|S), cell[y+1][t] &= ~N; } walk(x1, y1); } } int solve(int x, int y, int tox, int toy) { int i, t, x1, y1; cell[y][x] |= V; if (x == tox && y == toy) return 1; each(i, 0, 3) { x1 = x + dirs[i][0], y1 = y + dirs[i][1]; if (cell[y1][x1]) continue; if (x1 == x) { t = (y + y1)/2; if (cell[t][x] || !solve(x1, y1, tox, toy)) continue; cell[t-1][x] |= S, cell[t][x] |= V|N|S, cell[t+1][x] |= N; } else if (y1 == y) { t = (x + x1)/2; if (cell[y][t] || !solve(x1, y1, tox, toy)) continue; cell[y][t-1] |= E, cell[y][t] |= V|E|W, cell[y][t+1] |= W; } return 1; } cell[y][x] &= ~V; return 0; } void make_maze() { int i, j; int h2 = 2 * h + 2, w2 = 2 * w + 2; byte **p; p = calloc(sizeof(byte*) * (h2 + 2) + w2 * h2 + 1, 1); p[1] = (byte*)(p + h2 + 2) + 1; each(i, 2, h2) p[i] = p[i-1] + w2; p[0] = p[h2]; cell = &p[1]; each(i, -1, 2 * h + 1) cell[i][-1] = cell[i][w2 - 1] = V; each(j, 0, 2 * w) cell[-1][j] = cell[h2 - 1][j] = V; each(i, 0, h) each(j, 0, 2 * w) cell[2*i][j] |= E|W; each(i, 0, 2 * h) each(j, 0, w) cell[i][2*j] |= N|S; each(j, 0, 2 * w) cell[0][j] &= ~N, cell[2*h][j] &= ~S; each(i, 0, 2 * h) cell[i][0] &= ~W, cell[i][2*w] &= ~E; avail = w * h; walk(irand(2) * 2 + 1, irand(h) * 2 + 1); each(i, 0, 2 * h) each(j, 0, 2 * w) cell[i][j] &= ~V; solve(1, 1, 2 * w - 1, 2 * h - 1); show(); } int main(int c, char **v) { setlocale(LC_ALL, ); if (c < 2 || (w = atoi(v[1])) <= 0) w = 16; if (c < 3 || (h = atoi(v[2])) <= 0) h = 8; make_maze(); return 0; }
597Maze generation
5c
i4qo2
package main import "fmt" type vector = []float64 type matrix []vector func (m1 matrix) mul(m2 matrix) matrix { rows1, cols1 := len(m1), len(m1[0]) rows2, cols2 := len(m2), len(m2[0]) if cols1 != rows2 { panic("Matrices cannot be multiplied.") } result := make(matrix, rows1) for i := 0; i < rows1; i++ { result[i] = make(vector, cols2) for j := 0; j < cols2; j++ { for k := 0; k < rows2; k++ { result[i][j] += m1[i][k] * m2[k][j] } } } return result } func identityMatrix(n int) matrix { if n < 1 { panic("Size of identity matrix can't be less than 1") } ident := make(matrix, n) for i := 0; i < n; i++ { ident[i] = make(vector, n) ident[i][i] = 1 } return ident } func (m matrix) pow(n int) matrix { le := len(m) if le != len(m[0]) { panic("Not a square matrix") } switch { case n < 0: panic("Negative exponents not supported") case n == 0: return identityMatrix(le) case n == 1: return m } pow := identityMatrix(le) base := m e := n for e > 0 { if (e & 1) == 1 { pow = pow.mul(base) } e >>= 1 base = base.mul(base) } return pow } func main() { m := matrix{{3, 2}, {2, 1}} for i := 0; i <= 10; i++ { fmt.Println("** Power of", i, "**") fmt.Println(m.pow(i)) fmt.Println() } }
591Matrix-exponentiation operator
0go
0uosk
null
594Mastermind
11kotlin
hf7j3
use strict; use feature 'say'; sub matrix_mult_chaining { my(@dimensions) = @_; my(@cp,@path); $cp[$_][$_] = 0 for keys @dimensions; my $n = $ for my $chain_length (1..$n) { for my $start (0 .. $n - $chain_length - 1) { my $end = $start + $chain_length; $cp[$end][$start] = 10e10; for my $step ($start .. $end - 1) { my $new_cost = $cp[$step][$start] + $cp[$end][$step + 1] + $dimensions[$start] * $dimensions[$step+1] * $dimensions[$end+1]; if ($new_cost < $cp[$end][$start]) { $cp[$end][$start] = $new_cost; $cp[$start][$end] = $step; } } } } $cp[$n-1][0] . ' ' . find_path(0, $n-1, @cp); } sub find_path { my($start,$end,@cp) = @_; my $result; if ($start == $end) { $result .= 'A' . ($start + 1); } else { $result .= '(' . find_path($start, $cp[$start][$end], @cp) . find_path($cp[$start][$end] + 1, $end, @cp) . ')'; } return $result; } say matrix_mult_chaining(<1 5 25 30 100 70 2 1 100 250 1 1000 2>); say matrix_mult_chaining(<1000 1 500 12 1 700 2500 3 2 5 14 10>);
592Matrix chain multiplication
2perl
htkjl
import java.nio.file.*; import static java.util.Arrays.stream; public class MaxPathSum { public static void main(String[] args) throws Exception { int[][] data = Files.lines(Paths.get("triangle.txt")) .map(s -> stream(s.trim().split("\\s+")) .mapToInt(Integer::parseInt) .toArray()) .toArray(int[][]::new); for (int r = data.length - 1; r > 0; r--) for (int c = 0; c < data[r].length - 1; c++) data[r - 1][c] += Math.max(data[r][c], data[r][c + 1]); System.out.println(data[0][0]); } }
588Maximum triangle path sum
9java
7dprj
require 'openssl' puts OpenSSL::Digest::MD4.hexdigest('Rosetta Code')
586MD4
14ruby
ma5yj
numbers = ARGV.map(&:to_i) if numbers.length == 0 puts puts() exit end def maya_print(number) digits5s1s = number.to_s(20).chars.map { |ch| ch.to_i(20) }.map { |dig| dig.divmod(5) } puts(('+----' * digits5s1s.length) + '+') 3.downto(0) do |row| digits5s1s.each do |d5s1s| if row < d5s1s[0] print('|----') elsif row == d5s1s[0] print() else print('| ') end end puts('|') end puts(('+----' * digits5s1s.length) + '+') end numbers.each do |num| puts(num) maya_print(num) end
589Mayan numerals
14ruby
u0rvz
typedef int bool; typedef unsigned long long ull; bool is_prime(ull n) { ull d; if (n < 2) return FALSE; if (!(n % 2)) return n == 2; if (!(n % 3)) return n == 3; d = 5; while (d * d <= n) { if (!(n % d)) return FALSE; d += 2; if (!(n % d)) return FALSE; d += 4; } return TRUE; } void ord(char *res, int n) { char suffix[3]; int m = n % 100; if (m >= 4 && m <= 20) { sprintf(res,, n); return; } switch(m % 10) { case 1: strcpy(suffix, ); break; case 2: strcpy(suffix, ); break; case 3: strcpy(suffix, ); break; default: strcpy(suffix, ); break; } sprintf(res, , n, suffix); } bool is_magnanimous(ull n) { ull p, q, r; if (n < 10) return TRUE; for (p = 10; ; p *= 10) { q = n / p; r = n % p; if (!is_prime(q + r)) return FALSE; if (q < 10) break; } return TRUE; } void list_mags(int from, int thru, int digs, int per_line) { ull i = 0; int c = 0; char res1[13], res2[13]; if (from < 2) { printf(, thru); } else { ord(res1, from); ord(res2, thru); printf(, res1, res2); } for ( ; c < thru; ++i) { if (is_magnanimous(i)) { if (++c >= from) { printf(, digs, i); if (!(c % per_line)) printf(); } } } } int main() { list_mags(1, 45, 3, 15); list_mags(241, 250, 1, 10); list_mags(391, 400, 1, 10); return 0; }
598Magnanimous numbers
5c
vqy2o
import Data.List (transpose) (<+>) :: Num a => [a] -> [a] -> [a] (<+>) = zipWith (+) (<*>) :: Num a => [a] -> [a] -> a (<*>) = (sum .) . zipWith (*) newtype Mat a = Mat [[a]] deriving (Eq, Show) instance Num a => Num (Mat a) where negate (Mat x) = Mat $ map (map negate) x Mat x + Mat y = Mat $ zipWith (<+>) x y Mat x * Mat y = Mat [ [ xs Main.<*> ys | ys <- transpose y ] | xs <- x ] abs = undefined fromInteger _ = undefined signum = undefined main :: IO () main = print $ Mat [[1, 2], [0, 1]] ^ 4
591Matrix-exponentiation operator
8haskell
cw294
math.randomseed( os.time() ) local black, white, none, code = "X", "O", "-" local colors, codeLen, maxGuess, rept, alpha, opt = 6, 4, 10, false, "ABCDEFGHIJKLMNOPQRST", "" local guesses, results function createCode() code = "" local dic, a = "" for i = 1, colors do dic = dic .. alpha:sub( i, i ) end for i = 1, codeLen do a = math.floor( math.random( 1, #dic ) ) code = code .. dic:sub( a, a ) if not rept then dic = dic:sub(1, a - 1 ) .. dic:sub( a + 1, #dic ) end end end function checkInput( inp ) table.insert( guesses, inp ) local b, w, fnd, str = 0, 0, {}, "" for bl = 1, codeLen do if inp:sub( bl, bl ) == code:sub( bl, bl ) then b = b + 1; fnd[bl] = true else for wh = 1, codeLen do if nil == fnd[bl] and wh ~= bl and inp:sub( wh, wh ) == code:sub( bl, bl ) then w = w + 1; fnd[bl] = true end end end end for i = 1, b do str = str .. string.format( "%s ", black ) end for i = 1, w do str = str .. string.format( "%s ", white ) end for i = 1, 2 * codeLen - #str, 2 do str = str .. string.format( "%s ", none ) end table.insert( results, str ) return b == codeLen end function play() local err, win, r = true, false; for j = 1, colors do opt = opt .. alpha:sub( j, j ) end while( true ) do createCode(); guesses, results = {}, {} for i = 1, maxGuess do err = true; while( err ) do io.write( string.format( "\n
594Mastermind
1lua
ktjh2
use strict; use warnings; my ($width, $height) = @ARGV; $_ ||= 10 for $width, $height; my %visited; my $h_barrier = "+" . ("--+" x $width) . "\n"; my $v_barrier = "|" . (" |" x $width) . "\n"; my @output = ($h_barrier, $v_barrier) x $height; push @output, $h_barrier; my @dx = qw(-1 1 0 0); my @dy = qw(0 0 -1 1); sub visit { my ($x, $y) = @_; $visited{$x, $y} = 1; my $rand = int rand 4; for my $n ( $rand .. 3, 0 .. $rand-1 ) { my ($xx, $yy) = ($x + $dx[$n], $y + $dy[$n]); next if $visited{ $xx, $yy }; next if $xx < 0 or $xx >= $width; next if $yy < 0 or $yy >= $height; my $row = $y * 2 + 1 + $dy[$n]; my $col = $x * 3 + 1 + $dx[$n]; substr( $output[$row], $col, 2, ' ' ); no warnings 'recursion'; visit( $xx, $yy ); } } visit( int rand $width, int rand $height ); print "Here is the maze:\n"; print @output; %visited = (); my @d = ('>>', '<<', 'vv', '^^'); sub solve { my ($x, $y) = @_; return 1 if $x == 0 and $y == 0; $visited{ $x, $y } = 1; my $rand = int rand 4; for my $n ( $rand .. 3, 0 .. $rand-1 ) { my ($xx, $yy) = ($x + $dx[$n], $y + $dy[$n]); next if $visited{ $xx, $yy }; next if $xx < 0 or $xx >= $width; next if $yy < 0 or $yy >= $height; my $row = $y * 2 + 1 + $dy[$n]; my $col = $x * 3 + 1 + $dx[$n]; my $b = substr( $output[$row], $col, 2 ); next if " " ne $b; no warnings 'recursion'; next if not solve( $xx, $yy ); substr( $output[$row], $col, 2, $d[$n] ); substr( $output[$row-$dy[$n]], $col-$dx[$n], 2, $d[$n] ); return 1; } 0; } if( solve( $width-1, $height-1 ) ) { print "Here is the solution:\n"; substr( $output[1], 1, 2, '**' ); print @output; } else { print "Could not solve!\n"; }
587Maze solving
2perl
svdq3
var arr = [ [55], [94, 48], [95, 30, 96], [77, 71, 26, 67], [97, 13, 76, 38, 45], [07, 36, 79, 16, 37, 68], [48, 07, 09, 18, 70, 26, 06], [18, 72, 79, 46, 59, 79, 29, 90], [20, 76, 87, 11, 32, 07, 07, 49, 18], [27, 83, 58, 35, 71, 11, 25, 57, 29, 85], [14, 64, 36, 96, 27, 11, 58, 56, 92, 18, 55], [02, 90, 03, 60, 48, 49, 41, 46, 33, 36, 47, 23], [92, 50, 48, 02, 36, 59, 42, 79, 72, 20, 82, 77, 42], [56, 78, 38, 80, 39, 75, 02, 71, 66, 66, 01, 03, 55, 72], [44, 25, 67, 84, 71, 67, 11, 61, 40, 57, 58, 89, 40, 56, 36], [85, 32, 25, 85, 57, 48, 84, 35, 47, 62, 17, 01, 01, 99, 89, 52], [06, 71, 28, 75, 94, 48, 37, 10, 23, 51, 06, 48, 53, 18, 74, 98, 15], [27, 02, 92, 23, 08, 71, 76, 84, 15, 52, 92, 63, 81, 10, 44, 10, 69, 93] ]; while (arr.length !== 1) { var len = arr.length; var row = []; var current = arr[len-2]; var currentLen = current.length - 1; var end = arr[len-1]; for ( var i = 0; i <= currentLen; i++ ) { row.push(Math.max(current[i] + end[i] || 0, current[i] + end[i+1] || 0) ) } arr.pop(); arr.pop(); arr.push(row); } console.log(arr);
588Maximum triangle path sum
10javascript
p6xb7
null
586MD4
15rust
9e4mm
const ONE: &str = ""; const FIVE: &str = ""; const ZERO: &str = ""; fn main() { println!("{}", mayan(4005)); println!("{}", mayan(8017)); println!("{}", mayan(326_205)); println!("{}", mayan(886_205)); println!("{}", mayan(69)); println!("{}", mayan(420)); println!("{}", mayan(1_063_715_456)); } fn mayan(dec: i64) -> String { let mut digits = vec![]; let mut num = dec; while num > 0 { digits.push(num% 20); num /= 20; } digits = digits.into_iter().rev().collect(); let mut boxes = vec!["".to_string(); 6]; let n = digits.len(); for (i, digit) in digits.iter().enumerate() { if i == 0 { boxes[0] = "".to_string(); if i == n - 1 { boxes[0] += ""; } } else if i == n - 1 { boxes[0] += ""; } else { boxes[0] += ""; } for j in 1..5 { boxes[j] += ""; let elem = 0.max(digit - (4 - j as i64) * 5); if elem >= 5 { boxes[j] += &format!("{: ^4}", FIVE); } else if elem > 0 { boxes[j] += &format!("{: ^4}", ONE.repeat(elem as usize% 15)); } else if j == 4 { boxes[j] += &format!("{: ^4}", ZERO); } else { boxes[j] += &" "; } if i == n - 1 { boxes[j] += ""; } } if i == 0 { boxes[5] = "".to_string(); if i == n - 1 { boxes[5] += ""; } } else if i == n - 1 { boxes[5] += ""; } else { boxes[5] += ""; } } let mut mayan = format!("Mayan {}:\n", dec); for b in boxes { mayan += &(b + "\n"); } mayan }
589Mayan numerals
15rust
587uq
null
591Matrix-exponentiation operator
10javascript
9elml
use strict; use warnings; use Tk; my $delay = 50; my $fade = 8; my $base_color = ' my $fontname = 'Times'; my $fontsize = 12; my $font = "{$fontname} $fontsize bold"; my @objects; my ( $xv, $yv ) = ( 0, 0 ); my $top = MainWindow->new(); $top->geometry('800x600'); my $run = 1; $top->protocol( 'WM_DELETE_WINDOW' => sub { $run = 0; } ); my @letters = ( 'A' .. 'Z', 'a' .. 'z', '0' .. '9' ); my $canvas = $top->Canvas( -background => 'black' )->pack( -fill => 'both', -expand => 'y' ); my $testch = $canvas->createText( 100, 100, -text => 'o', -fill => 'black', -font => $font ); $top->update; my @coords = $canvas->bbox($testch); $canvas->delete($testch); my $lwidth = $coords[2] - $coords[0]; my $lheight = ( $coords[3] - $coords[1] ) * .8; my $cols = int $canvas->width / $lwidth; my $rows = int $canvas->height / $lheight; for my $y ( 0 .. $rows ) { for my $x ( 0 .. $cols ) { $objects[$x][$y] = $canvas->createText( $x * $lwidth, $y * $lheight, -text => $letters[ int rand @letters ], -fill => $base_color, -font => $font ); } } my $neo_image = $top->Photo( -data => neo() ); my $neo = $canvas->createImage( $canvas->width / 2, $canvas->height / 2, -image => $neo_image ); while ($run) { drop('Nothing Like The Matrix'); } exit; MainLoop; sub drop { my @phrase = split //, reverse shift; my $x = int rand $cols; my @orig; for my $y ( 0 .. $rows ) { $orig[$y] = $canvas->itemcget( $objects[$x][$y], '-text' ); } for my $y ( 0 .. $rows + @phrase + $fade ) { for my $letter ( 0 .. @phrase ) { last if ( $y - $letter < 0 ); $canvas->itemconfigure( $objects[$x][ $y - $letter ], -text => $phrase[$letter], -fill => " ); } if ( $y > @phrase ) { $canvas->itemconfigure( $objects[$x][ $y - @phrase ], -text => $orig[ $y - @phrase ], -fill => " ); } if ( $y > @phrase + 2 ) { $canvas->itemconfigure( $objects[$x][ $y - @phrase - int ($fade / 2) ], -fill => " $canvas->itemconfigure( $objects[$x][ $y - @phrase - $fade + 1 ], -fill => $base_color ); } last unless $run; $top->after($delay); neo_move(); $top->update; } } sub neo_move { $xv += ( ( rand 2 ) - 1 > 0 ) ? 1 : -1; $yv += ( ( rand 2 ) - 1 > 0 ) ? 1 : -1; my ( $x, $y ) = $canvas->coords($neo); $xv = -$xv if ( ( $x < 0 ) or ( $x > $canvas->width ) ); $yv = -$yv if ( ( $y < 0 ) or ( $y > $canvas->height ) ); $canvas->move( $neo, $xv, $yv ); } sub neo { return ' R0lGODlhjAC1APcAAAQDBISCZEJDM8nDq6eihGJjSyQjFOzj0oSEhGRlZCktLKKkpEhNTMHFxBES BFBSNDMyJJSSbOru7HFyVGt0aqm1q5OVhMnTy2RELLmzmy0UEUQiDMa1pZSEbCo4MrSVhIh0Z9jO tLSljNPV1IhkSPjy3D9EPCYDBB4VHJGVlCIjHGxKTOrl3GFkVLnCuUU5LQsLCXmDesq9tk9XTBEa FOXVxSEqImRUQvv37HF1dJOahZmkmOzq3Km6tMe8qEJLQJhyVIZ9Z9bFtJeEeLamlG5sVFEzIUAp LKSUfGBeXN/FxBIUFHN7XF9FPiwcDD0kITc9PF5ZTk1LNFlbQ3p9ZYqMdXhqZOna1C4lHREOFOXb xLesl/z6/JeNdj47JJqafLy7pZ+Vhjs+MKurlYl8dBUEBa2chNrQvBUNC9e8qkAsHIqLbGtrTH10 W8O6m1Q+PPXs301EMpyMhMGtpFhURNzbykU+MVBMPS8dHPTq1B4UDD0zI4qTfDo4LU5FPJKclvTm 3G1dTYFjVHhcXIOMhlprZKqrpFxMNJWLbEw+JF1NPqSbfGBQTKyri8XMxEQsFNbb1CYMBB8dHGRa PHR9dD8xLNvNxH1tWbCelOXQvG5lVUgcEIhcTM/KrDAqF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l
4o45d
def parens(n): def aux(n, k): if n == 1: yield k elif n == 2: yield [k, k + 1] else: a = [] for i in range(1, n): for u in aux(i, k): for v in aux(n - i, k + i): yield [u, v] yield from aux(n, 0)
592Matrix chain multiplication
3python
kzbhf
aux <- function(i, j, u) { k <- u[[i, j]] if (k < 0) { i } else { paste0("(", Recall(i, k, u), "*", Recall(i + k, j - k, u), ")") } } chain.mul <- function(a) { n <- length(a) - 1 u <- matrix(0, n, n) v <- matrix(0, n, n) u[, 1] <- -1 for (j in seq(2, n)) { for (i in seq(n - j + 1)) { v[[i, j]] <- Inf for (k in seq(j - 1)) { s <- v[[i, k]] + v[[i + k, j - k]] + a[[i]] * a[[i + k]] * a[[i + j]] if (s < v[[i, j]]) { u[[i, j]] <- k v[[i, j]] <- s } } } } list(cost = v[[1, n]], solution = aux(1, n, u)) } chain.mul(c(5, 6, 3, 1)) chain.mul(c(1, 5, 25, 30, 100, 70, 2, 1, 100, 250, 1, 1000, 2)) chain.mul(c(1000, 1, 500, 12, 1, 700, 2500, 3, 2, 5, 14, 10))
592Matrix chain multiplication
13r
rn7gj
import org.bouncycastle.crypto.digests.MD4Digest object RosettaRIPEMD160 extends App { val (raw, messageDigest) = ("Rosetta Code".getBytes("US-ASCII"), new MD4Digest()) messageDigest.update(raw, 0, raw.length) val out = Array.fill[Byte](messageDigest.getDigestSize())(0) messageDigest.doFinal(out, 0) assert(out.map("%02x".format(_)).mkString == "a52bcfc6a0d0d300cdc5ddbfbefe478b") import scala.compat.Platform.currentTime println(s"Successfully completed without errors. [total ${currentTime - executionStart} ms]") }
586MD4
16scala
2q7lb
def mcnugget(limit) sv = (0..limit).to_a (0..limit).step(6) do |s| (0..limit).step(9) do |n| (0..limit).step(20) do |t| sv.delete(s + n + t) end end end sv.max end puts(mcnugget 100)
585McNuggets problem
14ruby
thlf2
os.MkdirAll("/tmp/some/path/to/dir", 0770)
595Make directory path
0go
f7id0
typedef struct arg { int (*fn)(struct arg*); int *k; struct arg *x1, *x2, *x3, *x4, *x5; } ARG; int f_1 (ARG* _) { return -1; } int f0 (ARG* _) { return 0; } int f1 (ARG* _) { return 1; } int eval(ARG* a) { return a->fn(a); } int A(ARG*); int B(ARG* a) { int k = *a->k -= 1; return A(FUN(a, a->x1, a->x2, a->x3, a->x4)); } int A(ARG* a) { return *a->k <= 0 ? eval(a->x4) + eval(a->x5) : B(a); } int main(int argc, char **argv) { int k = argc == 2 ? strtol(argv[1], 0, 0) : 10; printf(, A(FUN(MAKE_ARG(f1), MAKE_ARG(f_1), MAKE_ARG(f_1), MAKE_ARG(f1), MAKE_ARG(f0)))); return 0; }
599Man or boy test
5c
9afm1
(ns maze.core (:require [clojure.set:refer [intersection select]] [clojure.string:as str])) (defn neighborhood ([] (neighborhood [0 0])) ([coord] (neighborhood coord 1)) ([[y x] r] (let [y-- (- y r) y++ (+ y r) x-- (- x r) x++ (+ x r)] #{[y++ x] [y-- x] [y x--] [y x++]}))) (defn cell-empty? [maze coords] (=:empty (get-in maze coords))) (defn wall? [maze coords] (=:wall (get-in maze coords))) (defn filter-maze ([pred maze coords] (select (partial pred maze) (set coords))) ([pred maze] (filter-maze pred maze (for [y (range (count maze)) x (range (count (nth maze y)))] [y x])))) (defn create-empty-maze [width height] (let [width (inc (* 2 width)) height (inc (* 2 height))] (vec (take height (interleave (repeat (vec (take width (repeat:wall)))) (repeat (vec (take width (cycle [:wall:empty]))))))))) (defn next-step [possible-steps] (rand-nth (vec possible-steps))) (defn create-random-maze [width height] (loop [maze (create-empty-maze width height) stack [] nonvisited (filter-maze cell-empty? maze) visited #{} coords (next-step nonvisited)] (if (empty? nonvisited) maze (let [nonvisited-neighbors (intersection (neighborhood coords 2) nonvisited)] (cond (seq nonvisited-neighbors) (let [next-coords (next-step nonvisited-neighbors) wall-coords (map #(+ %1 (/ (- %2 %1) 2)) coords next-coords)] (recur (assoc-in maze wall-coords:empty) (conj stack coords) (disj nonvisited next-coords) (conj visited next-coords) next-coords)) (seq stack) (recur maze (pop stack) nonvisited visited (last stack))))))) (def cell-code->str [" " " " " " " " " " " " " " " " " " " " " " " " "" "" "" "" " " " " " " " " " " " " " " " " " " " " " " " " "" "" "" ""]) (defn cell-code [maze coord] (transduce (comp (map (partial wall? maze)) (keep-indexed (fn [idx el] (when el idx))) (map (partial bit-shift-left 1))) (completing bit-or) 0 (sort (cons coord (neighborhood coord))))) (defn cell->str [maze coord] (get cell-code->str (cell-code maze coord))) (defn maze->str [maze] (->> (for [y (range (count maze))] (for [x (range (count (nth maze y)))] (cell->str maze [y x]))) (map str/join) (str/join \newline))) (println (maze->str (create-random-maze 10 10)))
597Maze generation
6clojure
zhitj
use List::Util qw(any); print 'Enter pool size, puzzle size, attempts allowed: '; ($pool,$length,$tries) = split /\s+/, <>; $length = 4 if $length eq '' or $length < 3 or $length > 11; $pool = 6 if $pool eq '' or $pool < 2 or $pool > 21; $tries = 10 if $tries eq '' or $tries < 7 or $tries > 21; @valid = sort { -1 + 2*int(rand 2) } ('A' .. 'T')[0..$pool-1]; @puzzle = @valid[0..$length-1]; $black = ''; $white = ''; while () { header(); print "$_\n" for @guesses; lose() if @guesses == $tries; @guess = get_guess(); next unless is_valid(@guess); $score = score(\@puzzle, \@guess); win() if $score eq join ' ', ($black) x $length; push @guesses, join(' ', @guess) . ':: ' . $score; } sub score { local *puzzle = shift; local *guess = shift; my @score; for $i (0..$length-1) { if ( $puzzle[$i] eq $guess[$i]) { push @score, $black } elsif (any {$puzzle[$i] eq $_} @guess) { push @score, $white } else { push @score, '-' } } join ' ', reverse sort @score; } sub header { $num = $tries - @guesses; print "Valid letter, but wrong position: - Correct letter and position: \n"; print "Guess the $length element sequence containing the letters " . join(', ', sort @valid) . "\n"; printf "Repeats are not allowed. You have $num guess%s remaining\n", $num > 1 ? 'es' : ''; } sub get_guess { print 'Your guess?: '; $g = <>; return split /\s*/, uc $g } sub is_valid { $length == @_ } sub win { print 'You win! The correct answer is: ' . join(' ',@puzzle) . "\n"; exit } sub lose { print 'Too bad, you ran out of guesses. The solution was: ' . join(' ',@puzzle) . "\n"; exit }
594Mastermind
2perl
zhftb
fn main() { let test_cases = vec![ [6, 9, 20], [12, 14, 17], [12, 13, 34], [5, 9, 21], [10, 18, 21], [71, 98, 99], [7_074_047, 8_214_596, 9_098_139], [582_795_988, 1_753_241_221, 6_814_151_015], [4, 30, 16], [12, 12, 13], [6, 15, 1], ]; for case in &test_cases { print!("g({}, {}, {}) = ", case[0], case[1], case[2]); println!( "{}", match frobenius(case.to_vec()) { Ok(g) => format!("{}", g), Err(e) => e, } ); } } fn frobenius(unsorted_a: Vec<i64>) -> Result<i64, String> { let mut a = unsorted_a; a.sort(); assert!(a[0] >= 1); if gcd(gcd(a[0], a[1]), a[2]) > 1 { return Err("Undefined".to_string()); } let d12 = gcd(a[0], a[1]); let d13 = gcd(a[0] / d12, a[2]); let d23 = gcd(a[1] / d12, a[2] / d13); let mut a_prime = vec![a[0] / d12 / d13, a[1] / d12 / d23, a[2] / d13 / d23]; a_prime.sort(); let rod = if a_prime[0] == 1 { -1 } else {
585McNuggets problem
15rust
zk2to
func maxNugget(limit: Int) -> Int { var (max, sixes, nines, twenties, i) = (0, 0, 0, 0, 0) mainLoop: while i < limit { sixes = 0 while sixes * 6 < i { if sixes * 6 == i { i += 1 continue mainLoop } nines = 0 while nines * 9 < i { if sixes * 6 + nines * 9 == i { i += 1 continue mainLoop } twenties = 0 while twenties * 20 < i { if sixes * 6 + nines * 9 + twenties * 20 == i { i += 1 continue mainLoop } twenties += 1 } nines += 1 } sixes += 1 } max = i i += 1 } return max } print(maxNugget(limit: 100))
585McNuggets problem
17swift
fjcdk
int** oddMagicSquare(int n) { if (n < 3 || n % 2 == 0) return NULL; int value = 0; int squareSize = n * n; int c = n / 2, r = 0,i; int** result = (int**)malloc(n*sizeof(int*)); for(i=0;i<n;i++) result[i] = (int*)malloc(n*sizeof(int)); while (++value <= squareSize) { result[r][c] = value; if (r == 0) { if (c == n - 1) { r++; } else { r = n - 1; c++; } } else if (c == n - 1) { r--; c = 0; } else if (result[r - 1][c + 1] == 0) { r--; c++; } else { r++; } } return result; } int** singlyEvenMagicSquare(int n) { if (n < 6 || (n - 2) % 4 != 0) return NULL; int size = n * n; int halfN = n / 2; int subGridSize = size / 4, i; int** subGrid = oddMagicSquare(halfN); int gridFactors[] = {0, 2, 3, 1}; int** result = (int**)malloc(n*sizeof(int*)); for(i=0;i<n;i++) result[i] = (int*)malloc(n*sizeof(int)); for (int r = 0; r < n; r++) { for (int c = 0; c < n; c++) { int grid = (r / halfN) * 2 + (c / halfN); result[r][c] = subGrid[r % halfN][c % halfN]; result[r][c] += gridFactors[grid] * subGridSize; } } int nColsLeft = halfN / 2; int nColsRight = nColsLeft - 1; for (int r = 0; r < halfN; r++) for (int c = 0; c < n; c++) { if (c < nColsLeft || c >= n - nColsRight || (c == nColsLeft && r == nColsLeft)) { if (c == 0 && r == nColsLeft) continue; int tmp = result[r][c]; result[r][c] = result[r + halfN][c]; result[r + halfN][c] = tmp; } } return result; } int numDigits(int n){ int count = 1; while(n>=10){ n /= 10; count++; } return count; } void printMagicSquare(int** square,int rows){ int i,j; for(i=0;i<rows;i++){ for(j=0;j<rows;j++){ printf(,rows - numDigits(square[i][j]),,square[i][j]); } printf(); } printf(, (rows * rows + 1) * rows / 2); } int main(int argC,char* argV[]) { int n; if(argC!=2||isdigit(argV[1][0])==0) printf(,argV[0]); else{ n = atoi(argV[1]); printMagicSquare(singlyEvenMagicSquare(n),n); } return 0; }
600Magic squares of singly even order
5c
m1nys
package main import ( "fmt" "math" "rcu" ) func magicConstant(n int) int { return (n*n + 1) * n / 2 } var ss = []string{ "\u2070", "\u00b9", "\u00b2", "\u00b3", "\u2074", "\u2075", "\u2076", "\u2077", "\u2078", "\u2079", } func superscript(n int) string { if n < 10 { return ss[n] } if n < 20 { return ss[1] + ss[n-10] } return ss[2] + ss[0] } func main() { fmt.Println("First 20 magic constants:") for n := 3; n <= 22; n++ { fmt.Printf("%5d ", magicConstant(n)) if (n-2)%10 == 0 { fmt.Println() } } fmt.Println("\n1,000th magic constant:", rcu.Commatize(magicConstant(1002))) fmt.Println("\nSmallest order magic square with a constant greater than:") for i := 1; i <= 20; i++ { goal := math.Pow(10, float64(i)) order := int(math.Cbrt(goal*2)) + 1 fmt.Printf("10%-2s:%9s\n", superscript(i), rcu.Commatize(order)) } }
601Magic constant
0go
o518q
import System.Directory (createDirectory, setCurrentDirectory) import Data.List.Split (splitOn) main :: IO () main = do let path = splitOn "/" "path/to/dir" mapM_ (\x -> createDirectory x >> setCurrentDirectory x) path
595Make directory path
8haskell
48v5s
import java.io.File; public interface Test { public static void main(String[] args) { try { File f = new File("C:/parent/test"); if (f.mkdirs()) System.out.println("path successfully created"); } catch (Exception e) { e.printStackTrace(); } } }
595Make directory path
9java
cey9h
var path = require('path'); var fs = require('fs'); function mkdirp (p, cb) { cb = cb || function () {}; p = path.resolve(p); fs.mkdir(p, function (er) { if (!er) { return cb(null); } switch (er.code) { case 'ENOENT':
595Make directory path
10javascript
502ur
package main import "fmt" type sBox [8][16]byte type gost struct { k87, k65, k43, k21 [256]byte enc []byte } func newGost(s *sBox) *gost { var g gost for i := range g.k87 { g.k87[i] = s[7][i>>4]<<4 | s[6][i&15] g.k65[i] = s[5][i>>4]<<4 | s[4][i&15] g.k43[i] = s[3][i>>4]<<4 | s[2][i&15] g.k21[i] = s[1][i>>4]<<4 | s[0][i&15] } g.enc = make([]byte, 8) return &g } func (g *gost) f(x uint32) uint32 { x = uint32(g.k87[x>>24&255])<<24 | uint32(g.k65[x>>16&255])<<16 | uint32(g.k43[x>>8&255])<<8 | uint32(g.k21[x&255]) return x<<11 | x>>(32-11) }
596Main step of GOST 28147-89
0go
m1zyi
int main() { int i; puts(); for(i=0;i<=10;i++) { printf(,i,mapRange(0,10,-1,0,i)); } return 0; }
602Map range
5c
503uk
import curses import random import time ROW_DELAY=.0001 def get_rand_in_range(min, max): return random.randrange(min,max+1) try: chars = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'] total_chars = len(chars) stdscr = curses.initscr() curses.noecho() curses.curs_set(False) curses.start_color() curses.init_pair(1, curses.COLOR_GREEN, curses.COLOR_BLACK) stdscr.attron(curses.color_pair(1)) max_x = curses.COLS - 1 max_y = curses.LINES - 1 columns_row = [] columns_active = [] for i in range(max_x+1): columns_row.append(-1) columns_active.append(0) while(True): for i in range(max_x): if columns_row[i] == -1: columns_row[i] = get_rand_in_range(0, max_y) columns_active[i] = get_rand_in_range(0, 1) for i in range(max_x): if columns_active[i] == 1: char_index = get_rand_in_range(0, total_chars-1) stdscr.addstr(columns_row[i], i, chars[char_index]) else: stdscr.addstr(columns_row[i], i, ); columns_row[i]+=1 if columns_row[i] >= max_y: columns_row[i] = -1 if get_rand_in_range(0, 1000) == 0: if columns_active[i] == 0: columns_active[i] = 1 else: columns_active[i] = 0 time.sleep(ROW_DELAY) stdscr.refresh() except KeyboardInterrupt as err: curses.endwin()
593Matrix digital rain
3python
gig4h
use std::collections::HashMap; fn main() { println!("{}\n", mcm_display(vec![5, 6, 3, 1])); println!( "{}\n", mcm_display(vec![1, 5, 25, 30, 100, 70, 2, 1, 100, 250, 1, 1000, 2]) ); println!( "{}\n", mcm_display(vec![1000, 1, 500, 12, 1, 700, 2500, 3, 2, 5, 14, 10]) ); } fn mcm_display(dims: Vec<i32>) -> String { let mut costs: HashMap<Vec<i32>, (i32, Vec<usize>)> = HashMap::new(); let mut line = format!("Dims: {:?}\n", dims); let ans = mcm(dims, &mut costs); let mut mats = (1..=ans.1.len() + 1) .map(|x| x.to_string()) .collect::<Vec<String>>(); for i in 0..ans.1.len() { let mat_taken = mats[ans.1[i]].clone(); mats.remove(ans.1[i]); mats[ans.1[i]] = "(".to_string() + &mat_taken + "*" + &mats[ans.1[i]] + ")"; } line += &format!("Order: {}\n", mats[0]); line += &format!("Cost: {}", ans.0); line } fn mcm(dims: Vec<i32>, costs: &mut HashMap<Vec<i32>, (i32, Vec<usize>)>) -> (i32, Vec<usize>) { match costs.get(&dims) { Some(c) => c.clone(), None => { let ans = if dims.len() == 3 { (dims[0] * dims[1] * dims[2], vec![0]) } else { let mut min_cost = std::i32::MAX; let mut min_path = Vec::new(); for i in 1..dims.len() - 1 { let taken = dims[(i - 1)..(i + 2)].to_vec(); let mut rest = dims[..i].to_vec(); rest.extend_from_slice(&dims[(i + 1)..]); let a1 = mcm(taken, costs); let a2 = mcm(rest, costs); if a1.0 + a2.0 < min_cost { min_cost = a1.0 + a2.0; min_path = vec![i - 1]; min_path.extend_from_slice(&a2.1); } } (min_cost, min_path) }; costs.insert(dims, ans.clone()); ans } } }
592Matrix chain multiplication
15rust
1yapu
null
588Maximum triangle path sum
11kotlin
u07vc
use strict; use warnings; my @twenty = map $_ * ( $_ ** 2 + 1 ) / 2, 3 .. 22; print "first twenty: @twenty\n\n" =~ s/.{50}\K /\n/gr; my $thousandth = 1002 * ( 1002 ** 2 + 1 ) / 2; print "thousandth: $thousandth\n\n"; print "10**N order\n"; for my $i ( 1 .. 20 ) { printf "%3d%9d\n", $i, (10 ** $i * 2) ** ( 1 / 3 ) + 1; }
601Magic constant
2perl
jdl7f
null
595Make directory path
11kotlin
3kfz5
require("lfs") function mkdir (path) local sep, pStr = package.config:sub(1, 1), "" for dir in path:gmatch("[^" .. sep .. "]+") do pStr = pStr .. dir .. sep lfs.mkdir(pStr) end end mkdir("C:\\path\\to\\dir")
595Make directory path
1lua
6bt39
const _ = [ [ 4, 10, 9, 2, 13, 8, 0, 14, 6, 11, 1, 12, 7, 15, 5, 3], [14, 11, 4, 12, 6, 13, 15, 10, 2, 3, 8, 1, 0, 7, 5, 9], [ 5, 8, 1, 13, 10, 3, 4, 2, 14, 15, 12, 7, 6, 0, 9, 11], [ 7, 13, 10, 1, 0, 8, 9, 15, 14, 4, 6, 12, 11, 2, 5, 3], [ 6, 12, 7, 1, 5, 15, 13, 8, 4, 10, 9, 14, 0, 3, 11, 2], [ 4, 11, 10, 0, 7, 2, 1, 13, 3, 6, 8, 5, 9, 12, 15, 14], [13, 11, 4, 1, 3, 15, 5, 9, 0, 10, 14, 7, 6, 8, 2, 12], [ 1, 15, 13, 0, 5, 7, 10, 4, 9, 2, 3, 14, 6, 11, 8, 12] ]; const _ = (_, _, ) => { const N = _.slice(0), S = N[0] + _ & 0xFFFFFFFF; let _S = 0; for (let = 0; < 4; ++) { const = (S >>> ( << 3)) & 0xFF; _S += [ * 2][ & 0x0F] + ([ * 2 + 1][ >>> 4] << 4) << ( << 3); } _S = (_S << 11) + (_S >>> 21) & 0xFFFFFFFF ^ N[1]; N[1] = N[0]; N[0] = _S; return N; };
596Main step of GOST 28147-89
10javascript
hfgjh
package main import "fmt"
598Magnanimous numbers
0go
s21qa
null
591Matrix-exponentiation operator
11kotlin
igdo4
(defn maprange [[a1 a2] [b1 b2] s] (+ b1 (/ (* (- s a1) (- b2 b1)) (- a2 a1)))) > (doseq [s (range 11)] (printf "%2s maps to%s\n" s (maprange [0 10] [-1 0] s))) 0 maps to -1 1 maps to -9/10 2 maps to -4/5 3 maps to -7/10 4 maps to -3/5 5 maps to -1/2 6 maps to -2/5 7 maps to -3/10 8 maps to -1/5 9 maps to -1/10 10 maps to 0
602Map range
6clojure
jdc7m
import random def encode(correct, guess): output_arr = [''] * len(correct) for i, (correct_char, guess_char) in enumerate(zip(correct, guess)): output_arr[i] = 'X' if guess_char == correct_char else 'O' if guess_char in correct else '-' return ''.join(output_arr) def safe_int_input(prompt, min_val, max_val): while True: user_input = input(prompt) try: user_input = int(user_input) except ValueError: continue if min_val <= user_input <= max_val: return user_input def play_game(): print() print() print() print() print() number_of_letters = safe_int_input(, 2, 20) code_length = safe_int_input(, 4, 10) letters = 'ABCDEFGHIJKLMNOPQRST'[:number_of_letters] code = ''.join(random.choices(letters, k=code_length)) guesses = [] while True: print() guess = input(f).upper().strip() if len(guess) != code_length or any([char not in letters for char in guess]): continue elif guess == code: print(f) break else: guesses.append(f) for i_guess in guesses: print() print(i_guess) print() if __name__ == '__main__': play_game()
594Mastermind
3python
3ktzc
local triangleSmall = { { 55 }, { 94, 48 }, { 95, 30, 96 }, { 77, 71, 26, 67 }, } local triangleLarge = { { 55 }, { 94, 48 }, { 95, 30, 96 }, { 77, 71, 26, 67 }, { 97, 13, 76, 38, 45 }, { 7, 36, 79, 16, 37, 68 }, { 48, 7, 9, 18, 70, 26, 6 }, { 18, 72, 79, 46, 59, 79, 29, 90 }, { 20, 76, 87, 11, 32, 7, 7, 49, 18 }, { 27, 83, 58, 35, 71, 11, 25, 57, 29, 85 }, { 14, 64, 36, 96, 27, 11, 58, 56, 92, 18, 55 }, { 2, 90, 3, 60, 48, 49, 41, 46, 33, 36, 47, 23 }, { 92, 50, 48, 2, 36, 59, 42, 79, 72, 20, 82, 77, 42 }, { 56, 78, 38, 80, 39, 75, 2, 71, 66, 66, 1, 3, 55, 72 }, { 44, 25, 67, 84, 71, 67, 11, 61, 40, 57, 58, 89, 40, 56, 36 }, { 85, 32, 25, 85, 57, 48, 84, 35, 47, 62, 17, 1, 1, 99, 89, 52 }, { 6, 71, 28, 75, 94, 48, 37, 10, 23, 51, 6, 48, 53, 18, 74, 98, 15 }, { 27, 2, 92, 23, 8, 71, 76, 84, 15, 52, 92, 63, 81, 10, 44, 10, 69, 93 }, }; function solve(triangle)
588Maximum triangle path sum
1lua
58ju6
(declare a) (defn man-or-boy "Man or boy test for Clojure" [k] (let [k (atom k)] (a k (fn [] 1) (fn [] -1) (fn [] -1) (fn [] 1) (fn [] 0)))) (defn a [k x1 x2 x3 x4 x5] (let [k (atom @k)] (letfn [(b [] (swap! k dec) (a k b x1 x2 x3 x4))] (if (<= @k 0) (+ (x4) (x5)) (b))))) (man-or-boy 10)
599Man or boy test
6clojure
usyvi
null
596Main step of GOST 28147-89
11kotlin
lwycp
import Data.List.Split ( chunksOf ) import Data.List ( (!!) ) isPrime :: Int -> Bool isPrime n |n == 2 = True |n == 1 = False |otherwise = null $ filter (\i -> mod n i == 0 ) [2 .. root] where root :: Int root = floor $ sqrt $ fromIntegral n isMagnanimous :: Int -> Bool isMagnanimous n = all isPrime $ map (\p -> fst p + snd p ) numberPairs where str:: String str = show n splitStrings :: [(String , String)] splitStrings = map (\i -> splitAt i str) [1 .. length str - 1] numberPairs :: [(Int , Int)] numberPairs = map (\p -> ( read $ fst p , read $ snd p )) splitStrings printInWidth :: Int -> Int -> String printInWidth number width = replicate ( width - l ) ' ' ++ str where str :: String str = show number l :: Int l = length str solution :: [Int] solution = take 400 $ filter isMagnanimous [0 , 1 ..] main :: IO ( ) main = do let numbers = solution numberlines = chunksOf 10 $ take 45 numbers putStrLn "First 45 magnanimous numbers:" mapM_ (\li -> putStrLn (foldl1 ( ++ ) $ map (\n -> printInWidth n 6 ) li )) numberlines putStrLn "241'st to 250th magnanimous numbers:" putStr $ show ( numbers !! 240 ) putStrLn ( foldl1 ( ++ ) $ map(\n -> printInWidth n 8 ) $ take 9 $ drop 241 numbers ) putStrLn "391'st to 400th magnanimous numbers:" putStr $ show ( numbers !! 390 ) putStrLn ( foldl1 ( ++ ) $ map(\n -> printInWidth n 8 ) $ drop 391 numbers)
598Magnanimous numbers
8haskell
9atmo
package main import ( "crypto/md5" "fmt" ) func main() { for _, p := range [][2]string{
590MD5
0go
svoqa