code
stringlengths
1
46.1k
label
class label
1.18k classes
domain_label
class label
21 classes
index
stringlengths
4
5
import Math.{addExact => ++, multiplyExact => **, negateExact => ~~, subtractExact => --} def requireOverflow(f: => Unit) = try {f; println("Undetected overflow")} catch{case e: Exception => } println("Testing overflow detection for 32-bit unsigned integers") requireOverflow(~~(--(~~(2147483647), 1)))
710Integer overflow
16scala
azv1n
if File.exist? @data = Marshal.load open() else @data = {} end class String def index_sanitize self.split.collect do |token| token.downcase.gsub(/\W/, '') end end end ARGV.each do |filename| open filename do |file| file.read.index_sanitize.each do |word| @data[word] ||= [] @data[word] << filename unless @data[word].include? filename end end end open(, ) do |index| index.write Marshal.dump(@data) end
708Inverted index
14ruby
5xzuj
const starttxt = """ ATTENTION ALL WUMPUS LOVERS!!! THERE ARE NOW TWO ADDITIONS TO THE WUMPUS FAMILY OF PROGRAMS. WUMP2: SOME DIFFERENT CAVE ARRANGEMENTS WUMP3: DIFFERENT HAZARDS """ const helptxt = """ WELCOME TO 'HUNT THE WUMPUS' THE WUMPUS LIVES IN A CAVE OF 20 ROOMS. EACH ROOM HAS 3 TUNNELS LEADING TO OTHER ROOMS. (LOOK AT A DODECAHEDRON TO SEE HOW THIS WORKS-IF YOU DON'T KNOW WHAT A DODECAHEDRON IS, ASK SOMEONE) HAZARDS: BOTTOMLESS PITS - TWO ROOMS HAVE BOTTOMLESS PITS IN THEM IF YOU GO THERE, YOU FALL INTO THE PIT (& LOSE!) SUPER BATS - TWO OTHER ROOMS HAVE SUPER BATS. IF YOU GO THERE, A BAT GRABS YOU AND TAKES YOU TO SOME OTHER ROOM AT RANDOM. (WHICH MIGHT BE TROUBLESOME) WUMPUS: THE WUMPUS IS NOT BOTHERED BY THE HAZARDS (HE HAS SUCKER FEET AND IS TOO BIG FOR A BAT TO LIFT). USUALLY HE IS ASLEEP. TWO THINGS WAKE HIM UP: YOUR ENTERING HIS ROOM OR YOUR SHOOTING AN ARROW. IF THE WUMPUS WAKES, HE MOVES (P=.75) ONE ROOM OR STAYS STILL (P=.25). AFTER THAT, IF HE IS WHERE YOU ARE, HE EATS YOU UP (& YOU LOSE!) YOU: EACH TURN YOU MAY MOVE OR SHOOT A CROOKED ARROW MOVING: YOU CAN GO ONE ROOM (THRU ONE TUNNEL) ARROWS: YOU HAVE 5 ARROWS. YOU LOSE WHEN YOU RUN OUT. EACH ARROW CAN GO FROM 1 TO 5 ROOMS. YOU AIM BY TELLING THE COMPUTER THE ROOM#S YOU WANT THE ARROW TO GO TO. IF THE ARROW CAN'T GO THAT WAY (IE NO TUNNEL) IT MOVES AT RANDOM TO THE NEXT ROOM. IF THE ARROW HITS THE WUMPUS, YOU WIN. IF THE ARROW HITS YOU, YOU LOSE. WARNINGS: WHEN YOU ARE ONE ROOM AWAY FROM WUMPUS OR HAZARD, THE COMPUTER SAYS: WUMPUS- 'I SMELL A WUMPUS' BAT - 'BATS NEARBY' PIT - 'I FEEL A DRAFT' """ function queryprompt(query, choices, choicetxt="") carr = map(x -> uppercase(strip(string(x))), collect(choices)) while true print(query, " ", choicetxt == ""? carr: choicetxt, ": ") choice = uppercase(strip(readline(stdin))) if choice in carr return choice end println() end end function wumpushunt(cheatmode = false) println(starttxt) arrows = 5 rooms = Vector{Vector{Int}}() push!(rooms, [2,6,5], [3,8,1], [4,10,2], [5,2,3], [1,14,4], [15,1,7], [17,6,8], [7,2,9], [18,8,10], [9,3,11], [19,10,12], [11,4,13], [20,12,14], [5,11,13], [6,16,14], [20,15,17], [16,7,18], [17,9,19], [18,11,20], [19,13,16]) roomcontents = shuffle(push!(fill("Empty", 15), "Bat", "Bat", "Pit", "Pit", "Wumpus")) randnextroom(room) = rand(rooms[room]) newplayerroom(cr, range = 40) = (for i in 1:range cr = randnextroom(cr) end; cr) function senseroom(p) linkedrooms = rooms[p] if cheatmode println("linked rooms are $(rooms[p]), which have $(roomcontents[rooms[p][1]]), $(roomcontents[rooms[p][2]]), $(roomcontents[rooms[p][3]])") end if any(x -> roomcontents[x] == "Wumpus", linkedrooms) println("I SMELL A WUMPUS!") end if any(x -> roomcontents[x] == "Pit", linkedrooms) println("I FEEL A DRAFT") end if any(x -> roomcontents[x] == "Bat", linkedrooms) println("BATS NEARBY!") end end function arrowflight(arrowroom) if roomcontents[arrowroom] == "Wumpus" println("AHA! YOU GOT THE WUMPUS!") return("win") elseif any(x -> roomcontents[x] == "Wumpus", rooms[arrowroom]) numrooms = rand([0, 1, 2, 3]) if numrooms > 0 println("...OOPS! BUMPED A WUMPUS!") wroom = rooms[arrowroom][findfirst(x -> roomcontents[x] == "Wumpus", rooms[arrowroom])] for i in 1:3 tmp = wroom wroom = rand(rooms[wroom]) if wroom == playerroom println("TSK TSK TSK- WUMPUS GOT YOU!") return "lose" else roomcontents[tmp] = roomcontents[wroom] roomcontents[wroom] = "Wumpus" end end end elseif arrowroom == playerroom println("OUCH! ARROW GOT YOU!") return "lose" end return "" end println("HUNT THE WUMPUS") playerroom = 1 while true playerroom = newplayerroom(playerroom) if roomcontents[playerroom] == "Empty" break end end while arrows > 0 senseroom(playerroom) println("YOU ARE IN ROOM $playerroom. TUNNELS LEAD TO ", join(rooms[playerroom], ";")) choice = queryprompt("SHOOT OR MOVE (H FOR HELP)", ["S", "M", "H"]) if choice == "M" choice = queryprompt("WHERE TO", rooms[playerroom]) playerroom = parse(Int, choice) if roomcontents[playerroom] == "Wumpus" println("TSK TSK TSK- WUMPUS GOT YOU!") return "lose" elseif roomcontents[playerroom] == "Pit" println("YYYIIIIEEEE . . . FELL IN PIT") return "lose" elseif roomcontents[playerroom] == "Bat" senseroom(playerroom) println("ZAP--SUPER BAT SNATCH! ELSEWHEREVILLE FOR YOU!") playerroom = newplayerroom(playerroom, 10) end elseif choice == "S" distance = parse(Int, queryprompt("NO. OF ROOMS(1-5)", 1:5)) choices = zeros(Int, 5) arrowroom = playerroom for i in 1:distance choices[i] = parse(Int, queryprompt("ROOM #", 1:20, "1-20")) while i > 2 && choices[i] == choices[i-2] println("ARROWS AREN'T THAT CROOKED - TRY ANOTHER ROOM") choices[i] = parse(Int, queryprompt("ROOM #", 1:20, "1-20")) end arrowroom = choices[i] end arrowroom = playerroom for rm in choices if rm!= 0 if!(rm in rooms[arrowroom]) rm = rand(rooms[arrowroom]) end arrowroom = rm if (ret = arrowflight(arrowroom))!= "" return ret end end end arrows -= 1 println("MISSED") elseif choice == "H" println(helptxt) end end println("OUT OF ARROWS.\nHA HA HA - YOU LOSE!") return "lose" end while true result = wumpushunt() println("Game over. You $(result)!") if queryprompt("Play again?", ["Y", "N"]) == "N" break end end
724Hunt the Wumpus
9java
qmtxa
use strict; use warnings; use feature 'say'; use Math::Complex; use List::AllUtils qw(sum mesh); use ntheory qw<todigitstring fromdigits>; sub zip { my($a,$b) = @_; my($la, $lb) = (length $a, length $b); my $l = '0' x abs $la - $lb; $a .= $l if $la < $lb; $b .= $l if $lb < $la; (join('', mesh(@{[split('',$a),]}, @{[split('',$b),]})) =~ s/0+$//r) or 0; } sub base_i { my($num,$radix,$precision) = @_; die unless $radix > -37 and $radix < -1; return '0' unless $num; my $value = $num; my $result = ''; my $place = 0; my $upper_bound = 1 / (-$radix + 1); my $lower_bound = $radix * $upper_bound; $value = $num / $radix ** ++$place until $lower_bound <= $value and $value < $upper_bound; while (($value or $place > 0) and $place > $precision) { my $digit = int $radix * $value - $lower_bound; $value = $radix * $value - $digit; $result .= '.' unless $place or not index($result, '.'); $result .= $digit == -$radix ? todigitstring($digit-1, -$radix) . '0' : (todigitstring($digit, -$radix) or '0'); $place--; } $result } sub base_c { my($num, $radix, $precision) = @_; die "Base $radix out of range" unless (-6 <= $radix->Im or $radix->Im <= -2) or (2 <= $radix->Im or $radix->Im <= 6); my ($re,$im); defined $num->Im ? ($re, $im) = ($num->Re, $num->Im) : $re = $num; my ($re_wh, $re_fr) = split /\./, base_i( $re, -1 * int($radix->Im**2), $precision); my ($im_wh, $im_fr) = split /\./, base_i( ($im/($radix->Im)), -1 * int($radix->Im**2), $precision); $_ //= '' for $re_fr, $im_fr; my $whole = reverse zip scalar reverse($re_wh), scalar reverse($im_wh); my $fraction = zip $im_fr, $re_fr; $fraction eq 0 ? "$whole" : "$whole.$fraction" } sub parse_base { my($str, $radix) = @_; return -1 * parse_base( substr($str,1), $radix) if substr($str,0,1) eq '-'; my($whole, $frac) = split /\./, $str; my $fraction = 0; my $k = 0; $fraction = sum map { (fromdigits($_, int $radix->Im**2) || 0) * $radix ** -($k++ +1) } split '', $frac if $frac; $k = 0; $fraction + sum map { (fromdigits($_, int $radix->Im**2) || 0) * $radix ** $k++ } reverse split '', $whole; } for ( [ 0*i, 2*i], [1+0*i, 2*i], [5+0*i, 2*i], [ -13+0*i, 2*i], [ 9*i, 2*i], [ -3*i, 2*i], [7.75-7.5*i, 2*i], [0.25+0*i, 2*i], [5+5*i, 2*i], [5+5*i, 3*i], [5+5*i, 4*i], [5+5*i, 5*i], [5+5*i, 6*i], [5+5*i, -2*i], [5+5*i, -3*i], [5+5*i, -4*i], [5+5*i, -5*i], [5+5*i, -6*i] ) { my($v,$r) = @$_; my $ibase = base_c($v, $r, -6); my $rt = cplx parse_base($ibase, $r); $rt->display_format('format' => '%.2f'); printf "base(%3s):%10s =>%9s =>%13s\n", $r, $v, $ibase, $rt; } say ''; say 'base( 6i): 31432.6219135802-2898.5266203704*i => ' . base_c(31432.6219135802-2898.5266203704*i, 0+6*i, -3);
720Imaginary base numbers
2perl
w63e6
import java.awt.*; import java.awt.event.*; import java.awt.image.*; import java.util.Arrays; import java.util.Random; import javax.swing.*; public class ImageNoise { int framecount = 0; int fps = 0; BufferedImage image; Kernel kernel; ConvolveOp cop; JFrame frame = new JFrame("Java Image Noise"); JPanel panel = new JPanel() { private int show_fps = 0;
722Image noise
9java
nulih
null
708Inverted index
15rust
4q35u
char * incr(char *s) { int i, begin, tail, len; int neg = (*s == '-'); char tgt = neg ? '0' : '9'; if (!strcmp(s, )) { s[0] = '0', s[1] = '\0'; return s; } len = strlen(s); begin = (*s == '-' || *s == '+') ? 1 : 0; for (tail = len - 1; tail >= begin && s[tail] == tgt; tail--); if (tail < begin && !neg) { if (!begin) s = realloc(s, len + 2); s[0] = '1'; for (i = 1; i <= len - begin; i++) s[i] = '0'; s[len + 1] = '\0'; } else if (tail == begin && neg && s[1] == '1') { for (i = 1; i < len - begin; i++) s[i] = '9'; s[len - 1] = '\0'; } else { for (i = len - 1; i > tail; i--) s[i] = neg ? '9' : '0'; s[tail] += neg ? -1 : 1; } return s; } void string_test(const char *s) { char *ret = malloc(strlen(s)); strcpy(ret, s); printf(, ret); printf(, ret = incr(ret)); free(ret); } int main() { string_test(); string_test(); string_test(); string_test(); string_test(); string_test(); string_test(); string_test(); return 0; }
727Increment a numerical string
5c
781rg
package Animal; 1;
712Inheritance/Single
2perl
9bqmn
class Animal { } class Dog extends Animal { } class Cat extends Animal { } class Lab extends Dog { } class Collie extends Dog { }
712Inheritance/Single
12php
w6vep
const starttxt = """ ATTENTION ALL WUMPUS LOVERS!!! THERE ARE NOW TWO ADDITIONS TO THE WUMPUS FAMILY OF PROGRAMS. WUMP2: SOME DIFFERENT CAVE ARRANGEMENTS WUMP3: DIFFERENT HAZARDS """ const helptxt = """ WELCOME TO 'HUNT THE WUMPUS' THE WUMPUS LIVES IN A CAVE OF 20 ROOMS. EACH ROOM HAS 3 TUNNELS LEADING TO OTHER ROOMS. (LOOK AT A DODECAHEDRON TO SEE HOW THIS WORKS-IF YOU DON'T KNOW WHAT A DODECAHEDRON IS, ASK SOMEONE) HAZARDS: BOTTOMLESS PITS - TWO ROOMS HAVE BOTTOMLESS PITS IN THEM IF YOU GO THERE, YOU FALL INTO THE PIT (& LOSE!) SUPER BATS - TWO OTHER ROOMS HAVE SUPER BATS. IF YOU GO THERE, A BAT GRABS YOU AND TAKES YOU TO SOME OTHER ROOM AT RANDOM. (WHICH MIGHT BE TROUBLESOME) WUMPUS: THE WUMPUS IS NOT BOTHERED BY THE HAZARDS (HE HAS SUCKER FEET AND IS TOO BIG FOR A BAT TO LIFT). USUALLY HE IS ASLEEP. TWO THINGS WAKE HIM UP: YOUR ENTERING HIS ROOM OR YOUR SHOOTING AN ARROW. IF THE WUMPUS WAKES, HE MOVES (P=.75) ONE ROOM OR STAYS STILL (P=.25). AFTER THAT, IF HE IS WHERE YOU ARE, HE EATS YOU UP (& YOU LOSE!) YOU: EACH TURN YOU MAY MOVE OR SHOOT A CROOKED ARROW MOVING: YOU CAN GO ONE ROOM (THRU ONE TUNNEL) ARROWS: YOU HAVE 5 ARROWS. YOU LOSE WHEN YOU RUN OUT. EACH ARROW CAN GO FROM 1 TO 5 ROOMS. YOU AIM BY TELLING THE COMPUTER THE ROOM#S YOU WANT THE ARROW TO GO TO. IF THE ARROW CAN'T GO THAT WAY (IE NO TUNNEL) IT MOVES AT RANDOM TO THE NEXT ROOM. IF THE ARROW HITS THE WUMPUS, YOU WIN. IF THE ARROW HITS YOU, YOU LOSE. WARNINGS: WHEN YOU ARE ONE ROOM AWAY FROM WUMPUS OR HAZARD, THE COMPUTER SAYS: WUMPUS- 'I SMELL A WUMPUS' BAT - 'BATS NEARBY' PIT - 'I FEEL A DRAFT' """ function queryprompt(query, choices, choicetxt="") carr = map(x -> uppercase(strip(string(x))), collect(choices)) while true print(query, " ", choicetxt == ""? carr: choicetxt, ": ") choice = uppercase(strip(readline(stdin))) if choice in carr return choice end println() end end function wumpushunt(cheatmode = false) println(starttxt) arrows = 5 rooms = Vector{Vector{Int}}() push!(rooms, [2,6,5], [3,8,1], [4,10,2], [5,2,3], [1,14,4], [15,1,7], [17,6,8], [7,2,9], [18,8,10], [9,3,11], [19,10,12], [11,4,13], [20,12,14], [5,11,13], [6,16,14], [20,15,17], [16,7,18], [17,9,19], [18,11,20], [19,13,16]) roomcontents = shuffle(push!(fill("Empty", 15), "Bat", "Bat", "Pit", "Pit", "Wumpus")) randnextroom(room) = rand(rooms[room]) newplayerroom(cr, range = 40) = (for i in 1:range cr = randnextroom(cr) end; cr) function senseroom(p) linkedrooms = rooms[p] if cheatmode println("linked rooms are $(rooms[p]), which have $(roomcontents[rooms[p][1]]), $(roomcontents[rooms[p][2]]), $(roomcontents[rooms[p][3]])") end if any(x -> roomcontents[x] == "Wumpus", linkedrooms) println("I SMELL A WUMPUS!") end if any(x -> roomcontents[x] == "Pit", linkedrooms) println("I FEEL A DRAFT") end if any(x -> roomcontents[x] == "Bat", linkedrooms) println("BATS NEARBY!") end end function arrowflight(arrowroom) if roomcontents[arrowroom] == "Wumpus" println("AHA! YOU GOT THE WUMPUS!") return("win") elseif any(x -> roomcontents[x] == "Wumpus", rooms[arrowroom]) numrooms = rand([0, 1, 2, 3]) if numrooms > 0 println("...OOPS! BUMPED A WUMPUS!") wroom = rooms[arrowroom][findfirst(x -> roomcontents[x] == "Wumpus", rooms[arrowroom])] for i in 1:3 tmp = wroom wroom = rand(rooms[wroom]) if wroom == playerroom println("TSK TSK TSK- WUMPUS GOT YOU!") return "lose" else roomcontents[tmp] = roomcontents[wroom] roomcontents[wroom] = "Wumpus" end end end elseif arrowroom == playerroom println("OUCH! ARROW GOT YOU!") return "lose" end return "" end println("HUNT THE WUMPUS") playerroom = 1 while true playerroom = newplayerroom(playerroom) if roomcontents[playerroom] == "Empty" break end end while arrows > 0 senseroom(playerroom) println("YOU ARE IN ROOM $playerroom. TUNNELS LEAD TO ", join(rooms[playerroom], ";")) choice = queryprompt("SHOOT OR MOVE (H FOR HELP)", ["S", "M", "H"]) if choice == "M" choice = queryprompt("WHERE TO", rooms[playerroom]) playerroom = parse(Int, choice) if roomcontents[playerroom] == "Wumpus" println("TSK TSK TSK- WUMPUS GOT YOU!") return "lose" elseif roomcontents[playerroom] == "Pit" println("YYYIIIIEEEE . . . FELL IN PIT") return "lose" elseif roomcontents[playerroom] == "Bat" senseroom(playerroom) println("ZAP--SUPER BAT SNATCH! ELSEWHEREVILLE FOR YOU!") playerroom = newplayerroom(playerroom, 10) end elseif choice == "S" distance = parse(Int, queryprompt("NO. OF ROOMS(1-5)", 1:5)) choices = zeros(Int, 5) arrowroom = playerroom for i in 1:distance choices[i] = parse(Int, queryprompt("ROOM #", 1:20, "1-20")) while i > 2 && choices[i] == choices[i-2] println("ARROWS AREN'T THAT CROOKED - TRY ANOTHER ROOM") choices[i] = parse(Int, queryprompt("ROOM #", 1:20, "1-20")) end arrowroom = choices[i] end arrowroom = playerroom for rm in choices if rm!= 0 if!(rm in rooms[arrowroom]) rm = rand(rooms[arrowroom]) end arrowroom = rm if (ret = arrowflight(arrowroom))!= "" return ret end end end arrows -= 1 println("MISSED") elseif choice == "H" println(helptxt) end end println("OUT OF ARROWS.\nHA HA HA - YOU LOSE!") return "lose" end while true result = wumpushunt() println("Game over. You $(result)!") if queryprompt("Play again?", ["Y", "N"]) == "N" break end end
724Hunt the Wumpus
10javascript
ivmol
<body> <canvas id='c'></canvas> <script> var canvas = document.getElementById('c'); var ctx = canvas.getContext('2d'); var w = canvas.width = 320; var h = canvas.height = 240; var t1 = new Date().getTime(); var frame_count = 0; ctx.font = 'normal 400 24px/2 Unknown Font, sans-serif'; var img = ctx.createImageData(w, h); var index_init = 0; for (var x = 0; x < w; x++) { for (var y = 0; y < h; y++) { img.data[index_init + 3] = 255;
722Image noise
10javascript
374z0
null
710Integer overflow
17swift
himj0
lines = {} str = io.read() while str do table.insert(lines,str) str = io.read() end
713Input loop
1lua
zrpty
object InvertedIndex extends App { import java.io.File
708Inverted index
16scala
78mr9
exit if RUBY_VERSION < '1.8.6' puts bloop.abs if defined?(bloop) and bloop.respond_to?(:abs)
709Introspection
14ruby
bdlkq
import math import re def inv(c): denom = c.real * c.real + c.imag * c.imag return complex(c.real / denom, -c.imag / denom) class QuaterImaginary: twoI = complex(0, 2) invTwoI = inv(twoI) def __init__(self, str): if not re.match(, str) or str.count('.') > 1: raise Exception('Invalid base 2i number') self.b2i = str def toComplex(self): pointPos = self.b2i.find('.') posLen = len(self.b2i) if (pointPos < 0) else pointPos sum = complex(0, 0) prod = complex(1, 0) for j in xrange(0, posLen): k = int(self.b2i[posLen - 1 - j]) if k > 0: sum += prod * k prod *= QuaterImaginary.twoI if pointPos != -1: prod = QuaterImaginary.invTwoI for j in xrange(posLen + 1, len(self.b2i)): k = int(self.b2i[j]) if k > 0: sum += prod * k prod *= QuaterImaginary.invTwoI return sum def __str__(self): return str(self.b2i) def toQuaterImaginary(c): if c.real == 0.0 and c.imag == 0.0: return QuaterImaginary() re = int(c.real) im = int(c.imag) fi = -1 ss = while re != 0: re, rem = divmod(re, -4) if rem < 0: rem += 4 re += 1 ss += str(rem) + '0' if im != 0: f = c.imag / 2 im = int(math.ceil(f)) f = -4 * (f - im) index = 1 while im != 0: im, rem = divmod(im, -4) if rem < 0: rem += 4 im += 1 if index < len(ss): ss[index] = str(rem) else: ss += '0' + str(rem) index = index + 2 fi = int(f) ss = ss[::-1] if fi != -1: ss += '.' + str(fi) ss = ss.lstrip('0') if ss[0] == '.': ss = '0' + ss return QuaterImaginary(ss) for i in xrange(1,17): c1 = complex(i, 0) qi = toQuaterImaginary(c1) c2 = qi.toComplex() print .format(c1, qi, c2), c1 = -c1 qi = toQuaterImaginary(c1) c2 = qi.toComplex() print .format(c1, qi, c2) print for i in xrange(1,17): c1 = complex(0, i) qi = toQuaterImaginary(c1) c2 = qi.toComplex() print .format(c1, qi, c2), c1 = -c1 qi = toQuaterImaginary(c1) c2 = qi.toComplex() print .format(c1, qi, c2) print
720Imaginary base numbers
3python
xy6wr
null
722Image noise
11kotlin
s96q7
use strict; use warnings; use PDL; use PDL::Image2D; my $kernel = pdl [[-2, -1, 0],[-1, 1, 1], [0, 1, 2]]; my $image = rpic 'pythagoras_tree.png'; my $smoothed = conv2d $image, $kernel, {Boundary => 'Truncate'}; wpic $smoothed, 'pythagoras_convolution.png';
721Image convolution
2perl
0cms4
object VersCheck extends App { val minimalVersion = 1.7 val vers = System.getProperty("java.specification.version"); println(if (vers.toDouble >= minimalVersion) "YAY!" else s"Must use Java >= $minimalVersion"); val bloop = Option(-42) if (bloop.isDefined) bloop.get.abs }
709Introspection
16scala
e35ab
>>> def j(n, k): p, i, seq = list(range(n)), 0, [] while p: i = (i+k-1)% len(p) seq.append(p.pop(i)) return 'Prisoner killing order:%s.\nSurvivor:%i'% (', '.join(str(i) for i in seq[:-1]), seq[-1]) >>> print(j(5, 2)) Prisoner killing order: 1, 3, 0, 4. Survivor: 2 >>> print(j(41, 3)) Prisoner killing order: 2, 5, 8, 11, 14, 17, 20, 23, 26, 29, 32, 35, 38, 0, 4, 9, 13, 18, 22, 27, 31, 36, 40, 6, 12, 19, 25, 33, 39, 7, 16, 28, 37, 10, 24, 1, 21, 3, 34, 15. Survivor: 30 >>>
702Josephus problem
3python
37nzc
null
723Include a file
0go
xytwf
class Animal: pass class Dog(Animal): pass class Cat(Animal): pass class Lab(Dog): pass class Collie(Dog): pass
712Inheritance/Single
3python
cps9q
aCollie <- "woof" class(aCollie) <- c("Collie", "Dog", "Animal")
712Inheritance/Single
13r
6je3e
use strict; use warnings; use List::Util qw( shuffle ); $| = 1; my %tunnels = qw(A BKT B ACL C BDM D CEN E DFO F EGP G FHQ H GIR I HJS J IKT K AJL L BKM M CLN N DMO O ENP P FOQ Q GPR R HQS S IRT T AJS); my ($you, $wumpus, $bat1, $bat2, $pit1, $pit2) = shuffle keys %tunnels; my $arrows = 5; print "\nTo shoot, enter a 's' and upper case letter of the desired tunnel. To move, just enter the upper case letter of the desired tunnel.\n"; while( 1 ) { my @adj = split //, my $adj = $tunnels{$you}; print "\nYou are in room $you and see three tunnels: @adj\n"; $adj =~ /$bat1|$bat2/ and print "You hear a rustling.\n"; $adj =~ /$pit1|$pit2/ and print "You feel a cold wind blowing from a nearby cavern.\n"; $adj =~ $wumpus and print "You smell something terrible nearby.\n"; print "(m)ove or (s)hoot (tunnel): "; defined($_ = <>) or exit; if( /s.*([$adj])/ ) { $1 eq $wumpus and exit !print "\nYou killed the Wumpus and won the game.\n"; $wumpus = substr $wumpus . $tunnels{$wumpus}, rand 4, 1; $wumpus eq $you and die "\nYou were eaten by a Wumpus and lost the game.\n"; --$arrows or die "\nYou ran out of arrows and lost the game.\n"; } elsif( /([$adj])/ ) { $you = $1; $wumpus eq $you and die "\nYou were eaten by a Wumpus and lost the game.\n"; "$pit1$pit2" =~ $you and die "\nYou fell into a bottomless pit and lost the game.\n"; "$bat1$bat2" =~ $you and (($you) = shuffle grep !/$you|$wumpus|$pit1|$pit2|$bat1|$bat2/, keys %tunnels), print "\nA giant bat has carried you to room $you.\n"; } else { print "I don't understand:(\n"; } }
724Hunt the Wumpus
2perl
mkgyz
from PIL import Image, ImageFilter if __name__==: im = Image.open() kernelValues = [-2,-1,0,-1,1,1,0,1,2] kernel = ImageFilter.Kernel((3,3), kernelValues) im2 = im.filter(kernel) im2.show()
721Image convolution
3python
8l90o
package main import "fmt" func main() { for i := 1;; i++ { fmt.Println(i) } }
714Integer sequence
0go
5xoul
%{ int cie, cei, ie, ei; %} %% cie ++cie, ++ie; cei ++cei, ++ei; ie ++ie; ei ++ei; .|\n ; %% int main() { cie = cei = ie = ei = 0; yylex(); printf(,, (2*ei < ie ? : )); printf(,, (2*cie < cei ? : )); printf(,, (2*(cie+ei) < (cei+ie) ? : )); return 0; }
728I before E except after C
5c
f4yd3
(str (inc (Integer/parseInt "1234")))
727Increment a numerical string
6clojure
pfqbd
(let [[a b] (repeatedly read)] (doseq [[op string] [[< "less than"] [> "greater than"] [= "equal to"]]] (when (op a b) (println (str a " is " string " " b)))))
725Integer comparison
6clojure
l17cb
import SomeModule #include "SomeModule.hs"
723Include a file
8haskell
yhg66
int valid_cc(const char *iban, int len) { V(, 28); V(, 24); V(, 20); V(, 28); V(, 16); V(, 22); V(, 20); V(, 29); V(, 22); V(, 21); V(, 21); V(, 28); V(, 24); V(, 18); V(, 28); V(, 20); V(, 18); V(, 18); V(, 27); V(, 22); V(, 22); V(, 23); V(, 27); V(, 18); V(, 28); V(, 28); V(, 26); V(, 22); V(, 23); V(, 27); V(, 20); V(, 30); V(, 21); V(, 28); V(, 21); V(, 20); V(, 20); V(, 19); V(, 31); V(, 27); V(, 30); V(, 27); V(, 24); V(, 22); V(, 18); V(, 15); V(, 24); V(, 29); V(, 28); V(, 25); V(, 24); V(, 27); V(, 24); V(, 22); V(, 24); V(, 19); V(, 24); V(, 24); V(, 21); V(, 24); V(, 26); V(, 23); V(, 22); V(, 24); return 0; } int strip(char *s) { int i = -1, m = 0; while(s[++i]) { s[i - m] = s[i]; m += s[i] <= 32; } s[i - m] = 0; return i - m; } int mod97(const char *s, int len) { int i, j, parts = len / 7; char rem[10] = ; for (i = 1; i <= parts + (len % 7 != 0); ++i) { strncpy(rem + 2, s + (i - 1) * 7, 7); j = atoi(rem) % 97; rem[0] = j / 10 + '0'; rem[1] = j % 10 + '0'; } return atoi(rem) % 97; } int valid_iban(char *iban) { int i, j, l = 0, sz = strip(iban); char *rot, *trans; for (i = 0; i < sz; ++i) { if (!isdigit(iban[i]) && !isupper(iban[i])) return 0; l += !!isupper(iban[i]); } if (!valid_cc(iban, sz)) return 0; rot = alloca(sz); strcpy(rot, iban + 4); strncpy(rot + sz - 4, iban, 4); trans = alloca(sz + l + 1); trans[sz + l] = 0; for (i = j = 0; i < sz; ++i, ++j) { if (isdigit(rot[i])) trans[j] = rot[i]; else { trans[j] = (rot[i] - 55) / 10 + '0'; trans[++j] = (rot[i] - 55) % 10 + '0'; } } return mod97(trans, sz + l) == 1; } int main(int _, char **argv) { while (--_, *++argv) printf(, *argv, valid_iban(*argv) ? : ); return 0; }
729IBAN
5c
0cnst
def base2i_decode(qi) return 0 if qi == '0' md = qi.match(/^(?<int>[0-3]+)(?:\.(?<frc>[0-3]+))?$/) raise 'ill-formed quarter-imaginary base value' if!md ls_pow = md[:frc]? -(md[:frc].length): 0 value = 0 (md[:int] + (md[:frc]? md[:frc]: '')).reverse.each_char.with_index do |dig, inx| value += dig.to_i * (2i)**(inx + ls_pow) end return value end def base2i_encode(gi) odd = gi.imag.to_i.odd? frac = (gi.imag.to_i!= 0) real = gi.real.to_i imag = (gi.imag.to_i + 1) / 2 value = '' phase_real = true while (real!= 0) || (imag!= 0) if phase_real real, rem = real.divmod(4) real = -real else imag, rem = imag.divmod(4) imag = -imag end value.prepend(rem.to_s) phase_real =!phase_real end value = '0' if value == '' value.concat(odd? '.2': '.0') if frac return value end
720Imaginary base numbers
14ruby
s9mqw
null
714Integer sequence
7groovy
cpx9i
my $x = 0 + "inf"; my $y = 0 + "+inf";
716Infinity
2perl
f47d7
jose <-function(s, r,n){ y <- 0:(r-1) for (i in (r+1):n) y <- (y + s) %% i return(y) } > jose(3,1,41) [1] 30
702Josephus problem
13r
d50nt
class Animal def self.inherited(subclass) puts end end class Dog < Animal end class Cat < Animal end class Lab < Dog end class Collie < Dog end
712Inheritance/Single
14ruby
2a8lw
trait Animal {} trait Cat: Animal {} trait Dog: Animal {} trait Lab: Dog {} trait Collie: Dog {}
712Inheritance/Single
15rust
veo2t
class Animal class Dog extends Animal class Cat extends Animal class Lab extends Dog class Collie extends Dog
712Inheritance/Single
16scala
4qd50
class Pixmap def convolute(kernel) newimg = Pixmap.new(@width, @height) pb = ProgressBar.new(@width) if $DEBUG @width.times do |x| @height.times do |y| apply_kernel(x, y, kernel, newimg) end pb.update(x) if $DEBUG end pb.close if $DEBUG newimg end def apply_kernel(x, y, kernel, newimg) x0 = x==0? 0: x-1 y0 = y==0? 0: y-1 x1 = x y1 = y x2 = x+1==@width ? x: x+1 y2 = y+1==@height? y: y+1 r = g = b = 0.0 [x0, x1, x2].zip(kernel).each do |xx, kcol| [y0, y1, y2].zip(kcol).each do |yy, k| r += k * self[xx,yy].r g += k * self[xx,yy].g b += k * self[xx,yy].b end end newimg[x,y] = RGBColour.new(luma(r), luma(g), luma(b)) end def luma(value) if value < 0 0 elsif value > 255 255 else value end end end teapot = Pixmap.open('teapot.ppm') [ ['Emboss', [[-2.0, -1.0, 0.0], [-1.0, 1.0, 1.0], [0.0, 1.0, 2.0]]], ['Sharpen', [[-1.0, -1.0, -1.0], [-1.0, 9.0, -1.0], [-1.0, -1.0, -1.0]]], ['Blur', [[0.1111,0.1111,0.1111],[0.1111,0.1111,0.1111],[0.1111,0.1111,0.1111]]], ].each do |label, kernel| savefile = 'teapot_' + label.downcase + '.ppm' teapot.convolute(kernel).save(savefile) end
721Image convolution
14ruby
ivloh
INF
716Infinity
12php
hifjf
public class Class1 extends Class2 {
723Include a file
9java
d5ln9
var s = document.createElement('script'); s.type = 'application/javascript';
723Include a file
10javascript
6j438
for i in `seq $1`;do printf '%*s\n' $1|tr ' ' '0'|sed "s/0/1/$i";done
730Identity matrix
4bash
ivfop
import random class WumpusGame(object): def __init__(self, edges=[]): if edges: cave = {} N = max([edges[i][0] for i in range(len(edges))]) for i in range(N): exits = [edge[1] for edge in edges if edge[0] == i] cave[i] = exits else: cave = {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]} self.cave = cave self.threats = {} self.arrows = 5 self.arrow_travel_distance = 5 self.player_pos = -1 def get_safe_rooms(self): return list(set(self.cave.keys()).difference(self.threats.keys())) def populate_cave(self): for threat in ['bat', 'bat', 'pit', 'pit', 'wumpus']: pos = random.choice(self.get_safe_rooms()) self.threats[pos] = threat self.player_pos = random.choice(self.get_safe_rooms()) def breadth_first_search(self, source, target, max_depth=5): graph = self.cave depth = 0 def search(stack, visited, target, depth): if stack == []: return False, -1 if target in stack: return True, depth visited = visited + stack stack = list(set([graph[v][i] for v in stack for i in range(len(graph[v]))]).difference(visited)) depth += 1 if depth > max_depth: return False, depth else: return search(stack, visited, target, depth) return search([source], [], target, depth) def print_warning(self, threat): if threat == 'bat': print() elif threat == 'pit': print() elif threat == 'wumpus': print() def get_players_input(self): while 1: inpt = input() try: mode = str(inpt).lower() assert mode in ['s', 'm', 'q'] break except (ValueError, AssertionError): print() if mode == 'q': return 'q', 0 while 1: inpt = input() try: target = int(inpt) except ValueError: print() continue if mode == 'm': try: assert target in self.cave[self.player_pos] break except AssertionError: print() elif mode == 's': try: bfs = self.breadth_first_search(self.player_pos, target) assert bfs[0] == True break except AssertionError: if bfs[1] == -1: print() target = random.choice(self.cave.keys()) if bfs[1] > self.arrow_travel_distance: print() return mode, target def enter_room(self, room_number): print(.format(room_number)) if self.threats.get(room_number) == 'bat': print() new_pos = random.choice(self.get_safe_rooms()) return self.enter_room(new_pos) elif self.threats.get(room_number) == 'wumpus': print() return -1 elif self.threats.get(room_number) == 'pit': print() return -1 for i in self.cave[room_number]: self.print_warning(self.threats.get(i)) return room_number def shoot_room(self, room_number): print(.format(room_number)) self.arrows -= 1 threat = self.threats.get(room_number) if threat in ['bat', 'wumpus']: del self.threats[room_number] if threat == 'wumpus': print() return -1 elif threat == 'bat': print() elif threat in ['pit', None]: print() if self.arrows < 1: print() return -1 if random.random() < 0.75: for room_number, threat in self.threats.items(): if threat == 'wumpus': wumpus_pos = room_number new_pos = random.choice(list(set(self.cave[wumpus_pos]).difference(self.threats.keys()))) del self.threats[room_number] self.threats[new_pos] = 'wumpus' if new_pos == self.player_pos: print() return -1 return self.player_pos def gameloop(self): print() print() print() self.populate_cave() self.enter_room(self.player_pos) while 1: print(.format(self.player_pos), end=) print(.format(*self.cave[self.player_pos])) inpt = self.get_players_input() print() if inpt[0] == 'm': target = inpt[1] self.player_pos = self.enter_room(target) elif inpt[0] == 's': target = inpt[1] self.player_pos = self.shoot_room(target) elif inpt[0] == 'q': self.player_pos = -1 if self.player_pos == -1: break print() print() if __name__ == '__main__': WG = WumpusGame() WG.gameloop()
724Hunt the Wumpus
3python
9brmf
mapM_ print [1..]
714Integer sequence
8haskell
xy2w4
(ns i-before-e.core (:require [clojure.string:as s]) (:gen-class)) (def patterns {:cie #"cie":ie #"(?<!c)ie":cei #"cei":ei #"(?<!c)ei"}) (defn update-counts "Given a map of counts of matching patterns and a word, increment any count if the word matches it's pattern." [counts [word freq]] (apply hash-map (mapcat (fn [[k v]] [k (if (re-seq (patterns k) word) (+ freq v) v)]) counts))) (defn count-ie-ei-combinations "Update counts of all ie and ei combinations" [words] (reduce update-counts {:ie 0:cie 0:ei 0:cei 0} words)) (defn apply-freq-1 "Apply a frequency of one to words" [words] (map #(vector % 1) words)) (defn- format-plausible [plausible?] (if plausible? "plausible" "implausible")) (defn- apply-rule [desc examples contra] (let [plausible? (<= (* 2 contra) examples)] (println (format "The sub rule%s is%s. There are%d examples and%d counter-examples.\n" desc (format-plausible plausible?) examples contra)) plausible?)) (defn i-before-e-except-after-c-plausible? "Check if i before e after c plausible?" [description words] (do (println description) (let [counts (count-ie-ei-combinations words) subrule1 (apply-rule "I before E when not preceeded by C" (:ie counts) (:ei counts)) subrule2 (apply-rule "E before I when preceeded by C" (:cei counts) (:cie counts)) rule (and subrule1 subrule2)] (println (format "Overall the rule 'I before E except after C' is%s" (format-plausible rule))) rule))) (defn format-freq-line [line] (letfn [(format-line [xs] [(first xs) (read-string (last xs))])] (-> line s/trim (s/split #"\s") format-line))) (defn -main [] (with-open [rdr (clojure.java.io/reader "http://wiki.puzzlers.org/pub/wordlists/unixdict.txt")] (i-before-e-except-after-c-plausible? "Check unixdist list" (apply-freq-1 (line-seq rdr)))) (with-open [rdr (clojure.java.io/reader "http://ucrel.lancs.ac.uk/bncfreq/lists/1_2_all_freq.txt")] (i-before-e-except-after-c-plausible? "Word frequencies (stretch goal)" (map format-freq-line (drop 1 (line-seq rdr))))))
728I before E except after C
6clojure
yh26b
fun f() = println("f called")
723Include a file
11kotlin
0c6sf
class Animal {
712Inheritance/Single
17swift
l10c2
package main import ( "fmt" "math/big" ) var ( one = new(big.Int).SetUint64(1) two = new(big.Int).SetUint64(2) three = new(big.Int).SetUint64(3) five = new(big.Int).SetUint64(5) seven = new(big.Int).SetUint64(7) ten = new(big.Int).SetUint64(10) ) func min(a, b *big.Int) *big.Int { if a.Cmp(b) < 0 { return a } return b } func humble(n int) []*big.Int { h := make([]*big.Int, n) h[0] = new(big.Int).Set(one) next2, next3 := new(big.Int).Set(two), new(big.Int).Set(three) next5, next7 := new(big.Int).Set(five), new(big.Int).Set(seven) var i, j, k, l int for m := 1; m < len(h); m++ { h[m] = new(big.Int).Set(min(next2, min(next3, min(next5, next7)))) if h[m].Cmp(next2) == 0 { i++ next2.Mul(two, h[i]) } if h[m].Cmp(next3) == 0 { j++ next3.Mul(three, h[j]) } if h[m].Cmp(next5) == 0 { k++ next5.Mul(five, h[k]) } if h[m].Cmp(next7) == 0 { l++ next7.Mul(seven, h[l]) } } return h } func commatize(n int) string { s := fmt.Sprintf("%d", n) le := len(s) for i := le - 3; i >= 1; i -= 3 { s = s[0:i] + "," + s[i:] } return s } func main() { const n = 13 * 1e6
726Humble numbers
0go
xynwf
>>> float('infinity') inf
716Infinity
3python
tgjfw
(def explen {"AL" 28 "AD" 24 "AT" 20 "AZ" 28 "BE" 16 "BH" 22 "BA" 20 "BR" 29 "BG" 22 "CR" 21 "HR" 21 "CY" 28 "CZ" 24 "DK" 18 "DO" 28 "EE" 20 "FO" 18 "FI" 18 "FR" 27 "GE" 22 "DE" 22 "GI" 23 "GR" 27 "GL" 18 "GT" 28 "HU" 28 "IS" 26 "IE" 22 "IL" 23 "IT" 27 "KZ" 20 "KW" 30 "LV" 21 "LB" 28 "LI" 21 "LT" 20 "LU" 20 "MK" 19 "MT" 31 "MR" 27 "MU" 30 "MC" 27 "MD" 24 "ME" 22 "NL" 18 "NO" 15 "PK" 24 "PS" 29 "PL" 28 "PT" 25 "RO" 24 "SM" 27 "SA" 24 "RS" 22 "SK" 24 "SI" 19 "ES" 24 "SE" 24 "CH" 21 "TN" 24 "TR" 26 "AE" 23 "GB" 22 "VG" 24}) (defn valid-iban? [iban] (let [iban (apply str (remove #{\space \tab} iban))] (cond (not (re-find #"^[\dA-Z]+$" iban)) false (not= (explen (subs iban 0 2)) (count iban)) false :else (let [rot (flatten (apply conj (split-at 4 iban))) trans (map #(read-string (str "36r" %)) rot)] (= 1 (mod (bigint (apply str trans)) 97)))))) (prn (valid-iban? "GB82 WEST 1234 5698 7654 32") (valid-iban? "GB82 TEST 1234 5698 7654 32"))
729IBAN
6clojure
d53nb
import Data.Set (deleteFindMin, fromList, union) import Data.List.Split (chunksOf) import Data.List (group) import Data.Bool (bool) humbles :: [Integer] humbles = go $ fromList [1] where go sofar = x: go (union pruned $ fromList ((x *) <$> [2, 3, 5, 7])) where (x, pruned) = deleteFindMin sofar main :: IO () main = do putStrLn "First 50 Humble numbers:" mapM_ (putStrLn . concat) $ chunksOf 10 $ justifyRight 4 ' ' . show <$> take 50 humbles putStrLn "\nCount of humble numbers for each digit length 1-25:" mapM_ print $ take 25 $ ((,) . head <*> length) <$> group (length . show <$> humbles) justifyRight :: Int -> a -> [a] -> [a] justifyRight n c = (drop . length) <*> (replicate n c ++)
726Humble numbers
8haskell
yhu66
-- HUNT THE WUMPUS -- BY GREGORY YOB -- SenseTalk adaptation by Jonathan Gover answer with or if it is then showInstructions -- SET UP CAVE (DODECAHEDRAL NODE LIST) set rooms to [ [2,5,8],[1,3,10],[2,4,12],[3,5,14],[1,4,6], [5,7,15],[6,8,17],[1,7,9],[8,10,18],[2,9,11], [10,12,19],[3,11,13],[12,14,20],[4,13,15],[6,14,16], [15,17,20],[7,16,18],[9,17,19],[11,18,20],[13,16,19] ] -- LOCATE L ARRAY ITEMS set locations to the randomLocations set initialLocations to locations repeat -- SET set arrowCount to 5 -- RUN THE GAME put repeat -- HAZARD WARNINGS & LOCATION locationAndHazardWarnings locations, rooms -- MOVE OR SHOOT answer with or or if it is then exit all -- SHOOT if it is then shoot reference to locations, rooms, reference to arrowCount winOrLose the result if the result isn't empty then exit repeat end if -- MOVE if it is then move reference to locations, rooms winOrLose the result if the result isn't empty then exit repeat end if end repeat answer with or if it is then exit repeat answer with or if it is then set locations to initialLocations else set locations to the randomLocations set initialLocations to locations end if end repeat to handle randomLocations put 1..20 shuffled into potentialLocations set locations to { player:first item of potentialLocations, wumpus:second item of potentialLocations, pits:third to fourth items of potentialLocations, bats:fifth to sixth items of potentialLocations } return locations end randomLocations to handle winOrLose result if result is then put if result is then put return result end winOrLose -- INSTRUCTIONS to handle showInstructions answer {{ WELCOME TO 'HUNT THE WUMPUS' THE WUMPUS LIVES IN A CAVE OF 20 ROOMS. EACH ROOM HAS 3 TUNNELS LEADING TO OTHER ROOMS. (LOOK AT A DODECAHEDRON TO SEE HOW THIS WORKS-IF YOU DON'T KNOW WHAT A DODECAHEDRON IS, ASK SOMEONE) HAZARDS: BOTTOMLESS PITS - TWO ROOMS HAVE BOTTOMLESS PITS IN THEM IF YOU GO THERE, YOU FALL INTO THE PIT (& LOSE!) SUPER BATS - TWO OTHER ROOMS HAVE SUPER BATS. IF YOU GO THERE, A BAT GRABS YOU AND TAKES YOU TO SOME OTHER ROOM AT RANDOM. (WHICH MIGHT BE TROUBLESOME) WUMPUS: THE WUMPUS IS NOT BOTHERED BY THE HAZARDS (HE HAS SUCKER FEET AND IS TOO BIG FOR A BAT TO LIFT). USUALLY HE IS ASLEEP. TWO THINGS WAKE HIM UP: YOUR ENTERING HIS ROOM OR YOUR SHOOTING AN ARROW. IF THE WUMPUS WAKES, HE MOVES (P=.75) ONE ROOM OR STAYS STILL (P=.25). AFTER THAT, IF HE IS WHERE YOU ARE, HE EATS YOU UP (& YOU LOSE!) YOU: EACH TURN YOU MAY MOVE OR SHOOT A CROOKED ARROW MOVING: YOU CAN GO ONE ROOM (THRU ONE TUNNEL) ARROWS: YOU HAVE 5 ARROWS. YOU LOSE WHEN YOU RUN OUT. EACH ARROW CAN GO FROM 1 TO 5 ROOMS. YOU AIM BY TELLING THE COMPUTER THE ROOM IF THE ARROW CAN'T GO THAT WAY (IE NO TUNNEL) IT MOVES AT RANDOM TO THE NEXT ROOM. IF THE ARROW HITS THE WUMPUS, YOU WIN. IF THE ARROW HITS YOU, YOU LOSE. WARNINGS: WHEN YOU ARE ONE ROOM AWAY FROM WUMPUS OR HAZARD, THE COMPUTER SAYS: WUMPUS- 'I SMELL A WUMPUS' BAT - 'BATS NEARBY' PIT - 'I FEEL A DRAFT' }} end showInstructions -- PRINT LOCATION & HAZARD WARNINGS to handle locationAndHazardWarnings locations, rooms put empty set currentRoomNumber to locations.player set tunnelsLeadingTo to item currentRoomNumber of rooms repeat with each item of tunnelsLeadingTo if it is locations.wumpus then put if it is in locations.pits then put if it is in locations.bats then put end repeat put! put! put empty end locationAndHazardWarnings -- ARROW ROUTINE to handle shoot locations, rooms, arrowCount -- PATH OF ARROW answer from list 1..5 set numberOfRooms to it set intendedPath to [] repeat until the number of items in intendedPath equals numberOfRooms answer from list 1..20 set nextRoom to it if the number of items in intendedPath is more than 1 if nextRoom equals the penultimate item in intendedPath put next repeat end if end if insert nextRoom into intendedPath end repeat -- SHOOT ARROW set arrowLocation to locations.player repeat with pathIndex from 1 to number of items in intendedPath set nextRoom to item pathIndex of intendedPath set tunnelsLeadingTo to item arrowLocation of rooms if tunnelsLeadingTo contains nextRoom then set arrowLocation to nextRoom else -- NO TUNNEL FOR ARROW set arrowLocation to any item of tunnelsLeadingTo end if -- SEE IF ARROW IS AT L(1) OR L(2) if arrowLocation equals locations.wumpus then put return end if if arrowLocation equals locations.player then put return end if put -- MOVE WUMPUS moveWumpus reference to locations, rooms if the result is then return -- AMMO CHECK subtract 1 from arrowCount if arrowCount is 0 then put return end if end repeat end shoot -- MOVE WUMPUS ROUTINE to handle moveWumpus locations, rooms if random of 4 isn't 4 then set currentRoomNumber to locations.wumpus set tunnelsLeadingTo to item currentRoomNumber of rooms set locations.wumpus to any item of tunnelsLeadingTo end if if locations.player equals locations.wumpus then put return end if return empty end moveWumpus -- MOVE ROUTINE to handle move locations, rooms set currentRoomNumber to locations.player set tunnelsLeadingTo to item currentRoomNumber of rooms answer from list tunnelsLeadingTo set locations.player to it -- CHECK FOR HAZARDS -- WUMPUS if locations.player equals locations.wumpus then put -- MOVE WUMPUS moveWumpus reference to locations, rooms if the result is then return end if -- PIT if locations.pits contains locations.player then put return end if -- BATS if locations.bats contains locations.player then put set locations.player to any item of 1..20 end if end move
724Hunt the Wumpus
14ruby
l1jcl
use Gtk3 '-init'; use Glib qw/TRUE FALSE/; use Time::HiRes qw/ tv_interval gettimeofday/; my $time0 = [gettimeofday]; my $frames = -8; my $window = Gtk3::Window->new(); $window->set_default_size(320, 240); $window->set_border_width(0); $window->set_title("Image_noise"); $window->set_app_paintable(TRUE); my $da = Gtk3::DrawingArea->new(); $da->signal_connect('draw' => \&draw_in_drawingarea); $window->add($da); $window->show_all(); Glib::Timeout->add (1, \&update); Gtk3->main; sub draw_in_drawingarea { my ($widget, $cr, $data) = @_; $cr->set_line_width(1); for $x (1..320) { for $y (1..240) { int rand 2 ? $cr->set_source_rgb(0, 0, 0) : $cr->set_source_rgb(1, 1, 1); $cr->rectangle( $x, $y, 1, 1); $cr->stroke; } } } sub update { $da->queue_draw; my $elapsed = tv_interval( $time0, [gettimeofday] ); $frames++; printf "fps:%.1f\n", $frames/$elapsed if $frames > 5; return TRUE; }
722Image noise
2perl
uw1vr
public class Count{ public static void main(String[] args){ for(long i = 1; ;i++) System.out.println(i); } }
714Integer sequence
9java
bd6k3
Inf -Inf .Machine$double.xmax is.finite forcefinite <- function(x) ifelse(is.finite(x), x, sign(x)*.Machine$double.xmax) forcefinite(c(1, -1, 0, .Machine$double.xmax, -.Machine$double.xmax, Inf, -Inf))
716Infinity
13r
iv4o5
require "myheader"
723Include a file
1lua
8ly0e
import java.math.BigInteger; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; public class HumbleNumbers { public static void main(String[] args) { System.out.println("First 50 humble numbers:"); System.out.println(Arrays.toString(humble(50))); Map<Integer,Integer> lengthCountMap = new HashMap<>(); BigInteger[] seq = humble(1_000_000); for ( int i = 0 ; i < seq.length ; i++ ) { BigInteger humbleNumber = seq[i]; int len = humbleNumber.toString().length(); lengthCountMap.merge(len, 1, (v1, v2) -> v1 + v2); } List<Integer> sorted = new ArrayList<>(lengthCountMap.keySet()); Collections.sort(sorted); System.out.printf("Length Count%n"); for ( Integer len : sorted ) { System.out.printf(" %2s %5s%n", len, lengthCountMap.get(len)); } } private static BigInteger[] humble(int n) { BigInteger two = BigInteger.valueOf(2); BigInteger twoTest = two; BigInteger three = BigInteger.valueOf(3); BigInteger threeTest = three; BigInteger five = BigInteger.valueOf(5); BigInteger fiveTest = five; BigInteger seven = BigInteger.valueOf(7); BigInteger sevenTest = seven; BigInteger[] results = new BigInteger[n]; results[0] = BigInteger.ONE; int twoIndex = 0, threeIndex = 0, fiveIndex = 0, sevenIndex = 0; for ( int index = 1 ; index < n ; index++ ) { results[index] = twoTest.min(threeTest).min(fiveTest).min(sevenTest); if ( results[index].compareTo(twoTest) == 0 ) { twoIndex++; twoTest = two.multiply(results[twoIndex]); } if (results[index].compareTo(threeTest) == 0 ) { threeIndex++; threeTest = three.multiply(results[threeIndex]); } if (results[index].compareTo(fiveTest) == 0 ) { fiveIndex++; fiveTest = five.multiply(results[fiveIndex]); } if (results[index].compareTo(sevenTest) == 0 ) { sevenIndex++; sevenTest = seven.multiply(results[sevenIndex]); } } return results; } }
726Humble numbers
9java
d5mn9
-- HUNT THE WUMPUS -- BY GREGORY YOB -- SenseTalk adaptation by Jonathan Gover answer "INSTRUCTIONS (Y-N)" with "No" or "Yes" if it is "Yes" then showInstructions -- SET UP CAVE (DODECAHEDRAL NODE LIST) set rooms to [ [2,5,8],[1,3,10],[2,4,12],[3,5,14],[1,4,6], [5,7,15],[6,8,17],[1,7,9],[8,10,18],[2,9,11], [10,12,19],[3,11,13],[12,14,20],[4,13,15],[6,14,16], [15,17,20],[7,16,18],[9,17,19],[11,18,20],[13,16,19] ] -- LOCATE L ARRAY ITEMS set locations to the randomLocations set initialLocations to locations repeat -- SET# ARROWS set arrowCount to 5 -- RUN THE GAME put "HUNT THE WUMPUS" repeat -- HAZARD WARNINGS & LOCATION locationAndHazardWarnings locations, rooms -- MOVE OR SHOOT answer "SHOOT OR MOVE (S-M)" with "Move" or "Shoot" or "Quit" if it is "Quit" then exit all -- SHOOT if it is "Shoot" then shoot reference to locations, rooms, reference to arrowCount winOrLose the result if the result isn't empty then exit repeat end if -- MOVE if it is "Move" then move reference to locations, rooms winOrLose the result if the result isn't empty then exit repeat end if end repeat answer "PLAY AGAIN? (Y-N)" with "No" or "Yes" if it is "No" then exit repeat answer "SAME SET-UP (Y-N)" with "No" or "Yes" if it is "Yes" then set locations to initialLocations else set locations to the randomLocations set initialLocations to locations end if end repeat to handle randomLocations put 1..20 shuffled into potentialLocations set locations to { player:first item of potentialLocations, wumpus:second item of potentialLocations, pits:third to fourth items of potentialLocations, bats:fifth to sixth items of potentialLocations } return locations end randomLocations to handle winOrLose result if result is "lose" then put "HA HA HA - YOU LOSE!" if result is "win" then put "HEE HEE HEE - THE WUMPUS'LL GETCHA NEXT TIME!!" return result end winOrLose -- INSTRUCTIONS to handle showInstructions answer {{ WELCOME TO 'HUNT THE WUMPUS' THE WUMPUS LIVES IN A CAVE OF 20 ROOMS. EACH ROOM HAS 3 TUNNELS LEADING TO OTHER ROOMS. (LOOK AT A DODECAHEDRON TO SEE HOW THIS WORKS-IF YOU DON'T KNOW WHAT A DODECAHEDRON IS, ASK SOMEONE) HAZARDS: BOTTOMLESS PITS - TWO ROOMS HAVE BOTTOMLESS PITS IN THEM IF YOU GO THERE, YOU FALL INTO THE PIT (& LOSE!) SUPER BATS - TWO OTHER ROOMS HAVE SUPER BATS. IF YOU GO THERE, A BAT GRABS YOU AND TAKES YOU TO SOME OTHER ROOM AT RANDOM. (WHICH MIGHT BE TROUBLESOME) WUMPUS: THE WUMPUS IS NOT BOTHERED BY THE HAZARDS (HE HAS SUCKER FEET AND IS TOO BIG FOR A BAT TO LIFT). USUALLY HE IS ASLEEP. TWO THINGS WAKE HIM UP: YOUR ENTERING HIS ROOM OR YOUR SHOOTING AN ARROW. IF THE WUMPUS WAKES, HE MOVES (P=.75) ONE ROOM OR STAYS STILL (P=.25). AFTER THAT, IF HE IS WHERE YOU ARE, HE EATS YOU UP (& YOU LOSE!) YOU: EACH TURN YOU MAY MOVE OR SHOOT A CROOKED ARROW MOVING: YOU CAN GO ONE ROOM (THRU ONE TUNNEL) ARROWS: YOU HAVE 5 ARROWS. YOU LOSE WHEN YOU RUN OUT. EACH ARROW CAN GO FROM 1 TO 5 ROOMS. YOU AIM BY TELLING THE COMPUTER THE ROOM#S YOU WANT THE ARROW TO GO TO. IF THE ARROW CAN'T GO THAT WAY (IE NO TUNNEL) IT MOVES AT RANDOM TO THE NEXT ROOM. IF THE ARROW HITS THE WUMPUS, YOU WIN. IF THE ARROW HITS YOU, YOU LOSE. WARNINGS: WHEN YOU ARE ONE ROOM AWAY FROM WUMPUS OR HAZARD, THE COMPUTER SAYS: WUMPUS- 'I SMELL A WUMPUS' BAT - 'BATS NEARBY' PIT - 'I FEEL A DRAFT' }} end showInstructions -- PRINT LOCATION & HAZARD WARNINGS to handle locationAndHazardWarnings locations, rooms put empty set currentRoomNumber to locations.player set tunnelsLeadingTo to item currentRoomNumber of rooms repeat with each item of tunnelsLeadingTo if it is locations.wumpus then put "I SMELL A WUMPUS!" if it is in locations.pits then put "I FEEL A DRAFT" if it is in locations.bats then put "BATS NEARBY!" end repeat put!"YOU ARE IN ROOM [[currentRoomNumber]]" put!"TUNNELS LEAD TO [[tunnelsLeadingTo joined by space]]" put empty end locationAndHazardWarnings -- ARROW ROUTINE to handle shoot locations, rooms, arrowCount -- PATH OF ARROW answer "NO. OF ROOMS(1-5)" from list 1..5 set numberOfRooms to it set intendedPath to [] repeat until the number of items in intendedPath equals numberOfRooms answer "ROOM #" from list 1..20 set nextRoom to it if the number of items in intendedPath is more than 1 if nextRoom equals the penultimate item in intendedPath put "ARROWS AREN'T THAT CROOKED - TRY ANOTHER ROOM" next repeat end if end if insert nextRoom into intendedPath end repeat -- SHOOT ARROW set arrowLocation to locations.player repeat with pathIndex from 1 to number of items in intendedPath set nextRoom to item pathIndex of intendedPath set tunnelsLeadingTo to item arrowLocation of rooms if tunnelsLeadingTo contains nextRoom then set arrowLocation to nextRoom else -- NO TUNNEL FOR ARROW set arrowLocation to any item of tunnelsLeadingTo end if -- SEE IF ARROW IS AT L(1) OR L(2) if arrowLocation equals locations.wumpus then put "AHA! YOU GOT THE WUMPUS!" return "win" end if if arrowLocation equals locations.player then put "OUCH! ARROW GOT YOU!" return "lose" end if put "MISSED" -- MOVE WUMPUS moveWumpus reference to locations, rooms if the result is "lose" then return "lose" -- AMMO CHECK subtract 1 from arrowCount if arrowCount is 0 then put "NO ARROWS LEFT" return "lose" end if end repeat end shoot -- MOVE WUMPUS ROUTINE to handle moveWumpus locations, rooms if random of 4 isn't 4 then set currentRoomNumber to locations.wumpus set tunnelsLeadingTo to item currentRoomNumber of rooms set locations.wumpus to any item of tunnelsLeadingTo end if if locations.player equals locations.wumpus then put "TSK TSK TSK- WUMPUS GOT YOU!" return "lose" end if return empty end moveWumpus -- MOVE ROUTINE to handle move locations, rooms set currentRoomNumber to locations.player set tunnelsLeadingTo to item currentRoomNumber of rooms answer "WHERE TO" from list tunnelsLeadingTo set locations.player to it -- CHECK FOR HAZARDS -- WUMPUS if locations.player equals locations.wumpus then put "...OOPS! BUMPED A WUMPUS!" -- MOVE WUMPUS moveWumpus reference to locations, rooms if the result is "lose" then return "lose" end if -- PIT if locations.pits contains locations.player then put "YYYIIIIEEEE . . . FELL IN PIT" return "lose" end if -- BATS if locations.bats contains locations.player then put "ZAP--SUPER BAT SNATCH! ELSEWHEREVILLE FOR YOU!" set locations.player to any item of 1..20 end if end move
724Hunt the Wumpus
15rust
2ahlt
var i = 0; while (true) document.write(++i + ' ');
714Integer sequence
10javascript
w6le2
a = 1.0/0 a.finite? a.infinite? a = -1/0.0 a.infinite? a = Float::MAX a.finite? a.infinite?
716Infinity
14ruby
37kz7
fn main() { let inf = f32::INFINITY; println!("{}", inf); }
716Infinity
15rust
6jb3l
val inf = Double.PositiveInfinity
716Infinity
16scala
9bam5
(() => { 'use strict';
726Humble numbers
10javascript
6jv38
import Foundation
724Hunt the Wumpus
17swift
cp79t
open FH, "< $filename" or die "can't open file: $!"; while (my $line = <FH>) { chomp $line; } close FH or die "can't close file: $!";
713Input loop
2perl
kn6hc
n = (ARGV[0] || 41).to_i k = (ARGV[1] || 3).to_i prisoners = (0...n).to_a prisoners.rotate!(k-1).shift while prisoners.length > 1 puts prisoners.first
702Josephus problem
14ruby
yhf6n
int main(int argc, char** argv) { if (argc < 2) { printf(); exit(EXIT_FAILURE); } int rowsize = atoi(argv[1]); if (rowsize < 0) { printf(); exit(EXIT_FAILURE); } int numElements = rowsize * rowsize; if (numElements < rowsize) { printf(, rowsize, numElements); abort(); } int** matrix = calloc(numElements, sizeof(int*)); if (!matrix) { printf(, numElements, sizeof(int*)); abort(); } for (unsigned int row = 0;row < rowsize;row++) { matrix[row] = calloc(numElements, sizeof(int)); if (!matrix[row]) { printf(, numElements, sizeof(int)); abort(); } matrix[row][row] = 1; } printf(); for (unsigned int row = 0;row < rowsize;row++) { for (unsigned int column = 0;column < rowsize;column++) { printf(, matrix[row][column]); } printf(); } }
730Identity matrix
5c
d5znv
import java.math.BigInteger
714Integer sequence
11kotlin
r0dgo
let inf = Double.infinity inf.isInfinite
716Infinity
17swift
zrhtu
$fh = fopen($filename, 'r'); if ($fh) { while (!feof($fh)) { $line = rtrim(fgets($fh)); } fclose($fh); }
713Input loop
12php
371zq
const N: usize = 41; const K: usize = 3; const M: usize = 3; const POSITION: usize = 5; fn main() { let mut prisoners: Vec<usize> = Vec::new(); let mut executed: Vec<usize> = Vec::new(); for pos in 0..N { prisoners.push(pos); } let mut to_kill: usize = 0; let mut len: usize = prisoners.len(); while len > M { to_kill = (to_kill + K - 1)% len; executed.push(prisoners.remove(to_kill)); len -= 1; } println!("JOSEPHUS n={}, k={}, m={}", N, K, M); println!("Executed: {:?}", executed); println!("Executed position number {}: {}", POSITION, executed[POSITION - 1]); println!("Survivors: {:?}", prisoners); }
702Josephus problem
15rust
mktya
fun isHumble(i: Int): Boolean { 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 } fun main() { val limit: Int = Short.MAX_VALUE.toInt() val humble = mutableMapOf<Int, Int>() var count = 0 var num = 1 while (count < limit) { if (isHumble(num)) { val str = num.toString() val len = str.length humble.merge(len, 1) { a, b -> a + b } if (count < 50) print("$num ") count++ } num++ } println("\n") println("Of the first $count humble numbers:") num = 1 while (num < humble.size - 1) { if (humble.containsKey(num)) { val c = humble[num] println("%5d have%2d digits".format(c, num)) num++ } else { break } } }
726Humble numbers
11kotlin
0ctsf
import time import random import Tkinter import Image, ImageTk class App(object): def __init__(self, size, root): self.root = root self.root.title() self.img = Image.new(, size) self.label = Tkinter.Label(root) self.label.pack() self.time = 0.0 self.frames = 0 self.size = size self.loop() def loop(self): self.ta = time.time() rnd = random.random white = (255, 255, 255) black = (0, 0, 0) npixels = self.size[0] * self.size[1] data = [white if rnd() > 0.5 else black for i in xrange(npixels)] self.img.putdata(data) self.pimg = ImageTk.PhotoImage(self.img) self.label[] = self.pimg self.tb = time.time() self.time += (self.tb - self.ta) self.frames += 1 if self.frames == 30: try: self.fps = self.frames / self.time except: self.fps = print (% (self.frames, self.time, self.fps)) self.time = 0 self.frames = 0 self.root.after(1, self.loop) def main(): root = Tkinter.Tk() app = App((320, 240), root) root.mainloop() main()
722Image noise
3python
5xaux
def executed( prisonerCount:Int, step:Int ) = { val prisoners = ((0 until prisonerCount) map (_.toString)).toList def behead( dead:Seq[String], alive:Seq[String] )(countOff:Int) : (Seq[String], Seq[String]) = { val group = if( alive.size < countOff ) countOff - alive.size else countOff (dead ++ alive.take(group).drop(group-1), alive.drop(group) ++ alive.take(group-1)) } def beheadN( dead:Seq[String], alive:Seq[String] ) : (Seq[String], Seq[String]) = behead(dead,alive)(step) def execute( t:(Seq[String], Seq[String]) ) : (Seq[String], Seq[String]) = t._2 match { case x :: Nil => (t._1, Seq(x)) case x :: xs => execute(beheadN(t._1,t._2)) } execute((List(),prisoners)) } val (dead,alive) = executed(41,3) println( "Prisoners executed in order:" ) print( dead.mkString(" ") ) println( "\n\nJosephus is prisoner " + alive(0) )
702Josephus problem
16scala
l16cq
function isHumble(n) local n2 = math.floor(n) if n2 <= 1 then return true end if n2 % 2 == 0 then return isHumble(n2 / 2) end if n2 % 3 == 0 then return isHumble(n2 / 3) end if n2 % 5 == 0 then return isHumble(n2 / 5) end if n2 % 7 == 0 then return isHumble(n2 / 7) end return false end function main() local limit = 10000 local humble = {0, 0, 0, 0, 0, 0, 0, 0, 0} local count = 0 local num = 1 while count < limit do if isHumble(num) then local buffer = string.format("%d", num) local le = string.len(buffer) if le > 9 then break end humble[le] = humble[le] + 1 if count < 50 then io.write(num .. " ") end count = count + 1 end num = num + 1 end print("\n") print("Of the first " .. count .. " humble numbers:") for num=1,9 do print(string.format("%5d have%d digits", humble[num], num)) end end main()
726Humble numbers
1lua
8lz0e
while(True): x = input() print(x)
713Input loop
3python
bdykr
lines <- readLines("file.txt")
713Input loop
13r
78try
'( (0 1) (2 3) )
730Identity matrix
6clojure
6j93q
require 'rubygems' require 'gl' require 'glut' W, H = 320, 240 SIZE = W * H Glut.glutInit ARGV Glut.glutInitWindowSize W, H Glut.glutIdleFunc lambda { i = Time.now noise = (1..SIZE).map { rand > 0.5? 0xFFFFFFFF: 0xFF000000 }.pack() Gl.glClear Gl::GL_COLOR_BUFFER_BIT Gl.glDrawPixels W, H, Gl::GL_RGBA, Gl::GL_UNSIGNED_BYTE, noise Gl.glFlush puts 1.0 / (Time.now - i) } Glut.glutCreateWindow Glut.glutMainLoop
722Image noise
14ruby
gsw4q
use strict; use warnings; use List::Util 'min'; use Math::GMPz; sub humble_gen { my @s = ([1], [1], [1], [1]); my @m = (2, 3, 5, 7); @m = map { Math::GMPz->new($_) } @m; return sub { my $n = min $s[0][0], $s[1][0], $s[2][0], $s[3][0]; for (0..3) { shift @{$s[$_]} if $s[$_][0] == $n; push @{$s[$_]}, $n * $m[$_] } return $n } } my $h = humble_gen; my $i = 0; my $upto = 50; my $list; ++$i, $list .= $h->(). " " until $i == $upto; print "$list\n"; $h = humble_gen; my $count = 0; my $digits = 1; while ($digits <= $upto) { ++$count and next if $digits == length $h->(); printf "Digits:%2d - Count:%s\n", $digits++, $count; $count = 1; }
726Humble numbers
2perl
5xku2
import java.awt.event.{ActionEvent, ActionListener} import swing.{Panel, MainFrame, SimpleSwingApplication} import javax.swing.Timer import java.awt.{Font, Color, Graphics2D, Dimension} object ImageNoise extends SimpleSwingApplication { var delay_ms = 2 var framecount = 0 var fps = 0 def top = new MainFrame { contents = panel } val panel = new Panel { preferredSize = new Dimension(320, 240) override def paintComponent(g: Graphics2D) { for (x <- 0 to size.width; y <- 0 to size.height) { val c = if (math.random > 0.5) Color.BLACK else Color.WHITE g.setColor(c) g.fillRect(x, y, 1, 1) } g.setColor(Color.RED) g.setFont(new Font("Monospaced", Font.BOLD, 20)) g.drawString("FPS: " + fps, size.width - 100, size.height - 10) framecount += 1 } } val repainter = new Timer(delay_ms, new ActionListener { def actionPerformed(e: ActionEvent) { panel.repaint } }) val framerateChecker = new Timer(1000, new ActionListener { def actionPerformed(e: ActionEvent) { fps = framecount framecount = 0 } }) repainter.start() framerateChecker.start() }
722Image noise
16scala
hi0ja
i = 1
714Integer sequence
1lua
78fru
class Josephus { class func lineUp(#numberOfPeople:Int) -> [Int] { var people = [Int]() for (var i = 0; i < numberOfPeople; i++) { people.append(i) } return people } class func execute(#numberOfPeople:Int, spacing:Int) -> Int { var killIndex = 0 var people = self.lineUp(numberOfPeople: numberOfPeople) println("Prisoners executed in order:") while (people.count > 1) { killIndex = (killIndex + spacing - 1)% people.count executeAndRemove(&people, killIndex: killIndex) } println() return people[0] } class func executeAndRemove(inout people:[Int], killIndex:Int) { print("\(people[killIndex]) ") people.removeAtIndex(killIndex) } class func execucteAllButM(#numberOfPeople:Int, spacing:Int, save:Int) -> [Int] { var killIndex = 0 var people = self.lineUp(numberOfPeople: numberOfPeople) println("Prisoners executed in order:") while (people.count > save) { killIndex = (killIndex + spacing - 1)% people.count executeAndRemove(&people, killIndex: killIndex) } println() return people } } println("Josephus is number: \(Josephus.execute(numberOfPeople: 41, spacing: 3))") println() println("Survivors: \(Josephus.execucteAllButM(numberOfPeople: 41, spacing: 3, save: 3))")
702Josephus problem
17swift
6jd3j
do "include.pl"; sayhello();
723Include a file
2perl
5x1u2
stream = $stdin stream.each do |line| end
713Input loop
14ruby
1t9pw
function josephus(n: number, k: number): number { if (!n) { return 1; } return ((josephus(n - 1, k) + k - 1)% n) + 1; }
702Josephus problem
20typescript
jo57l
include()
723Include a file
12php
o2m85
use std::io::{self, BufReader, Read, BufRead}; use std::fs::File; fn main() { print_by_line(io::stdin()) .expect("Could not read from stdin"); File::open("/etc/fstab") .and_then(print_by_line) .expect("Could not read from file"); } fn print_by_line<T: Read>(reader: T) -> io::Result<()> { let buffer = BufReader::new(reader); for line in buffer.lines() { println!("{}", line?) } Ok(()) }
713Input loop
15rust
azc14
scala.io.Source.fromFile("input.txt").getLines().foreach { line => ... }
713Input loop
16scala
xyvwg
package main import ( "bufio" "fmt" "log" "os" "regexp" "strings" ) func main() { f, err := os.Open("unixdict.txt") if err != nil { log.Fatalln(err) } defer f.Close() s := bufio.NewScanner(f) rie := regexp.MustCompile("^ie|[^c]ie") rei := regexp.MustCompile("^ei|[^c]ei") var cie, ie int var cei, ei int for s.Scan() { line := s.Text() if strings.Contains(line, "cie") { cie++ } if strings.Contains(line, "cei") { cei++ } if rie.MatchString(line) { ie++ } if rei.MatchString(line) { ei++ } } err = s.Err() if err != nil { log.Fatalln(err) } if check(ie, ei, "I before E when not preceded by C") && check(cei, cie, "E before I when preceded by C") { fmt.Println("Both plausable.") fmt.Println(`"I before E, except after C" is plausable.`) } else { fmt.Println("One or both implausable.") fmt.Println(`"I before E, except after C" is implausable.`) } }
728I before E except after C
0go
jo17d
package main import ( "regexp" "strings" "testing" ) var lengthByCountryCode = map[string]int{ "AL": 28, "AD": 24, "AT": 20, "AZ": 28, "BE": 16, "BH": 22, "BA": 20, "BR": 29, "BG": 22, "CR": 21, "HR": 21, "CY": 28, "CZ": 24, "DK": 18, "DO": 28, "EE": 20, "FO": 18, "FI": 18, "FR": 27, "GE": 22, "DE": 22, "GI": 23, "GR": 27, "GL": 18, "GT": 28, "HU": 28, "IS": 26, "IE": 22, "IL": 23, "IT": 27, "KZ": 20, "KW": 30, "LV": 21, "LB": 28, "LI": 21, "LT": 20, "LU": 20, "MK": 19, "MT": 31, "MR": 27, "MU": 30, "MC": 27, "MD": 24, "ME": 22, "NL": 18, "NO": 15, "PK": 24, "PS": 29, "PL": 28, "PT": 25, "RO": 24, "SM": 27, "SA": 24, "RS": 22, "SK": 24, "SI": 19, "ES": 24, "SE": 24, "CH": 21, "TN": 24, "TR": 26, "AE": 23, "GB": 22, "VG": 24, } func isValidIBAN(iban string) bool { if len(iban) < 4 { return false } iban = regexp.MustCompile(`\s+`).ReplaceAllString(iban, "") iban = strings.ToUpper(iban) if ibanLen := lengthByCountryCode[iban[0:2]]; ibanLen == len(iban) { return false } iban = iban[4:] + iban[:4] result := 0 for _, ch := range iban { var n int if '0' <= ch && ch <= '9' { n = int(ch) - '0' } else if 'A' <= ch && ch <= 'Z' { n = 10 + int(ch) - 'A' } else { return false } if n < 10 { result = (10*result + n) % 97 } else { result = (100*result + n) % 97 } } return result == 1 } func TestIsValidIBAN(t *testing.T) { tests := []struct { iban string valid bool }{ {"GB82 WEST 1234 5698 7654 32", true}, {"GB82 TEST 1234 5698 7654 32", false}, } for _, test := range tests { if isValidIBAN(test.iban) == test.valid { return } t.Errorf("Expected%q to be%v", test.iban, test.valid) } }
729IBAN
0go
uwrvt
import Network.HTTP import Text.Regex.TDFA import Text.Printf getWordList :: IO String getWordList = do response <- simpleHTTP.getRequest$ url getResponseBody response where url = "http://wiki.puzzlers.org/pub/wordlists/unixdict.txt" main = do words <- getWordList putStrLn "Checking Rule 1: \"I before E when not preceded by C\"..." let numTrueRule1 = matchCount (makeRegex "[^c]ie" :: Regex) words numFalseRule1 = matchCount (makeRegex "[^c]ei" :: Regex) words rule1Plausible = numTrueRule1 > (2*numFalseRule1) printf "Rule 1 is correct for%d\n incorrect for%d\n" numTrueRule1 numFalseRule1 printf "*** Rule 1 is%splausible.\n" (if rule1Plausible then "" else "im") putStrLn "Checking Rule 2: \"E before I when preceded by C\"..." let numTrueRule2 = matchCount (makeRegex "cei" :: Regex) words numFalseRule2 = matchCount (makeRegex "cie" :: Regex) words rule2Plausible = numTrueRule2 > (2*numFalseRule2) printf "Rule 2 is correct for%d\n incorrect for%d\n" numTrueRule2 numFalseRule2 printf "*** Rule 2 is%splausible.\n" (if rule2Plausible then "" else "im")
728I before E except after C
8haskell
o2t8p
package main import "fmt" import "strconv" func main() { i, _ := strconv.Atoi("1234") fmt.Println(strconv.Itoa(i + 1)) }
727Increment a numerical string
0go
d5yne
import mymodule
723Include a file
3python
4qa5k
def validateIBAN(String iban) { def iso = [AL: 28, AD: 24, AT: 20, AZ: 28, BE: 16, BH: 22, BA: 20, BR: 29, BG: 22, HR: 21, CY: 28, CZ: 24, DK: 18, DO: 28, EE: 20, FO: 18, FI: 18, FR: 27, GE: 22, DE: 22, GI: 23, GL: 18, GT: 28, HU: 28, IS: 26, IE: 22, IL: 23, IT: 27, KZ: 20, KW: 30, LV: 21, LB: 28, LI: 21, LT: 20, LU: 20, MK: 19, MT: 31, MR: 27, MU: 30, MC: 27, MD: 24, ME: 22, NL: 18, NO: 15, PK: 24, PS: 29, PL: 28, PT: 25, RO: 24, SM: 27, SA: 24, RS: 22, SK: 24, SI: 19, ES: 24, SE: 24, CH: 21, TN: 24, TR: 26, AE: 23, GB: 22, VG: 24, GR: 27, CR: 21] iban = iban.replaceAll(/\s/, '').toUpperCase() if (iban.size() < 4 || iso[iban[0..1]] != iban.size()) return false iban = iban[4..-1] + iban[0..<4] def number = iban.collect { Character.digit(it as char, 36) }.join('') (number as BigInteger).mod(97) == 1 }
729IBAN
7groovy
9bvm4
'''Humble numbers''' from itertools import groupby, islice from functools import reduce def humbles(): '''A non-finite stream of Humble numbers. OEIS A002473 ''' hs = set([1]) while True: nxt = min(hs) yield nxt hs.remove(nxt) hs.update(nxt * x for x in [2, 3, 5, 7]) def main(): '''First 50, and counts with N digits''' print('First 50 Humble numbers:\n') for row in chunksOf(10)( take(50)(humbles()) ): print(' '.join(map( lambda x: str(x).rjust(3), row ))) print('\nCounts of Humble numbers with n digits:\n') for tpl in take(10)( (k, len(list(g))) for k, g in groupby(len(str(x)) for x in humbles()) ): print(tpl) def chunksOf(n): '''A series of lists of length n, subdividing the contents of xs. Where the length of xs is not evenly divible, the final list will be shorter than n. ''' return lambda xs: reduce( lambda a, i: a + [xs[i:n + i]], range(0, len(xs), n), [] ) if 0 < n else [] def take(n): '''The prefix of xs of length n, or xs itself if n > length xs. ''' return lambda xs: ( list(islice(xs, n)) ) if __name__ == '__main__': main()
726Humble numbers
3python
4qb5k
println ((("23455" as BigDecimal) + 1) as String) println ((("23455.78" as BigDecimal) + 1) as String)
727Increment a numerical string
7groovy
0cfsh
source("filename.R")
723Include a file
13r
2aklg
import Data.Char (toUpper) import Data.Maybe (fromJust) validateIBAN :: String -> Either String String validateIBAN [] = Left "No IBAN number." validateIBAN xs = case lookupCountry of Nothing -> invalidBecause "Country does not exist." Just l -> if length normalized /= l then invalidBecause "Number length does not match." else check where normalized = map toUpper $ concat $ words xs country = take 2 normalized lookupCountry = lookup country countries countries :: [(String, Int)] countries = zip (words "AL AT BE BA BG HR CZ DO FO FR DE GR GT \ \IS IL KZ LV LI LU MT MU MD NL PK PL RO SA SK ES CH TR GB \ \AD AZ BH BR CR CY DK EE FI GE GI GL HU IE IT KW LB LT MK \ \MR MC ME NO PS PT SM RS SI SE TN AE VG") [28,20,16,20,22,21,24,28,18,27,22,27,28,26,23,20,21,21,20, 31,30,24,18,24,28,24,24,24,24,21,26,22,24,28,22,29,21,28,18, 20,18,22,23,18,28,22,27,30,28,20,19,27,27,22,15,29,25,27,22, 19,24,24,23,24] digits = ['0'..'9'] letters = ['A'..'Z'] replDigits = zip letters $ map show [10..35] validDigits = digits ++ letters sane = all (`elem` validDigits) normalized (p1, p2) = splitAt 4 normalized p3 = p2 ++ p1 p4 :: Integer p4 = read $ concat $ map convertLetter p3 convertLetter x | x `elem` digits = [x] | otherwise = fromJust $ lookup x replDigits check = if sane then if p4 `mod` 97 == 1 then Right xs else invalidBecause "Validation failed." else invalidBecause "Number contains illegal digits." invalidBecause reason = Left $ "Invalid IBAN number " ++ xs ++ ": " ++ reason
729IBAN
8haskell
w60ed