code
stringlengths
1
46.1k
label
class label
1.18k classes
domain_label
class label
21 classes
index
stringlengths
4
5
import Data.List toBase :: Int -> Integer -> [Int] toBase b = unfoldr f where f 0 = Nothing f n = let (q, r) = n `divMod` fromIntegral b in Just (fromIntegral r, q) fromBase :: Int -> [Int] -> Integer fromBase n lst = foldr (\x r -> fromIntegral n*r + fromIntegral x) 0 lst listToInt :: Int -> [Int] -> Integer listToInt b lst = fromBase (b+1) $ concat seq where seq = [ let (q, r) = divMod n b in replicate q 0 ++ [r+1] | n <- lst ] intToList :: Int -> Integer -> [Int] intToList b lst = go 0 $ toBase (b+1) lst where go 0 [] = [] go i (0:xs) = go (i+1) xs go i (x:xs) = (i*b + x - 1): go 0 xs
718Index finite lists of positive integers
8haskell
ivuor
assert(math.type~=nil, "Lua 5.3+ required for this test.") minint, maxint = math.mininteger, math.maxinteger print("min, max int64 = " .. minint .. ", " .. maxint) print("min-1 underflow = " .. (minint-1) .. " equals max? " .. tostring(minint-1==maxint)) print("max+1 overflow = " .. (maxint+1) .. " equals min? " .. tostring(maxint+1==minint))
710Integer overflow
1lua
d5pnq
if _VERSION:sub(5) + 0 < 5.1 then print"too old" end
709Introspection
1lua
f4adp
$ perl -de1 Loading DB routines from perl5db.pl version 1.3 Editor support available. Enter h or `h h' for help, or `man perldebug' for more help. main::(-e:1): 1 DB<1> sub f {my ($s1, $s2, $sep) = @_; $s1 . $sep . $sep . $s2} DB<2> p f('Rosetta', 'Code', ':') Rosetta::Code DB<3> q
707Interactive programming (repl)
2perl
vet20
null
717Idiomatically determine all the characters that can be used for symbols
11kotlin
cpa98
import BigInt func is89(_ n: Int) -> Bool { var n = n while true { var s = 0 repeat { s += (n%10) * (n%10) n /= 10 } while n > 0 if s == 89 { return true } else if s == 1 { return false } n = s } } func iterSquare(upToPower pow: Int) { var sums = [BigInt](repeating: 0, count: pow * 81 + 1) sums[0] = 1 for n in 1...pow { var i = n * 81 while i > 0 { for j in 1..<10 { let s = j * j guard s <= i else { break } sums[i] += sums[i-s] } i -= 1 } var count89 = BigInt(0) for x in 1..<n*81 + 1 { guard is89(x) else { continue } count89 += sums[x] } print("1->10^\(n): \(count89)") } } iterSquare(upToPower: 8)
703Iterated digits squaring
17swift
azj1i
import java.math.BigInteger; import static java.util.Arrays.stream; import java.util.*; import static java.util.stream.Collectors.*; public class Test3 { static BigInteger rank(int[] x) { String s = stream(x).mapToObj(String::valueOf).collect(joining("F")); return new BigInteger(s, 16); } static List<BigInteger> unrank(BigInteger n) { BigInteger sixteen = BigInteger.valueOf(16); String s = ""; while (!n.equals(BigInteger.ZERO)) { s = "0123456789ABCDEF".charAt(n.mod(sixteen).intValue()) + s; n = n.divide(sixteen); } return stream(s.split("F")).map(x -> new BigInteger(x)).collect(toList()); } public static void main(String[] args) { int[] s = {1, 2, 3, 10, 100, 987654321}; System.out.println(Arrays.toString(s)); System.out.println(rank(s)); System.out.println(unrank(rank(s))); } }
718Index finite lists of positive integers
9java
xymwy
null
708Inverted index
11kotlin
xyrws
package main type animal struct { alive bool } type dog struct { animal obedienceTrained bool } type cat struct { animal litterBoxTrained bool } type lab struct { dog color string } type collie struct { dog catchesFrisbee bool } func main() { var pet lab pet.alive = true pet.obedienceTrained = false pet.color = "yellow" }
712Inheritance/Single
0go
bdmkh
class Animal{
712Inheritance/Single
7groovy
r0tgh
int main(int argc, char const *argv[]) { for (char c = 0x41; c < 0x5b; c ++) putchar(c); putchar('\n'); for (char c = 0x61; c < 0x7b; c ++) putchar(c); putchar('\n'); return 0; }
719Idiomatically determine all the lowercase and uppercase letters
5c
2aalo
int find(char *s, char c) { for (char *i = s; *i != 0; i++) { if (*i == c) { return i - s; } } return -1; } void reverse(char *b, char *e) { for (e--; b < e; b++, e--) { char t = *b; *b = *e; *e = t; } } struct Complex { double rel, img; }; void printComplex(struct Complex c) { printf(, c.rel, c.img); } struct Complex makeComplex(double rel, double img) { struct Complex c = { rel, img }; return c; } struct Complex addComplex(struct Complex a, struct Complex b) { struct Complex c = { a.rel + b.rel, a.img + b.img }; return c; } struct Complex mulComplex(struct Complex a, struct Complex b) { struct Complex c = { a.rel * b.rel - a.img * b.img, a.rel * b.img - a.img * b.rel }; return c; } struct Complex mulComplexD(struct Complex a, double b) { struct Complex c = { a.rel * b, a.img * b }; return c; } struct Complex negComplex(struct Complex a) { return mulComplexD(a, -1.0); } struct Complex divComplex(struct Complex a, struct Complex b) { double re = a.rel * b.rel + a.img * b.img; double im = a.img * b.rel - a.rel * b.img; double d = b.rel * b.rel + b.img * b.img; struct Complex c = { re / d, im / d }; return c; } struct Complex inv(struct Complex c) { double d = c.rel * c.rel + c.img * c.img; struct Complex i = { c.rel / d, -c.img / d }; return i; } const struct Complex TWO_I = { 0.0, 2.0 }; const struct Complex INV_TWO_I = { 0.0, -0.5 }; struct QuaterImaginary { char *b2i; int valid; }; struct QuaterImaginary makeQuaterImaginary(char *s) { struct QuaterImaginary qi = { s, 0 }; size_t i, valid = 1, cnt = 0; if (*s != 0) { for (i = 0; s[i] != 0; i++) { if (s[i] < '0' || '3' < s[i]) { if (s[i] == '.') { cnt++; } else { valid = 0; break; } } } if (valid && cnt > 1) { valid = 0; } } qi.valid = valid; return qi; } void printQuaterImaginary(struct QuaterImaginary qi) { if (qi.valid) { printf(, qi.b2i); } else { printf(); } } struct Complex qi2c(struct QuaterImaginary qi) { size_t len = strlen(qi.b2i); int pointPos = find(qi.b2i, '.'); size_t posLen = (pointPos > 0) ? pointPos : len; struct Complex sum = makeComplex(0.0, 0.0); struct Complex prod = makeComplex(1.0, 0.0); size_t j; for (j = 0; j < posLen; j++) { double k = qi.b2i[posLen - 1 - j] - '0'; if (k > 0.0) { sum = addComplex(sum, mulComplexD(prod, k)); } prod = mulComplex(prod, TWO_I); } if (pointPos != -1) { prod = INV_TWO_I; for (j = posLen + 1; j < len; j++) { double k = qi.b2i[j] - '0'; if (k > 0.0) { sum = addComplex(sum, mulComplexD(prod, k)); } prod = mulComplex(prod, INV_TWO_I); } } return sum; } struct QuaterImaginary c2qi(struct Complex c, char *out) { char *p = out; int re, im, fi; *p = 0; if (c.rel == 0.0 && c.img == 0.0) { return makeQuaterImaginary(); } re = (int)c.rel; im = (int)c.img; fi = -1; while (re != 0) { int rem = re % -4; re /= -4; if (rem < 0) { rem += 4; re++; } *p++ = rem + '0'; *p++ = '0'; *p = 0; } if (im != 0) { size_t index = 1; struct Complex fc = divComplex((struct Complex) { 0.0, c.img }, (struct Complex) { 0.0, 2.0 }); double f = fc.rel; im = (int)ceil(f); f = -4.0 * (f - im); while (im != 0) { int rem = im % -4; im /= -4; if (rem < 0) { rem += 4; im++; } if (index < (p - out)) { out[index] = rem + '0'; } else { *p++ = '0'; *p++ = rem + '0'; *p = 0; } index += 2; } fi = (int)f; } reverse(out, p); if (fi != -1) { *p++ = '.'; *p++ = fi + '0'; *p = 0; } while (out[0] == '0' && out[1] != '.') { size_t i; for (i = 0; out[i] != 0; i++) { out[i] = out[i + 1]; } } if (*out == '.') { reverse(out, p); *p++ = '0'; *p = 0; reverse(out, p); } return makeQuaterImaginary(out); } int main() { char buffer[16]; int i; for (i = 1; i <= 16; i++) { struct Complex c1 = { i, 0.0 }; struct QuaterImaginary qi = c2qi(c1, buffer); struct Complex c2 = qi2c(qi); printComplex(c1); printf(); printQuaterImaginary(qi); printf(); printComplex(c2); printf(); c1 = negComplex(c1); qi = c2qi(c1, buffer); c2 = qi2c(qi); printComplex(c1); printf(); printQuaterImaginary(qi); printf(); printComplex(c2); printf(); } printf(); for (i = 1; i <= 16; i++) { struct Complex c1 = { 0.0, i }; struct QuaterImaginary qi = c2qi(c1, buffer); struct Complex c2 = qi2c(qi); printComplex(c1); printf(); printQuaterImaginary(qi); printf(); printComplex(c2); printf(); c1 = negComplex(c1); qi = c2qi(c1, buffer); c2 = qi2c(qi); printComplex(c1); printf(); printQuaterImaginary(qi); printf(); printComplex(c2); printf(); } return 0; }
720Imaginary base numbers
5c
pfdby
null
718Index finite lists of positive integers
11kotlin
pftb6
package Camera; 1;
711Inheritance/Multiple
2perl
o2j8x
use strict; use warnings; use List::Util 'sum'; sub comma { reverse ((reverse shift) =~ s/(.{3})/$1,/gr) =~ s/^,//r } my ($index, $last, $gap, $count) = (0, 0, 0, 0); my $threshold = 10_000_000; print "Gap Index of gap Starting Niven\n"; while (1) { $count++; next unless 0 == $count % sum split //, $count; if ((my $diff = $count - $last) > $gap) { $gap = $diff; printf "%3d%15s%15s\n", $gap, $index > 1 ? comma $index : 1, $last > 1 ? comma $last : 1; } $last = $count; last if ++$index >= $threshold; }
715Increasing gaps between consecutive Niven numbers
2perl
ivgo3
class Animal a class Animal a => Cat a class Animal a => Dog a class Dog a => Lab a class Dog a => Collie a
712Inheritance/Single
8haskell
d5kn4
for $i (0..0x7f) { $c = chr($i); print $c if $c =~ /\w/; } use utf8; binmode STDOUT, ":utf8"; for (0..0x1ffff) { $c = chr($_); print $c if $c =~ /\p{Word}/; }
717Idiomatically determine all the characters that can be used for symbols
2perl
xy9w8
image filter(image img, double *K, int Ks, double, double);
721Image convolution
5c
w6zec
use bigint; use ntheory qw(fromdigits todigitstring); use feature 'say'; sub rank { join '', fromdigits(join('a',@_), 11) } sub unrank { split 'a', todigitstring(@_[0], 11) } say join ' ', @n = qw<12 11 0 7 9 15 15 5 7 13 5 5>; say $n = rank(@n); say join ' ', unrank $n;
718Index finite lists of positive integers
2perl
yhk6u
class Camera: pass
711Inheritance/Multiple
3python
ivhof
def digit_sum(n, sum): sum += 1 while n > 0 and n% 10 == 0: sum -= 9 n /= 10 return sum previous = 1 gap = 0 sum = 0 niven_index = 0 gap_index = 1 print() niven = 1 while gap_index <= 22: sum = digit_sum(niven, sum) if niven% sum == 0: if niven > previous + gap: gap = niven - previous; print('{0:9d} {1:4d} {2:13d} {3:11d}'.format(gap_index, gap, niven_index, previous)) gap_index += 1 previous = niven niven_index += 1 niven += 1
715Increasing gaps between consecutive Niven numbers
3python
nuriz
null
710Integer overflow
2perl
786rh
module Commatize refine Integer do def commatize self.to_s.gsub( /(\d)(?=\d{3}+(?:\.|$))(\d{3}\..*)?/, ) end end end using Commatize def isqrt(x) q, r = 1, 0 while (q <= x) do q <<= 2 end while (q > 1) do q >>= 2; t = x-r-q; r >>= 1 if (t >= 0) then x, r = t, r+q end end r end puts (0..65).map{|n| isqrt(n) }.join() 1.step(73, 2) do |n| print puts isqrt(7**n).commatize end
705Isqrt (integer square root) of X
14ruby
6jo3t
python Python 2.6.1 (r261:67517, Dec 4 2008, 16:51:00) [MSC v.1500 32 bit (Intel)] on win32 Type , , or for more information. >>> def f(string1, string2, separator): return separator.join([string1, '', string2]) >>> f('Rosetta', 'Code', ':') 'Rosetta::Code' >>>
707Interactive programming (repl)
3python
uwzvd
def validISBN13?(str) cleaned = str.delete().chars return false unless cleaned.size == 13 cleaned.each_slice(2).sum{|d1, d2| d1.to_i + 3*d2.to_i }.remainder(10) == 0 end isbns = [, , , ] isbns.each{|isbn| puts }
704ISBN13 check digit
14ruby
8la01
[ $ $ QsTtUuVvWwXxYyZz()[]{}<>~=+-*/^\|_.,:;?!'string is used, so cannot appear as a character in that string. In the second string all the reasonable delimiters are used, so Q is used as the delimiter. As it is not possible to make a string that uses all the characters, two strings are concatenated (join) to make the string during compilation. (Which is why $ $ Qs...$Q join is nested (inside [ ... ]) and followed by the word constant, which causes the nest to be evaluated during compilation.) Regardless of operating system, Quackery only knows the characters in the string tokenchars, plus space and carriage return. The characters in tokenchars are in QACSFOT order (the Quackery Arbitrary Character Sequence For Ordered Text) which it uses for string comparison, but the valid tokens (which is all of them) will be printed by alltokens in the order native to the operating system. (In this instance, Unicode.) ) [ tokenchars find tokenchars found ] is validtoken ( c --> b ) [ 256 times [ i^ validtoken if [ i^ emit ] ] ] is alltokens ( --> ) alltokens
717Idiomatically determine all the characters that can be used for symbols
3python
qmcxi
unsigned int frames = 0; unsigned int t_acc = 0; void print_fps () { static Uint32 last_t = 0; Uint32 t = SDL_GetTicks(); Uint32 dt = t - last_t; t_acc += dt; if (t_acc > 1000) { unsigned int el_time = t_acc / 1000; printf(, (float) frames / (float) el_time); t_acc = 0; frames = 0; } last_t = t; } void blit_noise(SDL_Surface *surf) { unsigned int i; long dim = surf->w * surf->h; while (1) { SDL_LockSurface(surf); for (i=0; i < dim; ++i) { ((unsigned char *)surf->pixels)[i] = ((rand() & 1) ? 255 : 0); } SDL_UnlockSurface(surf); SDL_Flip(surf); ++frames; print_fps(); } } int main(void) { SDL_Surface *surf = NULL; srand((unsigned int)time(NULL)); SDL_Init(SDL_INIT_TIMER | SDL_INIT_VIDEO); surf = SDL_SetVideoMode(320, 240, 8, SDL_DOUBLEBUF | SDL_HWSURFACE); blit_noise(surf); }
722Image noise
5c
cph9c
module Camera end class MobilePhone end class CameraPhone < MobilePhone include Camera end
711Inheritance/Multiple
14ruby
d5bns
trait Camera {} trait MobilePhone {} trait CameraPhone: Camera + MobilePhone {}
711Inheritance/Multiple
15rust
f4pd6
use num::BigUint; use num::CheckedSub; use num_traits::{One, Zero}; fn isqrt(number: &BigUint) -> BigUint { let mut q: BigUint = One::one(); while q <= *number { q <<= &2; } let mut z = number.clone(); let mut result: BigUint = Zero::zero(); while q > One::one() { q >>= &2; let t = z.checked_sub(&result).and_then(|diff| diff.checked_sub(&q)); result >>= &1; if let Some(t) = t { z = t; result += &q; } } result } fn with_thousand_separator(s: &str) -> String { let digits: Vec<_> = s.chars().rev().collect(); let chunks: Vec<_> = digits .chunks(3) .map(|chunk| chunk.iter().collect::<String>()) .collect(); chunks.join(",").chars().rev().collect::<String>() } fn main() { println!("The integer square roots of integers from 0 to 65 are:"); (0_u32..=65).for_each(|n| print!("{} ", isqrt(&n.into()))); println!("\nThe integer square roots of odd powers of 7 from 7^1 up to 7^74 are:"); (1_u32..75).step_by(2).for_each(|exp| { println!( "7^{:>2}={:>83} ISQRT: {:>42} ", exp, with_thousand_separator(&BigUint::from(7_u8).pow(exp).to_string()), with_thousand_separator(&isqrt(&BigUint::from(7_u8).pow(exp)).to_string()) ) }); }
705Isqrt (integer square root) of X
15rust
yhi68
use Set::Object 'set'; sub createindex { my @files = @_; my %iindex; foreach my $file (@files) { open(F, "<", $file) or die "Can't read file $file: $!"; while(<F>) { s/\A\W+//; foreach my $w (map {lc} grep {length() >= 3} split /\W+/) { if ( exists($iindex{$w}) ) { $iindex{$w}->insert($file); } else { $iindex{$w} = set($file); } } } close(F); } return %iindex; } sub search_words_with_index { my %idx = %{shift()}; my @words = @_; my $res = set(); foreach my $w (map {lc} @words) { $w =~ s/\W+//g; length $w < 3 and next; exists $idx{$w} or return set(); $res = $res->is_null ? set(@{$idx{$w}}) : $res * $idx{$w}; } return @$res; } my @searchwords = split /,/, shift; print "$_\n" foreach search_words_with_index({createindex(@ARGV)}, @searchwords);
708Inverted index
2perl
2adlf
$ R R version 2.7.2 (2008-08-25) Copyright (C) 2008 The R Foundation for Statistical Computing ISBN 3-900051-07-0 R is free software and comes with ABSOLUTELY NO WARRANTY. You are welcome to redistribute it under certain conditions. Type 'license()' or 'licence()' for distribution details. Natural language support but running in an English locale R is a collaborative project with many contributors. Type 'contributors()' for more information and 'citation()' on how to cite R or R packages in publications. Type 'demo()' for some demos, 'help()' for on-line help, or 'help.start()' for an HTML browser interface to help. Type 'q()' to quit R. > f <- function(a, b, s) paste(a, "", b, sep=s) > f("Rosetta", "Code", ":") [1] "Rosetta::Code" > q() Save workspace image? [y/n/c]: n
707Interactive programming (repl)
13r
cpn95
fn main() { let isbns = ["978-1734314502", "978-1734314509", "978-1788399081", "978-1788399083"]; isbns.iter().for_each(|isbn| println!("{}: {}", isbn, check_isbn(isbn))); } fn check_isbn(isbn: &str) -> bool { if isbn.chars().filter(|c| c.is_digit(10)).count()!= 13 { return false; } let checksum = isbn.chars().filter_map(|c| c.to_digit(10)) .zip([1, 3].iter().cycle()) .fold(0, |acc, (val, fac)| acc + val * fac); checksum% 10 == 0 }
704ISBN13 check digit
15rust
o2e83
public class Animal{
712Inheritance/Single
9java
s94q0
function Animal() {
712Inheritance/Single
10javascript
nuhiy
object IdiomaticallyDetermineSymbols extends App { private def print(msg: String, limit: Int, p: Int => Boolean, fmt: String) = println(msg + (0 to 0x10FFFF).filter(p).take(limit).map(fmt.format(_)).mkString + "...") print("Java Identifier start: ", 72, cp => Character.isJavaIdentifierStart(cp), "%c") print("Java Identifier part: ", 25, cp => Character.isJavaIdentifierPart(cp), "[%d]") print("Identifier ignorable: ", 25, cp => Character.isIdentifierIgnorable(cp), "[%d]") print("Unicode Identifier start: ", 72, cp => Character.isUnicodeIdentifierStart(cp), "%c") print("Unicode Identifier part: ", 25, cp => Character.isUnicodeIdentifierPart(cp), "[%d]") }
717Idiomatically determine all the characters that can be used for symbols
16scala
nu4ic
def rank(x): return int('a'.join(map(str, [1] + x)), 11) def unrank(n): s = '' while n: s,n = [n%11] + s, n return map(int, s.split('a'))[1:] l = [1, 2, 3, 10, 100, 987654321] print l n = rank(l) print n l = unrank(n) print l
718Index finite lists of positive integers
3python
mkbyh
trait Camera trait MobilePhone class CameraPhone extends Camera with MobilePhone
711Inheritance/Multiple
16scala
37ezy
protocol Camera { } protocol Phone { } class CameraPhone: Camera, Phone { }
711Inheritance/Multiple
17swift
nukil
nivens = Enumerator.new {|y| (1..).each {|n| y << n if n.remainder(n.digits.sum).zero?} } cur_gap = 0 puts 'Gap Index of gap Starting Niven' nivens.each_cons(2).with_index(1) do |(n1, n2), i| break if i > 10_000_000 if n2-n1 > cur_gap then printf , n2-n1, i, n1 cur_gap = n2-n1 end end
715Increasing gaps between consecutive Niven numbers
14ruby
f4jdr
null
715Increasing gaps between consecutive Niven numbers
15rust
tghfd
null
712Inheritance/Single
11kotlin
azl13
package main import ( "fmt" "unicode" ) const ( lcASCII = "abcdefghijklmnopqrstuvwxyz" ucASCII = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" ) func main() { fmt.Println("ASCII lower case:") fmt.Println(lcASCII) for l := 'a'; l <= 'z'; l++ { fmt.Print(string(l)) } fmt.Println() fmt.Println("\nASCII upper case:") fmt.Println(ucASCII) for l := 'A'; l <= 'Z'; l++ { fmt.Print(string(l)) } fmt.Println() fmt.Println("\nUnicode version " + unicode.Version) showRange16("Lower case 16-bit code points:", unicode.Lower.R16) showRange32("Lower case 32-bit code points:", unicode.Lower.R32) showRange16("Upper case 16-bit code points:", unicode.Upper.R16) showRange32("Upper case 32-bit code points:", unicode.Upper.R32) } func showRange16(hdr string, rList []unicode.Range16) { fmt.Print("\n", hdr, "\n") fmt.Printf("%d ranges:\n", len(rList)) for _, rng := range rList { fmt.Printf("%U: ", rng.Lo) for r := rng.Lo; r <= rng.Hi; r += rng.Stride { fmt.Printf("%c", r) } fmt.Println() } } func showRange32(hdr string, rList []unicode.Range32) { fmt.Print("\n", hdr, "\n") fmt.Printf("%d ranges:\n", len(rList)) for _, rng := range rList { fmt.Printf("%U: ", rng.Lo) for r := rng.Lo; r <= rng.Hi; r += rng.Stride { fmt.Printf("%c", r) } fmt.Println() } }
719Idiomatically determine all the lowercase and uppercase letters
0go
qmmxz
package main import ( "fmt" "math" "strconv" "strings" ) const ( twoI = 2.0i invTwoI = 1.0 / twoI ) type quaterImaginary struct { b2i string } func reverse(s string) string { r := []rune(s) for i, j := 0, len(r)-1; i < len(r)/2; i, j = i+1, j-1 { r[i], r[j] = r[j], r[i] } return string(r) } func newQuaterImaginary(b2i string) quaterImaginary { b2i = strings.TrimSpace(b2i) _, err := strconv.ParseFloat(b2i, 64) if err != nil { panic("invalid Base 2i number") } return quaterImaginary{b2i} } func toComplex(q quaterImaginary) complex128 { pointPos := strings.Index(q.b2i, ".") var posLen int if pointPos != -1 { posLen = pointPos } else { posLen = len(q.b2i) } sum := 0.0i prod := complex(1.0, 0.0) for j := 0; j < posLen; j++ { k := float64(q.b2i[posLen-1-j] - '0') if k > 0.0 { sum += prod * complex(k, 0.0) } prod *= twoI } if pointPos != -1 { prod = invTwoI for j := posLen + 1; j < len(q.b2i); j++ { k := float64(q.b2i[j] - '0') if k > 0.0 { sum += prod * complex(k, 0.0) } prod *= invTwoI } } return sum } func (q quaterImaginary) String() string { return q.b2i }
720Imaginary base numbers
0go
6j73p
package main import ( "fmt" "image" "image/color" "image/jpeg" "math" "os" )
721Image convolution
0go
cpk9g
package main import ( "fmt" "math" )
716Infinity
0go
4q852
package main import ( "bufio" "io" "log" "os" ) func main() { in := bufio.NewReader(os.Stdin) for { s, err := in.ReadString('\n') if err != nil {
713Input loop
0go
nuji1
def lineMap = [:] System.in.eachLine { line, i -> lineMap[i] = line } lineMap.each { println it }
713Input loop
7groovy
s95q1
<?php function buildInvertedIndex($filenames) { $invertedIndex = []; foreach($filenames as $filename) { $data = file_get_contents($filename); if($data === false) die('Unable to read file: ' . $filename); preg_match_all('/(\w+)/', $data, $matches, PREG_SET_ORDER); foreach($matches as $match) { $word = strtolower($match[0]); if(!array_key_exists($word, $invertedIndex)) $invertedIndex[$word] = []; if(!in_array($filename, $invertedIndex[$word], true)) $invertedIndex[$word][] = $filename; } } return $invertedIndex; } function lookupWord($invertedIndex, $word) { return array_key_exists($word, $invertedIndex)? $invertedIndex[$word] : false; } $invertedIndex = buildInvertedIndex2(['file1.txt', 'file2.txt', 'file3.txt']); foreach(['cat', 'is', 'banana', 'it'] as $word) { $matches = lookupWord($invertedIndex, $word); if($matches !== false) { echo $word\ . implode(', ', $matches) . ; } else { echo $word\; } }
708Inverted index
12php
s9jqs
require v5.6.1; require 5.6.1; require 5.006_001;
709Introspection
2perl
jom7f
func checkISBN(isbn: String) -> Bool { guard!isbn.isEmpty else { return false } let sum = isbn .compactMap({ $0.wholeNumberValue }) .enumerated() .map({ $0.offset & 1 == 1? 3 * $0.element: $0.element }) .reduce(0, +) return sum% 10 == 0 } let cases = [ "978-1734314502", "978-1734314509", "978-1788399081", "978-1788399083" ] for isbn in cases { print("\(isbn) => \(checkISBN(isbn: isbn)? "good": "bad")") }
704ISBN13 check digit
17swift
0c1s6
main = do putStrLn $ "Lower: " ++ ['a'..'z'] putStrLn $ "Upper: " ++ ['A'..'Z']
719Idiomatically determine all the lowercase and uppercase letters
8haskell
mkkyf
import java.util.stream.IntStream; public class Letters { public static void main(String[] args) throws Exception { System.out.print("Upper case: "); IntStream.rangeClosed(0, 0x10FFFF) .filter(Character::isUpperCase) .limit(72) .forEach(n -> System.out.printf("%c", n)); System.out.println("..."); System.out.print("Lower case: "); IntStream.rangeClosed(0, 0x10FFFF) .filter(Character::isLowerCase) .limit(72) .forEach(n -> System.out.printf("%c", n)); System.out.println("..."); } }
719Idiomatically determine all the lowercase and uppercase letters
9java
f44dv
import Data.Char (chr, digitToInt, intToDigit, isDigit, ord) import Data.Complex (Complex (..), imagPart, realPart) import Data.List (delete, elemIndex) import Data.Maybe (fromMaybe) base :: Complex Float base = 0:+ 2 quotRemPositive :: Int -> Int -> (Int, Int) quotRemPositive a b | r < 0 = (1 + q, floor (realPart (-base ^^ 2)) + r) | otherwise = (q, r) where (q, r) = quotRem a b digitToIntQI :: Char -> Int digitToIntQI c | isDigit c = digitToInt c | otherwise = ord c - ord 'a' + 10 shiftRight :: String -> String shiftRight n | l == '0' = h | otherwise = h <> ('.': [l]) where (l, h) = (last n, init n) intToDigitQI :: Int -> Char intToDigitQI i | i `elem` [0 .. 9] = intToDigit i | otherwise = chr (i - 10 + ord 'a') fromQItoComplex :: String -> Complex Float -> Complex Float fromQItoComplex num b = let dot = fromMaybe (length num) (elemIndex '.' num) in fst $ foldl ( \(a, indx) x -> ( a + fromIntegral (digitToIntQI x) * (b ^^ (dot - indx)), indx + 1 ) ) (0, 1) (delete '.' num) euclidEr :: Int -> Int -> [Int] -> [Int] euclidEr a b l | a == 0 = l | otherwise = let (q, r) = quotRemPositive a b in euclidEr q b (0: r: l) fromIntToQI :: Int -> [Int] fromIntToQI 0 = [0] fromIntToQI x = tail ( euclidEr x (floor $ realPart (base ^^ 2)) [] ) getCuid :: Complex Int -> Int getCuid c = imagPart c * floor (imagPart (-base)) qizip :: Complex Int -> [Int] qizip c = let (r, i) = ( fromIntToQI (realPart c) <> [0], fromIntToQI (getCuid c) ) in let m = min (length r) (length i) in take (length r - m) r <> take (length i - m) i <> reverse ( zipWith (+) (take m (reverse r)) (take m (reverse i)) ) fromComplexToQI :: Complex Int -> String fromComplexToQI = shiftRight . fmap intToDigitQI . qizip main :: IO () main = putStrLn (fromComplexToQI (35:+ 23)) >> print (fromQItoComplex "10.2" base)
720Imaginary base numbers
8haskell
jo87g
import java.awt.image.*; import java.io.File; import java.io.IOException; import javax.imageio.*; public class ImageConvolution { public static class ArrayData { public final int[] dataArray; public final int width; public final int height; public ArrayData(int width, int height) { this(new int[width * height], width, height); } public ArrayData(int[] dataArray, int width, int height) { this.dataArray = dataArray; this.width = width; this.height = height; } public int get(int x, int y) { return dataArray[y * width + x]; } public void set(int x, int y, int value) { dataArray[y * width + x] = value; } } private static int bound(int value, int endIndex) { if (value < 0) return 0; if (value < endIndex) return value; return endIndex - 1; } public static ArrayData convolute(ArrayData inputData, ArrayData kernel, int kernelDivisor) { int inputWidth = inputData.width; int inputHeight = inputData.height; int kernelWidth = kernel.width; int kernelHeight = kernel.height; if ((kernelWidth <= 0) || ((kernelWidth & 1) != 1)) throw new IllegalArgumentException("Kernel must have odd width"); if ((kernelHeight <= 0) || ((kernelHeight & 1) != 1)) throw new IllegalArgumentException("Kernel must have odd height"); int kernelWidthRadius = kernelWidth >>> 1; int kernelHeightRadius = kernelHeight >>> 1; ArrayData outputData = new ArrayData(inputWidth, inputHeight); for (int i = inputWidth - 1; i >= 0; i--) { for (int j = inputHeight - 1; j >= 0; j--) { double newValue = 0.0; for (int kw = kernelWidth - 1; kw >= 0; kw--) for (int kh = kernelHeight - 1; kh >= 0; kh--) newValue += kernel.get(kw, kh) * inputData.get( bound(i + kw - kernelWidthRadius, inputWidth), bound(j + kh - kernelHeightRadius, inputHeight)); outputData.set(i, j, (int)Math.round(newValue / kernelDivisor)); } } return outputData; } public static ArrayData[] getArrayDatasFromImage(String filename) throws IOException { BufferedImage inputImage = ImageIO.read(new File(filename)); int width = inputImage.getWidth(); int height = inputImage.getHeight(); int[] rgbData = inputImage.getRGB(0, 0, width, height, null, 0, width); ArrayData reds = new ArrayData(width, height); ArrayData greens = new ArrayData(width, height); ArrayData blues = new ArrayData(width, height); for (int y = 0; y < height; y++) { for (int x = 0; x < width; x++) { int rgbValue = rgbData[y * width + x]; reds.set(x, y, (rgbValue >>> 16) & 0xFF); greens.set(x, y, (rgbValue >>> 8) & 0xFF); blues.set(x, y, rgbValue & 0xFF); } } return new ArrayData[] { reds, greens, blues }; } public static void writeOutputImage(String filename, ArrayData[] redGreenBlue) throws IOException { ArrayData reds = redGreenBlue[0]; ArrayData greens = redGreenBlue[1]; ArrayData blues = redGreenBlue[2]; BufferedImage outputImage = new BufferedImage(reds.width, reds.height, BufferedImage.TYPE_INT_ARGB); for (int y = 0; y < reds.height; y++) { for (int x = 0; x < reds.width; x++) { int red = bound(reds.get(x, y), 256); int green = bound(greens.get(x, y), 256); int blue = bound(blues.get(x, y), 256); outputImage.setRGB(x, y, (red << 16) | (green << 8) | blue | -0x01000000); } } ImageIO.write(outputImage, "PNG", new File(filename)); return; } public static void main(String[] args) throws IOException { int kernelWidth = Integer.parseInt(args[2]); int kernelHeight = Integer.parseInt(args[3]); int kernelDivisor = Integer.parseInt(args[4]); System.out.println("Kernel size: " + kernelWidth + "x" + kernelHeight + ", divisor=" + kernelDivisor); int y = 5; ArrayData kernel = new ArrayData(kernelWidth, kernelHeight); for (int i = 0; i < kernelHeight; i++) { System.out.print("["); for (int j = 0; j < kernelWidth; j++) { kernel.set(j, i, Integer.parseInt(args[y++])); System.out.print(" " + kernel.get(j, i) + " "); } System.out.println("]"); } ArrayData[] dataArrays = getArrayDatasFromImage(args[0]); for (int i = 0; i < dataArrays.length; i++) dataArrays[i] = convolute(dataArrays[i], kernel, kernelDivisor); writeOutputImage(args[1], dataArrays); return; } }
721Image convolution
9java
r0qg0
def rank(arr) arr.join('a').to_i(11) end def unrank(n) n.to_s(11).split('a').map(&:to_i) end l = [1, 2, 3, 10, 100, 987654321] p l n = rank(l) p n l = unrank(n) p l
718Index finite lists of positive integers
14ruby
cp19k
object IndexFiniteList extends App { val (defBase, s) = (10, Seq(1, 2, 3, 10, 100, 987654321)) def rank(x: Seq[Int], base: Int = defBase) = BigInt(x.map(Integer.toString(_, base)).mkString(base.toHexString), base + 1) def unrank(n: BigInt, base: Int = defBase): List[BigInt] = n.toString(base + 1).split((base).toHexString).map(BigInt(_)).toList val ranked = rank(s) println(s.mkString("[", ", ", "]")) println(ranked) println(unrank(ranked).mkString("[", ", ", "]")) }
718Index finite lists of positive integers
16scala
uwxv8
def biggest = { Double.POSITIVE_INFINITY }
716Infinity
7groovy
l1wc1
maxRealFloat :: RealFloat a => a -> a maxRealFloat x = encodeFloat b (e-1) `asTypeOf` x where b = floatRadix x - 1 (_,e) = floatRange x infinity :: RealFloat a => a infinity = if isInfinite inf then inf else maxRealFloat 1.0 where inf = 1/0
716Infinity
8haskell
qmlx9
import System.IO readLines :: Handle -> IO [String] readLines h = do s <- hGetContents h return $ lines s readWords :: Handle -> IO [String] readWords h = do s <- hGetContents h return $ words s
713Input loop
8haskell
uwov2
import BigInt func integerSquareRoot<T: BinaryInteger>(_ num: T) -> T { var x: T = num var q: T = 1 while q <= x { q <<= 2 } var r: T = 0 while q > 1 { q >>= 2 let t: T = x - r - q r >>= 1 if t >= 0 { x = t r += q } } return r } func pad(string: String, width: Int) -> String { if string.count >= width { return string } return String(repeating: " ", count: width - string.count) + string } func commatize<T: BinaryInteger>(_ num: T) -> String { let string = String(num) var result = String() result.reserveCapacity(4 * string.count / 3) var i = 0 for ch in string { if i > 0 && i% 3 == string.count% 3 { result += "," } result.append(ch) i += 1 } return result } print("Integer square root for numbers 0 to 65:") for n in 0...65 { print(integerSquareRoot(n), terminator: " ") } let powerWidth = 83 let isqrtWidth = 42 print("\n\nInteger square roots of odd powers of 7 from 1 to 73:") print(" n |\(pad(string: "7 ^ n", width: powerWidth)) |\(pad(string: "isqrt(7 ^ n)", width: isqrtWidth))") print(String(repeating: "-", count: powerWidth + isqrtWidth + 6)) var p: BigInt = 7 for n in stride(from: 1, through: 73, by: 2) { let power = pad(string: commatize(p), width: powerWidth) let isqrt = pad(string: commatize(integerSquareRoot(p)), width: isqrtWidth) print("\(pad(string: String(n), width: 2)) |\(power) |\(isqrt)") p *= 49 }
705Isqrt (integer square root) of X
17swift
378z2
$ irb irb(main):001:0> def f(string1, string2, separator) irb(main):002:1> [string1, '', string2].join(separator) irb(main):003:1> end => :f irb(main):004:0> f('Rosetta', 'Code', ':') => irb(main):005:0> exit $
707Interactive programming (repl)
14ruby
4q65p
(load "path/to/file")
723Include a file
6clojure
4qa5o
Class = { classname = "Class aka Object aka Root-Of-Tree", new = function(s,t) s.__index = s local instance = setmetatable(t or {}, s) instance.parent = s return instance end } Animal = Class:new{classname="Animal", speak=function(s) return s.voice or "("..s.classname.." has no voice)" end } Cat = Animal:new{classname="Cat", voice="meow"} Dog = Animal:new{classname="Dog", voice="woof"} Lab = Dog:new{classname="Lab", voice="bark"} Collie = Dog:new{classname="Collie"}
712Inheritance/Single
1lua
e32ac
null
719Idiomatically determine all the lowercase and uppercase letters
11kotlin
8ll0q
function ASCIIstring (pattern) local matchString, ch = "" for charNum = 0, 255 do ch = string.char(charNum) if string.match(ch, pattern) then matchString = matchString .. ch end end return matchString end print(ASCIIstring("%l")) print(ASCIIstring("%u"))
719Idiomatically determine all the lowercase and uppercase letters
1lua
o228h
null
721Image convolution
10javascript
bdiki
<?php if (version_compare(PHP_VERSION, '5.3.0', '<' )) { echo( . PHP_VERSION . ); exit(); } $bloop = -3; if (isset($bloop) && function_exists('abs')) { echo(abs($bloop)); } echo(count($GLOBALS) . ); echo(array_sum($GLOBALS) . ); ?>
709Introspection
12php
tgef1
my @prisoner = 0 .. 40; my $k = 3; until (@prisoner == 1) { push @prisoner, shift @prisoner for 1 .. $k-1; shift @prisoner; } print "Prisoner @prisoner survived.\n"
702Josephus problem
2perl
zritb
name: myapp version: "1.0" author: A Rust Developer <[email protected]> about: Does awesome things args: - STRING1: about: First string to use required: true index: 1 - STRING2: about: Second string to use required: true index: 2 - SEPARATOR: about: Separtor to use required: true index: 3
707Interactive programming (repl)
15rust
gsy4o
C:\>scala Welcome to Scala version 2.8.0.r21356-b20100407020120 (Java HotSpot(TM) Client V M, Java 1.6.0_05). Type in expressions to have them evaluated. Type :help for more information. scala> "rosetta" res0: java.lang.String = rosetta
707Interactive programming (repl)
16scala
joc7i
public class ImaginaryBaseNumber { private static class Complex { private Double real, imag; public Complex(double r, double i) { this.real = r; this.imag = i; } public Complex(int r, int i) { this.real = (double) r; this.imag = (double) i; } public Complex add(Complex rhs) { return new Complex( real + rhs.real, imag + rhs.imag ); } public Complex times(Complex rhs) { return new Complex( real * rhs.real - imag * rhs.imag, real * rhs.imag + imag * rhs.real ); } public Complex times(double rhs) { return new Complex( real * rhs, imag * rhs ); } public Complex inv() { double denom = real * real + imag * imag; return new Complex( real / denom, -imag / denom ); } public Complex unaryMinus() { return new Complex(-real, -imag); } public Complex divide(Complex rhs) { return this.times(rhs.inv()); }
720Imaginary base numbers
9java
uwevv
double infinity = Double.POSITIVE_INFINITY;
716Infinity
9java
pf3b3
Python 2.7.5 (default, May 15 2013, 22:43:36) [MSC v.1500 32 bit (Intel)] on win32 Type , or for more information. >>> for calc in ''' -(-2147483647-1) 2000000000 + 2000000000 -2147483647 - 2147483647 46341 * 46341 (-2147483647-1) / -1'''.split('\n'): ans = eval(calc) print('Expression:%r evaluates to%s of type%s' % (calc.strip(), ans, type(ans))) Expression: '-(-2147483647-1)' evaluates to 2147483648 of type <type 'long'> Expression: '2000000000 + 2000000000' evaluates to 4000000000 of type <type 'long'> Expression: '-2147483647 - 2147483647' evaluates to -4294967294 of type <type 'long'> Expression: '46341 * 46341' evaluates to 2147488281 of type <type 'long'> Expression: '(-2147483647-1) / -1' evaluates to 2147483648 of type <type 'long'> >>>
710Integer overflow
3python
joy7p
import java.io.InputStream; import java.util.Scanner; public class InputLoop { public static void main(String args[]) {
713Input loop
9java
mkwym
''' This implements: http: ''' from pprint import pprint as pp from glob import glob try: reduce except: from functools import reduce try: raw_input except: raw_input = input def parsetexts(fileglob='InvertedIndex/T*.txt'): texts, words = {}, set() for txtfile in glob(fileglob): with open(txtfile, 'r') as f: txt = f.read().split() words |= set(txt) texts[txtfile.split('\\')[-1]] = txt return texts, words def termsearch(terms): return reduce(set.intersection, (invindex[term] for term in terms), set(texts.keys())) texts, words = parsetexts() print('\nTexts') pp(texts) print('\nWords') pp(sorted(words)) invindex = {word:set(txt for txt, wrds in texts.items() if word in wrds) for word in words} print('\nInverted Index') pp({k:sorted(v) for k,v in invindex.items()}) terms = [, , ] print('\nTerm Search for: ' + repr(terms)) pp(sorted(termsearch(terms)))
708Inverted index
3python
vef29
for $i (0..2**8-1) { $c = chr $i; $lower .= $c if $c =~ /[[:lower:]]/; $upper .= $c if $c =~ /[[:upper:]]/; } print "$lower\n"; print "$upper\n";
719Idiomatically determine all the lowercase and uppercase letters
2perl
4qq5d
classes = (str.isupper, str.islower, str.isalnum, str.isalpha, str.isdecimal, str.isdigit, str.isidentifier, str.isnumeric, str.isprintable, str.isspace, str.istitle) for stringclass in classes: chars = ''.join(chr(i) for i in range(0x10FFFF+1) if stringclass(chr(i))) print('\nString class%s has%i characters the first of which are:\n %r' % (stringclass.__name__, len(chars), chars[:100]))
719Idiomatically determine all the lowercase and uppercase letters
3python
gss4h
null
721Image convolution
11kotlin
ve121
Infinity
716Infinity
10javascript
xycw9
$ js -e 'while (line = readline()) { do_something_with(line); }' < inputfile
713Input loop
10javascript
ve825
<?php function Jotapata($n=41,$k=3,$m=1){$m--; $prisoners=array_fill(0,$n,false); $deadpool=1; $order=0; while((array_sum(array_count_values($prisoners))<$n)){ foreach($prisoners as $thisPrisoner=>$dead){ if(!$dead){ if($deadpool==$k){ $order++; $prisoners[$thisPrisoner]=((($n-$m)>($order)?$order:(($n)==$order?'Call me *Titus Flavius* Josephus':'Joe\'s friend '.(($order)-($n-$m-1))))); $deadpool=1; }else{$duckpool++;} } } } return $prisoners; } echo '<pre>'.print_r(Jotapata(41,3,5),true).'<pre>';
702Josephus problem
12php
bdrk9
LETTERS letters
719Idiomatically determine all the lowercase and uppercase letters
13r
vee27
null
720Imaginary base numbers
11kotlin
9bkmh
fun main(args: Array<String>) { val p = Double.POSITIVE_INFINITY
716Infinity
11kotlin
78nr4
import sys major, minor, bugfix = sys.version_info[:3] if major < 2: sys.exit('Python 2 is required') def defined(name): return name in globals() or name in locals() or name in vars(__builtins__) def defined2(name): try: eval(name) return True except NameError: return False if defined('bloop') and defined('abs') and callable(abs): print abs(bloop) if defined2('bloop') and defined2('abs') and callable(abs): print abs(bloop)
709Introspection
3python
hi9jw
package main import ( "bufio" "fmt" "log" "math/rand" "os" "strconv" "strings" "time" ) var cave = map[int][3]int{ 1: {2, 3, 4}, 2: {1, 5, 6}, 3: {1, 7, 8}, 4: {1, 9, 10}, 5: {2, 9, 11}, 6: {2, 7, 12}, 7: {3, 6, 13}, 8: {3, 10, 14}, 9: {4, 5, 15}, 10: {4, 8, 16}, 11: {5, 12, 17}, 12: {6, 11, 18}, 13: {7, 14, 18}, 14: {8, 13, 19}, 15: {9, 16, 17}, 16: {10, 15, 19}, 17: {11, 20, 15}, 18: {12, 13, 20}, 19: {14, 16, 20}, 20: {17, 18, 19}, } var player, wumpus, bat1, bat2, pit1, pit2 int var arrows = 5 func isEmpty(r int) bool { if r != player && r != wumpus && r != bat1 && r != bat2 && r != pit1 && r != pit2 { return true } return false } func sense(adj [3]int) { bat := false pit := false for _, ar := range adj { if ar == wumpus { fmt.Println("You smell something terrible nearby.") } switch ar { case bat1, bat2: if !bat { fmt.Println("You hear a rustling.") bat = true } case pit1, pit2: if !pit { fmt.Println("You feel a cold wind blowing from a nearby cavern.") pit = true } } } fmt.Println() } func check(err error) { if err != nil { log.Fatal(err) } } func plural(n int) string { if n != 1 { return "s" } return "" } func main() { rand.Seed(time.Now().UnixNano()) player = 1 wumpus = rand.Intn(19) + 2
724Hunt the Wumpus
0go
knshz
package main import ( "code.google.com/p/x-go-binding/ui/x11" "fmt" "image" "image/color" "image/draw" "log" "os" "time" ) var randcol = genrandcol() func genrandcol() <-chan color.Color { c := make(chan color.Color) go func() { for { select { case c <- image.Black: case c <- image.White: } } }() return c } func gennoise(screen draw.Image) { for y := 0; y < 240; y++ { for x := 0; x < 320; x++ { screen.Set(x, y, <-randcol) } } } func fps() chan<- bool { up := make(chan bool) go func() { var frames int64 var lasttime time.Time var totaltime time.Duration for { <-up frames++ now := time.Now() totaltime += now.Sub(lasttime) if totaltime > time.Second { fmt.Printf("FPS:%v\n", float64(frames)/totaltime.Seconds()) frames = 0 totaltime = 0 } lasttime = now } }() return up } func main() { win, err := x11.NewWindow() if err != nil { fmt.Println(err) os.Exit(1) } defer win.Close() go func() { upfps := fps() screen := win.Screen() for { gennoise(screen) win.FlushImage() upfps <- true } }() for _ = range win.EventChan() { } }
722Image noise
0go
w6teg
2.1.1:001 > a = 2**62 -1 => 4611686018427387903 2.1.1:002 > a.class => Fixnum 2.1.1:003 > (b = a + 1).class => Bignum 2.1.1:004 > (b-1).class => Fixnum
710Integer overflow
14ruby
kn9hg
error: attempt to divide with overflow --> src/main.rs:3:23 | 3 | let i32_5: i32 = (-2_147_483_647 - 1) / -1; | ^^^^^^^^^^^^^^^^^^^^^^^^^ | = note: `#[deny(const_err)]` on by default
710Integer overflow
15rust
bdckx
null
713Input loop
11kotlin
tgbf0
if(getRversion() < "2.14.1") { warning("Your version of R is older than 2.14.1") q() }
709Introspection
13r
gs347
int main() { int a, b; scanf(, &a, &b); if (a < b) printf(, a, b); if (a == b) printf(, a, b); if (a > b) printf(, a, b); return 0; }
725Integer comparison
5c
6ju32
bool isHumble(int i) { if (i <= 1) return true; if (i % 2 == 0) return isHumble(i / 2); if (i % 3 == 0) return isHumble(i / 3); if (i % 5 == 0) return isHumble(i / 5); if (i % 7 == 0) return isHumble(i / 7); return false; } int main() { int limit = SHRT_MAX; int humble[16]; int count = 0; int num = 1; char buffer[16]; memset(humble, 0, sizeof(humble)); for (; count < limit; num++) { if (isHumble(num)) { size_t len; sprintf_s(buffer, sizeof(buffer), , num); len = strlen(buffer); if (len >= 16) { break; } humble[len]++; if (count < 50) { printf(, num); } count++; } } printf(); printf(, count); for (num = 1; num < 10; num++) { printf(, humble[num], num); } return 0; }
726Humble numbers
5c
l1rcy
import System.Random import System.IO import Data.List import Data.Char import Control.Monad cave :: [[Int]] cave = [ [1,4,7], [0,2,9], [1,3,11], [2,4,13], [0,3,5], [4,6,14], [5,7,16], [0,6,8], [7,9,17], [1,8,10], [9,11,18], [2,10,12], [11,13,19], [3,12,14], [5,13,15], [14,16,19], [6,15,17], [8,16,18], [10,17,19], [12,15,18]] caveSize :: Int caveSize = length cave data GameState = GameState { wumpus :: Int, player :: Int, arrows :: Int, pits :: [Int], bats :: [Int] } instance Show GameState where show g = "You are in room " ++ show (player g) ++ ". " ++ "Adjacent rooms are: " ++ (intercalate ", " $ map show adjs) ++ ".\nYou have " ++ show (arrows g) ++ " arrows.\n\n" ++ adjMsgs where adjs = cave!!player g adj = any (`elem` adjs) . ($ g) adjMsgs = unlines $ ["You smell something terrible nearby." | adj $ pure.wumpus] ++ ["You hear a rustling." | adj bats] ++ ["You feel a cold wind blowing from a nearby cavern." | adj pits] initGame :: StdGen -> GameState initGame g = GameState {wumpus=w, player=p, arrows=5, pits=[p1,p2], bats=[b1,b2]} where [w, p, p1, p2, b1, b2] = take 6 $ nub $ map (`mod` 20) $ randoms g moveWumpus :: GameState -> StdGen -> GameState moveWumpus s g | null freeAdj = s | otherwise = s {wumpus = freeAdj!!(fst $ randomR (0, length freeAdj-1) g)} where freeAdj = [r | r <- cave!!wumpus s, not $ elem r $ pits s++bats s] movePlayer :: GameState -> StdGen -> GameState movePlayer s g = s {player = (cave !! player s) !! (fst $ randomR (0,2) g)} data Action = Move | Shoot | Quit deriving Show inputAction :: IO Action inputAction = do putStr "M)ove, S)hoot or Q)uit? " hFlush stdout ch <- getChar putStrLn "" case toLower ch of 'm' -> return Move 's' -> return Shoot 'q' -> return Quit _ -> putStrLn "Invalid command" >> inputAction inputDestination :: Int -> IO Int inputDestination cur = do putStr "Where to? " hFlush stdout input <- getLine case reads input of [] -> err "Sorry?" [(x,_)] -> if x `elem` (cave !! cur) then return x else err "Can't get there from here." where err x = putStrLn x >> inputDestination cur inputYesNo :: IO Bool inputYesNo = do ch <- getChar case toLower ch of 'n' -> putStrLn "" >> return False 'y' -> putStrLn "" >> return True _ -> putStr (map chr [7,8]) >> inputYesNo data PlayerState = NoArrows | Bat | Pit | Wumpus | Alive deriving Show playerState :: GameState -> PlayerState playerState s | player s == wumpus s = Wumpus | player s `elem` bats s = Bat | player s `elem` pits s = Pit | arrows s == 0 = NoArrows | otherwise = Alive data GameResult = Win | Lose | Stop deriving Show game :: GameState -> IO GameResult game s = case playerState s of Wumpus -> putStrLn "You find yourself face to face with the wumpus." >> putStrLn "It eats you alive in one bite.\n" >> return Lose Pit -> putStrLn "You fall into a deep pit. Death waits at the bottom.\n" >> return Lose Bat -> putStrLn "You have walked into the lair of a giant bat." >> putStrLn "It picks you up and deposits you outside.\n" >> newStdGen >>= game . movePlayer s NoArrows -> putStrLn "You notice you are out of arrows." >> putStrLn "You hear a large beast approaching.\n" >> return Lose Alive -> do putStrLn "" putStrLn $ show s action <- inputAction case action of Quit -> return Stop _ -> do dest <- inputDestination (player s) case action of Move -> game s {player = dest} Shoot -> shoot s dest shoot :: GameState -> Int -> IO GameResult shoot s tgt | tgt == wumpus s = do putStrLn "Congratulations! You shot the wumpus!\n" return Win | otherwise = do let s'' = s { arrows = pred $ arrows s } putStrLn "That's a miss." awake <- randomRIO (0,3::Int) if awake /= 0 then do putStrLn "The wumpus wakes from his slumber." newStdGen >>= game . moveWumpus s'' else game s'' playGame :: IO () playGame = do result <- newStdGen >>= game . initGame case result of Stop -> return () _ -> do case result of Lose -> putStrLn "You have met your demise." Win -> putStrLn "You win!" putStr "\nAnother game? (Y/N) " inputYesNo >>= flip when playGame main :: IO () main = do hSetBuffering stdin NoBuffering hSetBuffering stdout NoBuffering putStrLn "*** HUNT THE WUMPUS ***" putStrLn "" playGame
724Hunt the Wumpus
8haskell
nu9ie
puts , [*..].join, , [*..].join
719Idiomatically determine all the lowercase and uppercase letters
14ruby
788ri
fn main() { println!( "Lowercase letters: {}", (b'a'..=b'z').map(|c| c as char).collect::<String>() ); println!( "Uppercase letters: {}", (b'A'..=b'Z').map(|c| c as char).collect::<String>() ); }
719Idiomatically determine all the lowercase and uppercase letters
15rust
joo72
object IdiomaticallyDetermineLowercaseUppercase extends App { println("Upper case: " + (0 to 0x10FFFF).map(_.toChar).filter(_.isUpper).take(72).mkString + "...") println("Lower case: " + (0 to 0x10FFFF).map(_.toChar).filter(_.isLower).take(72).mkString + "...") }
719Idiomatically determine all the lowercase and uppercase letters
16scala
bddk6
cabal install glfw-b
722Image noise
8haskell
6jg3k
function infinity() return 1/0
716Infinity
1lua
jod71