code
stringlengths
1
46.1k
label
class label
1.18k classes
domain_label
class label
21 classes
index
stringlengths
4
5
x <- sample(c(0, 1), 26, replace=T) x names(x) <- letters x sort(x, method=) sort(x, method=)
245Sort stability
12php
30fzq
import java.util.Comparator; import java.util.Arrays; public class Test { public static void main(String[] args) { String[] strings = {"Here", "are", "some", "sample", "strings", "to", "be", "sorted"}; Arrays.sort(strings, new Comparator<String>() { public int compare(String s1, String s2) { int c = s2.length() - s1.length(); if (c == 0) c = s1.compareToIgnoreCase(s2); return c; } }); for (String s: strings) System.out.print(s + " "); } }
243Sort using a custom comparator
9java
j2j7c
object CombSort extends App { val ia = Array(28, 44, 46, 24, 19, 2, 17, 11, 25, 4) val ca = Array('X', 'B', 'E', 'A', 'Z', 'M', 'S', 'L', 'Y', 'C') def sorted[E](input: Array[E])(implicit ord: Ordering[E]): Array[E] = { import ord._ var gap = input.length var swapped = true while (gap > 1 || swapped) { if (gap > 1) gap = (gap / 1.3).toInt swapped = false for (i <- 0 until input.length - gap) if (input(i) >= input(i + gap)) { val t = input(i) input(i) = input(i + gap) input(i + gap) = t swapped = true } } input } println(s"Unsorted: ${ia.mkString("[", ", ", "]")}") println(s"Sorted : ${sorted(ia).mkString("[", ", ", "]")}\n") println(s"Unsorted: ${ca.mkString("[", ", ", "]")}") println(s"Sorted : ${sorted(ca).mkString("[", ", ", "]")}") }
235Sorting algorithms/Comb sort
16scala
sbtqo
class Array def beadsort map {|e| [1] * e}.columns.columns.map(&:length) end def columns y = length x = map(&:length).max Array.new(x) do |row| Array.new(y) { |column| self[column][row] }.compact end end end p [5,3,1,7,4,1,1].beadsort
239Sorting algorithms/Bead sort
14ruby
4mj5p
null
240Sorting algorithms/Cocktail sort
11kotlin
xh0ws
import Data.List ( sort , intercalate ) splitString :: Eq a => (a) -> [a] -> [[a]] splitString c [] = [] splitString c s = let ( item , rest ) = break ( == c ) s ( _ , next ) = break ( /= c ) rest in item: splitString c next convertIntListToString :: [Int] -> String convertIntListToString = intercalate "." . map show orderOID :: [String] -> [String] orderOID = map convertIntListToString . sort . map ( map read . splitString '.' ) oid :: [String] oid = ["1.3.6.1.4.1.11.2.17.19.3.4.0.10" , "1.3.6.1.4.1.11.2.17.5.2.0.79" , "1.3.6.1.4.1.11.2.17.19.3.4.0.4" , "1.3.6.1.4.1.11150.3.4.0.1" , "1.3.6.1.4.1.11.2.17.19.3.4.0.1" , "1.3.6.1.4.1.11150.3.4.0"] main :: IO ( ) main = do mapM_ putStrLn $ orderOID oid
248Sort a list of object identifiers
8haskell
qhpx9
x <- sample(c(0, 1), 26, replace=T) x names(x) <- letters x sort(x, method=) sort(x, method=)
245Sort stability
3python
bujkr
function lengthSorter(a, b) { var result = b.length - a.length; if (result == 0) result = a.localeCompare(b); return result; } var test = ["Here", "are", "some", "sample", "strings", "to", "be", "sorted"]; test.sort(lengthSorter); alert( test.join(' ') );
243Sort using a custom comparator
10javascript
1g1p7
bogosort <- function(x) { while(is.unsorted(x)) x <- sample(x) x } n <- c(1, 10, 9, 7, 3, 0) bogosort(n)
236Sorting algorithms/Bogosort
13r
e7oad
function cocktailSort( A ) local swapped repeat swapped = false for i = 1, #A - 1 do if A[ i ] > A[ i+1 ] then A[ i ], A[ i+1 ] = A[ i+1 ] ,A[i] swapped=true end end if swapped == false then break
240Sorting algorithms/Cocktail sort
1lua
qk8x0
size_t write_data(void *ptr, size_t size, size_t nmeb, void *stream){ return fwrite(ptr,size,nmeb,stream); } size_t read_data(void *ptr, size_t size, size_t nmeb, void *stream){ return fread(ptr,size,nmeb,stream); } void callSOAP(char* URL, char * inFile, char * outFile) { FILE * rfp = fopen(inFile, ); if(!rfp) perror(); FILE * wfp = fopen(outFile, ); if(!wfp) perror(); struct curl_slist *header = NULL; header = curl_slist_append (header, ); header = curl_slist_append (header, ); header = curl_slist_append (header, ); header = curl_slist_append (header, ); CURL *curl; curl = curl_easy_init(); if(curl) { curl_easy_setopt(curl, CURLOPT_URL, URL); curl_easy_setopt(curl, CURLOPT_POST, 1L); curl_easy_setopt(curl, CURLOPT_READFUNCTION, read_data); curl_easy_setopt(curl, CURLOPT_READDATA, rfp); curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_data); curl_easy_setopt(curl, CURLOPT_WRITEDATA, wfp); curl_easy_setopt(curl, CURLOPT_HTTPHEADER, header); curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE_LARGE, (curl_off_t)-1); curl_easy_setopt(curl, CURLOPT_VERBOSE,1L); curl_easy_perform(curl); curl_easy_cleanup(curl); } } int main(int argC,char* argV[]) { if(argC!=4) printf(,argV[0]); else callSOAP(argV[1],argV[2],argV[3]); return 0; }
253SOAP
5c
w7gec
import java.util.*; public class Hopido { final static String[] board = { ".00.00.", "0000000", "0000000", ".00000.", "..000..", "...0..."}; final static int[][] moves = {{-3, 0}, {0, 3}, {3, 0}, {0, -3}, {2, 2}, {2, -2}, {-2, 2}, {-2, -2}}; static int[][] grid; static int totalToFill; public static void main(String[] args) { int nRows = board.length + 6; int nCols = board[0].length() + 6; grid = new int[nRows][nCols]; for (int r = 0; r < nRows; r++) { Arrays.fill(grid[r], -1); for (int c = 3; c < nCols - 3; c++) if (r >= 3 && r < nRows - 3) { if (board[r - 3].charAt(c - 3) == '0') { grid[r][c] = 0; totalToFill++; } } } int pos = -1, r, c; do { do { pos++; r = pos / nCols; c = pos % nCols; } while (grid[r][c] == -1); grid[r][c] = 1; if (solve(r, c, 2)) break; grid[r][c] = 0; } while (pos < nRows * nCols); printResult(); } static boolean solve(int r, int c, int count) { if (count > totalToFill) return true; List<int[]> nbrs = neighbors(r, c); if (nbrs.isEmpty() && count != totalToFill) return false; Collections.sort(nbrs, (a, b) -> a[2] - b[2]); for (int[] nb : nbrs) { r = nb[0]; c = nb[1]; grid[r][c] = count; if (solve(r, c, count + 1)) return true; grid[r][c] = 0; } return false; } static List<int[]> neighbors(int r, int c) { List<int[]> nbrs = new ArrayList<>(); for (int[] m : moves) { int x = m[0]; int y = m[1]; if (grid[r + y][c + x] == 0) { int num = countNeighbors(r + y, c + x) - 1; nbrs.add(new int[]{r + y, c + x, num}); } } return nbrs; } static int countNeighbors(int r, int c) { int num = 0; for (int[] m : moves) if (grid[r + m[1]][c + m[0]] == 0) num++; return num; } static void printResult() { for (int[] row : grid) { for (int i : row) { if (i == -1) System.out.printf("%2s ", ' '); else System.out.printf("%2d ", i); } System.out.println(); } } }
250Solve a Hopido puzzle
9java
xjhwy
package main import ( "fmt" big "github.com/ncw/gmp" )
254Smallest number k such that k+2^m is composite for all m less than k
0go
w74eg
typedef struct twoStringsStruct { char * key, *value; } sTwoStrings; int ord( char v ) { static char *dgts = ; char *cp; for (cp=dgts; v != *cp; cp++); return (cp-dgts); } int cmprStrgs(const sTwoStrings *s1,const sTwoStrings *s2) { char *p1 = s1->key; char *p2 = s2->key; char *mrk1, *mrk2; while ((tolower(*p1) == tolower(*p2)) && *p1) { p1++; p2++;} if (isdigit(*p1) && isdigit(*p2)) { long v1, v2; if ((*p1 == '0') ||(*p2 == '0')) { while (p1 > s1->key) { p1--; p2--; if (*p1 != '0') break; } if (!isdigit(*p1)) { p1++; p2++; } } mrk1 = p1; mrk2 = p2; v1 = 0; while(isdigit(*p1)) { v1 = 10*v1+ord(*p1); p1++; } v2 = 0; while(isdigit(*p2)) { v2 = 10*v2+ord(*p2); p2++; } if (v1 == v2) return(p2-mrk2)-(p1-mrk1); return v1 - v2; } if (tolower(*p1) != tolower(*p2)) return (tolower(*p1) - tolower(*p2)); for(p1=s1->key, p2=s2->key; (*p1 == *p2) && *p1; p1++, p2++); return (*p1 -*p2); } int maxstrlen( char *a, char *b) { int la = strlen(a); int lb = strlen(b); return (la>lb)? la : lb; } int main() { sTwoStrings toBsorted[] = { { , }, { , }, { , }, { , }, { , }, { , }, { , }, { , }, { , }, { , }, { , }, }; int k, maxlens[ASIZE]; char format[12]; sTwoStrings *cp; qsort( (void*)toBsorted, ASIZE, sizeof(sTwoStrings),cmprStrgs); for (k=0,cp=toBsorted; k < ASIZE; k++,cp++) { maxlens[k] = maxstrlen(cp->key, cp->value); sprintf(format,, maxlens[k]); printf(format, toBsorted[k].value); } printf(); for (k=0; k < ASIZE; k++) { sprintf(format,, maxlens[k]); printf(format, toBsorted[k].key); } printf(); return 0; }
255Sort an array of composite structures
5c
lfocy
class Array def counting_sort! replace counting_sort end def counting_sort min, max = minmax count = Array.new(max - min + 1, 0) each {|number| count[number - min] += 1} (min..max).each_with_object([]) {|i, ary| ary.concat([i] * count[i - min])} end end ary = [9,7,10,2,9,7,4,3,10,2,7,10,2,1,3,8,7,3,9,5,8,5,1,6,3,7,5,4,6,9,9,6,6,10,2,4,5,2,8,2,2,5,2,9,3,3,5,7,8,4] p ary.counting_sort.join() p ary = Array.new(20){rand(-10..10)} p ary.counting_sort
237Sorting algorithms/Counting sort
14ruby
6o23t
use strict; use warnings; $_ = <<END; 0 0 0 0 0 0 0 0 0 0 0 46 45 0 55 74 0 0 0 38 0 0 43 0 0 78 0 0 35 0 0 0 0 0 71 0 0 0 33 0 0 0 59 0 0 0 17 0 0 0 0 0 67 0 0 18 0 0 11 0 0 64 0 0 0 24 21 0 1 2 0 0 0 0 0 0 0 0 0 0 0 END my $gap = /.\n/ * $-[0]; print; s/ (?=\d\b)/0/g; my $max = sprintf "%02d", tr/0-9// / 2; solve( '01', $_ ); sub solve { my ($have, $in) = @_; $have eq $max and exit !print "solution\n", $in =~ s/\b0/ /gr; if( $in =~ ++(my $want = $have) ) { $in =~ /($have|$want)( |.{$gap})($have|$want)/s and solve($want, $in); } else { ($_ = $in) =~ s/$have \K00/$want/ and solve( $want, $_ ); ($_ = $in) =~ s/$have.{$gap}\K00/$want/s and solve( $want, $_ ); ($_ = $in) =~ s/00(?= $have)/$want/ and solve( $want, $_ ); ($_ = $in) =~ s/00(?=.{$gap}$have)/$want/s and solve( $want, $_ ); } }
249Solve a Numbrix puzzle
2perl
xjkw8
(sort [5 4 3 2 1]) (1 2 3 4 5)
252Sort an integer array
6clojure
xj7wk
package com.rosettacode; import java.util.Comparator; import java.util.stream.Stream; public class OIDListSorting { public static void main(String[] args) { final String dot = "\\."; final Comparator<String> oids_comparator = (o1, o2) -> { final String[] o1Numbers = o1.split(dot), o2Numbers = o2.split(dot); for (int i = 0; ; i++) { if (i == o1Numbers.length && i == o2Numbers.length) return 0; if (i == o1Numbers.length) return -1; if (i == o2Numbers.length) return 1; final int nextO1Number = Integer.valueOf(o1Numbers[i]), nextO2Number = Integer.valueOf(o2Numbers[i]); final int result = Integer.compare(nextO1Number, nextO2Number); if (result != 0) return result; } }; Stream.of("1.3.6.1.4.1.11.2.17.19.3.4.0.10", "1.3.6.1.4.1.11.2.17.5.2.0.79", "1.3.6.1.4.1.11.2.17.19.3.4.0.4", "1.3.6.1.4.1.11150.3.4.0.1", "1.3.6.1.4.1.11.2.17.19.3.4.0.1", "1.3.6.1.4.1.11150.3.4.0") .sorted(oids_comparator) .forEach(System.out::println); } }
248Sort a list of object identifiers
9java
p5rb3
x <- sample(c(0, 1), 26, replace=T) x names(x) <- letters x sort(x, method="quick") sort(x, method="shell")
245Sort stability
13r
7c4ry
use 5.010_000; my $x = 'lions, tigers, and'; my $y = 'bears, oh my!'; my $z = '(from the "Wizard of OZ")'; ( $x, $y, $z ) = sort ( $x, $y, $z ); say 'Case 1:'; say " x = $x"; say " y = $y"; say " z = $z"; $x = 77444; $y = -12; $z = 0; ( $x, $y, $z ) = sort { $a <=> $b } ( $x, $y, $z ); say 'Case 2:'; say " x = $x"; say " y = $y"; say " z = $z";
242Sort three variables
2perl
7ljrh
func combSort(inout list:[Int]) { var swapped = true var gap = list.count while gap > 1 || swapped { gap = gap * 10 / 13 if gap == 9 || gap == 10 { gap = 11 } else if gap < 1 { gap = 1 } swapped = false for var i = 0, j = gap; j < list.count; i++, j++ { if list[i] > list[j] { (list[i], list[j]) = (list[j], list[i]) swapped = true } } } }
235Sorting algorithms/Comb sort
17swift
aro1i
(require '[clj-soap.core:as soap]) (let [client (soap/client-fn "http://example.com/soap/wsdl")] (client:soapFunc) (client:anotherSoapFunc))
253SOAP
6clojure
8pk05
null
250Solve a Hopido puzzle
11kotlin
p54b6
use strict; use warnings; use bigint; use ntheory 'is_prime'; my $cnt; LOOP: for my $k (2..1e10) { next unless 1 == $k % 2; for my $m (1..$k-1) { next LOOP if is_prime $k + (1<<$m) } print "$k "; last if ++$cnt == 5; }
254Smallest number k such that k+2^m is composite for all m less than k
2perl
u3fvr
fn counting_sort( mut data: Vec<usize>, min: usize, max: usize, ) -> Vec<usize> {
237Sorting algorithms/Counting sort
15rust
yiv68
def countSort(input: List[Int], min: Int, max: Int): List[Int] = input.foldLeft(Array.fill(max - min + 1)(0)) { (arr, n) => arr(n - min) += 1 arr }.zipWithIndex.foldLeft(List[Int]()) { case (lst, (cnt, ndx)) => List.fill(cnt)(ndx + min) ::: lst }.reverse
237Sorting algorithms/Counting sort
16scala
cf493
package main import ( "fmt" "sort" ) func main() {
247Sort disjoint sublist
0go
vzm2m
<?php $x = 'lions, tigers, and'; $y = 'bears, oh my!'; $z = '(from the )'; $items = [$x, $y, $z]; sort($items); list($x, $y, $z) = $items; echo <<<EOT Case 1: x = $x y = $y z = $z EOT; $x = 77444; $y = -12; $z = 0; $items = [$x, $y, $z]; sort($items); list($x, $y, $z) = $items; echo <<<EOT Case 2: x = $x y = $y z = $z EOT;
242Sort three variables
12php
fqtdh
import java.util.Arrays fun main(args: Array<String>) { val strings = arrayOf("Here", "are", "some", "sample", "strings", "to", "be", "sorted") fun printArray(message: String, array: Array<String>) = with(array) { print("$message [") forEachIndexed { index, string -> print(if (index == lastIndex) string else "$string, ") } println("]") } printArray("Unsorted:", strings) Arrays.sort(strings) { first, second -> val lengthDifference = second.length - first.length if (lengthDifference == 0) first.lowercase().compareTo(second.lowercase(), true) else lengthDifference } printArray("Sorted:", strings) }
243Sort using a custom comparator
11kotlin
5y5ua
test = { "Here", "we", "have", "some", "sample", "strings", "to", "be", "sorted" } function stringSorter(a, b) if string.len(a) == string.len(b) then return string.lower(a) < string.lower(b) end return string.len(a) > string.len(b) end table.sort(test, stringSorter)
243Sort using a custom comparator
1lua
4m45c
package main import "fmt" var moves = [][2]int{ {-1, -2}, {1, -2}, {-1, 2}, {1, 2}, {-2, -1}, {-2, 1}, {2, -1}, {2, 1}, } var board1 = " xxx " + " x xx " + " xxxxxxx" + "xxx x x" + "x x xxx" + "sxxxxxx " + " xx x " + " xxx " var board2 = ".....s.x....." + ".....x.x....." + "....xxxxx...." + ".....xxx....." + "..x..x.x..x.." + "xxxxx...xxxxx" + "..xx.....xx.." + "xxxxx...xxxxx" + "..x..x.x..x.." + ".....xxx....." + "....xxxxx...." + ".....x.x....." + ".....x.x....." func solve(pz [][]int, sz, sx, sy, idx, cnt int) bool { if idx > cnt { return true } for i := 0; i < len(moves); i++ { x := sx + moves[i][0] y := sy + moves[i][1] if (x >= 0 && x < sz) && (y >= 0 && y < sz) && pz[x][y] == 0 { pz[x][y] = idx if solve(pz, sz, x, y, idx+1, cnt) { return true } pz[x][y] = 0 } } return false } func findSolution(b string, sz int) { pz := make([][]int, sz) for i := 0; i < sz; i++ { pz[i] = make([]int, sz) for j := 0; j < sz; j++ { pz[i][j] = -1 } } var x, y, idx, cnt int for j := 0; j < sz; j++ { for i := 0; i < sz; i++ { switch b[idx] { case 'x': pz[i][j] = 0 cnt++ case 's': pz[i][j] = 1 cnt++ x, y = i, j } idx++ } } if solve(pz, sz, x, y, 2, cnt) { for j := 0; j < sz; j++ { for i := 0; i < sz; i++ { if pz[i][j] != -1 { fmt.Printf("%02d ", pz[i][j]) } else { fmt.Print("-- ") } } fmt.Println() } } else { fmt.Println("Cannot solve this puzzle!") } } func main() { findSolution(board1, 8) fmt.Println() findSolution(board2, 13) }
256Solve a Holy Knight's tour
0go
kvmhz
package main import ( "fmt" "github.com/tiaguinho/gosoap" "log" ) type CheckVatResponse struct { CountryCode string `xml:"countryCode"` VatNumber string `xml:"vatNumber"` RequestDate string `xml:"requestDate"` Valid string `xml:"valid"` Name string `xml:"name"` Address string `xml:"address"` } var ( rv CheckVatResponse ) func check(err error) { if err != nil { log.Fatal(err) } } func main() {
253SOAP
0go
cdi9g
(def *langs* [["Clojure" 2007] ["Common Lisp" 1984] ["Java" 1995] ["Haskell" 1990] ["Lisp" 1958] ["Scheme" 1975]]) user> (sort-by second *langs*) (["Lisp" 1958] ["Scheme" 1975] ["Common Lisp" 1984] ["Haskell" 1990] ["Java" 1995] ["Clojure" 2007])
255Sort an array of composite structures
6clojure
4yt5o
null
248Sort a list of object identifiers
11kotlin
7cvr4
def sparseSort = { a, indices = ([] + (0..<(a.size()))) -> indices.sort().unique() a[indices] = a[indices].sort() a }
247Sort disjoint sublist
7groovy
mity5
ary = [[, ], [, ], [, ], [, ]] p ary.sort {|a,b| a[1] <=> b[1]}
245Sort stability
14ruby
14kpw
fn main() { let country_city = [ ("UK", "London"), ("US", "New York"), ("US", "Birmingham"), ("UK", "Birmingham"), ]; let mut city_sorted = country_city.clone(); city_sorted.sort_by_key(|k| k.1); let mut country_sorted = country_city.clone(); country_sorted.sort_by_key(|k| k.0); println!("Original:"); for x in &country_city { println!("{} {}", x.0, x.1); } println!("\nWhen sorted by city:"); for x in &city_sorted { println!("{} {}", x.0, x.1); } println!("\nWhen sorted by county:"); for x in &country_sorted { println!("{} {}", x.0, x.1); } }
245Sort stability
15rust
agb14
scala> val list = List((1, 'c'), (1, 'b'), (2, 'a')) list: List[(Int, Char)] = List((1,c), (1,b), (2,a)) scala> val srt1 = list.sortWith(_._2 < _._2) srt1: List[(Int, Char)] = List((2,a), (1,b), (1,c)) scala> val srt2 = srt1.sortBy(_._1)
245Sort stability
16scala
xjawg
def shuffle(l) l.sort_by { rand } end def bogosort(l) l = shuffle(l) until in_order(l) l end def in_order(l) (0..l.length-2).all? {|i| l[i] <= l[i+1] } end
236Sorting algorithms/Bogosort
14ruby
81z01
int w, h, n_boxes; uint8_t *board, *goals, *live; typedef uint16_t cidx_t; typedef uint32_t hash_t; typedef struct state_t state_t; struct state_t { hash_t h; state_t *prev, *next, *qnext; cidx_t c[]; }; size_t state_size, block_size = 32; state_t *block_root, *block_head; inline state_t* newstate(state_t *parent) { inline state_t* next_of(state_t *s) { return (void*)((uint8_t*)s + state_size); } state_t *ptr; if (!block_head) { block_size *= 2; state_t *p = malloc(block_size * state_size); assert(p); p->next = block_root; block_root = p; ptr = (void*)((uint8_t*)p + state_size * block_size); p = block_head = next_of(p); state_t *q; for (q = next_of(p); q < ptr; p = q, q = next_of(q)) p->next = q; p->next = NULL; } ptr = block_head; block_head = block_head->next; ptr->prev = parent; ptr->h = 0; return ptr; } inline void unnewstate(state_t *p) { p->next = block_head; block_head = p; } enum { space, wall, player, box }; const char * const glyph1[] = { , , EE, EE}; const char * const glyph2[] = { EE, , EE, EE}; void mark_live(const int c) { const int y = c / w, x = c % w; if (live[c]) return; live[c] = 1; if (y > 1 && board[c - w] != wall && board[c - w * 2] != wall) mark_live(c - w); if (y < h - 2 && board[c + w] != wall && board[c + w * 2] != wall) mark_live(c + w); if (x > 1 && board[c - 1] != wall && board[c - 2] != wall) mark_live(c - 1); if (x < w - 2 && board[c + 1] != wall && board[c + 2] != wall) mark_live(c + 1); } state_t *parse_board(const int y, const int x, const char *s) { w = x, h = y; board = calloc(w * h, sizeof(uint8_t)); assert(board); goals = calloc(w * h, sizeof(uint8_t)); assert(goals); live = calloc(w * h, sizeof(uint8_t)); assert(live); n_boxes = 0; for (int i = 0; s[i]; i++) { switch(s[i]) { case ' continue; case '.': case '+': goals[i] = 1; case '@': continue; case '*': goals[i] = 1; case '$': n_boxes++; continue; default: continue; } } const int is = sizeof(int); state_size = (sizeof(state_t) + (1 + n_boxes) * sizeof(cidx_t) + is - 1) / is * is; state_t *state = newstate(NULL); for (int i = 0, j = 0; i < w * h; i++) { if (goals[i]) mark_live(i); if (s[i] == '$' || s[i] == '*') state->c[++j] = i; else if (s[i] == '@' || s[i] == '+') state->c[0] = i; } return state; } void show_board(const state_t *s) { unsigned char b[w * h]; memcpy(b, board, w * h); b[ s->c[0] ] = player; for (int i = 1; i <= n_boxes; i++) b[ s->c[i] ] = box; for (int i = 0; i < w * h; i++) { printf((goals[i] ? glyph2 : glyph1)[ b[i] ]); if (! ((1 + i) % w)) putchar('\n'); } } inline void hash(state_t *s) { if (!s->h) { register hash_t ha = 0; cidx_t *p = s->c; for (int i = 0; i <= n_boxes; i++) ha = p[i] + 31 * ha; s->h = ha; } } state_t **buckets; hash_t hash_size, fill_limit, filled; void extend_table() { int old_size = hash_size; if (!old_size) { hash_size = 1024; filled = 0; fill_limit = hash_size * 3 / 4; } else { hash_size *= 2; fill_limit *= 2; } buckets = realloc(buckets, sizeof(state_t*) * hash_size); assert(buckets); memset(buckets + old_size, 0, sizeof(state_t*) * (hash_size - old_size)); const hash_t bits = hash_size - 1; for (int i = 0; i < old_size; i++) { state_t *head = buckets[i]; buckets[i] = NULL; while (head) { state_t *next = head->next; const int j = head->h & bits; head->next = buckets[j]; buckets[j] = head; head = next; } } } state_t *lookup(state_t *s) { hash(s); state_t *f = buckets[s->h & (hash_size - 1)]; for (; f; f = f->next) { if ( !memcmp(s->c, f->c, sizeof(cidx_t) * (1 + n_boxes))) break; } return f; } bool add_to_table(state_t *s) { if (lookup(s)) { unnewstate(s); return false; } if (filled++ >= fill_limit) extend_table(); hash_t i = s->h & (hash_size - 1); s->next = buckets[i]; buckets[i] = s; return true; } bool success(const state_t *s) { for (int i = 1; i <= n_boxes; i++) if (!goals[s->c[i]]) return false; return true; } state_t *move_me(state_t *s, const int dy, const int dx) { const int y = s->c[0] / w; const int x = s->c[0] % w; const int y1 = y + dy; const int x1 = x + dx; const int c1 = y1 * w + x1; if (y1 < 0 || y1 > h || x1 < 0 || x1 > w || board[c1] == wall) return NULL; int at_box = 0; for (int i = 1; i <= n_boxes; i++) { if (s->c[i] == c1) { at_box = i; break; } } int c2; if (at_box) { c2 = c1 + dy * w + dx; if (board[c2] == wall || !live[c2]) return NULL; for (int i = 1; i <= n_boxes; i++) if (s->c[i] == c2) return NULL; } state_t *n = newstate(s); memcpy(n->c + 1, s->c + 1, sizeof(cidx_t) * n_boxes); cidx_t *p = n->c; p[0] = c1; if (at_box) p[at_box] = c2; for (int i = n_boxes; --i; ) { cidx_t t = 0; for (int j = 1; j < i; j++) { if (p[j] > p[j + 1]) t = p[j], p[j] = p[j+1], p[j+1] = t; } if (!t) break; } return n; } state_t *next_level, *done; bool queue_move(state_t *s) { if (!s || !add_to_table(s)) return false; if (success(s)) { puts(); done = s; return true; } s->qnext = next_level; next_level = s; return false; } bool do_move(state_t *s) { return queue_move(move_me(s, 1, 0)) || queue_move(move_me(s, -1, 0)) || queue_move(move_me(s, 0, 1)) || queue_move(move_me(s, 0, -1)); } void show_moves(const state_t *s) { if (s->prev) show_moves(s->prev); usleep(200000); printf(); show_board(s); } int main() { state_t *s = parse_board( 8, 7, 5, 13, 5, 13, 11, 19, ); show_board(s); extend_table(); queue_move(s); for (int i = 0; !done; i++) { printf(, i); fflush(stdout); state_t *head = next_level; for (next_level = NULL; head && !done; head = head->qnext) do_move(head); if (!next_level) { puts(); return 1; } } printf(); getchar(), puts(); show_moves(done); free(buckets); free(board); free(goals); free(live); while (block_root) { void *tmp = block_root->next; free(block_root); block_root = tmp; } return 0; }
257Sokoban
5c
68e32
import Data.Array (Array, (//), (!), assocs, elems, bounds, listArray) import Data.Foldable (forM_) import Data.List (intercalate, transpose) import Data.Maybe type Position = (Int, Int) type KnightBoard = Array Position (Maybe Int) toSlot :: Char -> Maybe Int toSlot '0' = Just 0 toSlot '1' = Just 1 toSlot _ = Nothing toString :: Maybe Int -> String toString Nothing = replicate 3 ' ' toString (Just n) = replicate (3 - length nn) ' ' ++ nn where nn = show n chunksOf :: Int -> [a] -> [[a]] chunksOf _ [] = [] chunksOf n xs = let (chunk, rest) = splitAt n xs in chunk: chunksOf n rest showBoard :: KnightBoard -> String showBoard board = intercalate "\n" . map concat . transpose . chunksOf (height + 1) . map toString $ elems board where (_, (_, height)) = bounds board toBoard :: [String] -> KnightBoard toBoard strs = board where height = length strs width = minimum (length <$> strs) board = listArray ((0, 0), (width - 1, height - 1)) . map toSlot . concat . transpose $ take width <$> strs add :: Num a => (a, a) -> (a, a) -> (a, a) add (a, b) (x, y) = (a + x, b + y) within :: Ord a => ((a, a), (a, a)) -> (a, a) -> Bool within ((a, b), (c, d)) (x, y) = a <= x && x <= c && b <= y && y <= d validMoves :: KnightBoard -> Position -> [Position] validMoves board position = filter isValid plausible where bound = bounds board plausible = add position <$> [(1, 2), (2, 1), (2, -1), (-1, 2), (-2, 1), (1, -2), (-1, -2), (-2, -1)] isValid pos = within bound pos && maybe False (== 0) (board ! pos) isSolved :: KnightBoard -> Bool isSolved = all (maybe True (0 /=)) solveKnightTour :: KnightBoard -> Maybe KnightBoard solveKnightTour board = solve board 1 initPosition where initPosition = fst $ head $ filter ((== Just 1) . snd) $ assocs board solve boardA depth position = let boardB = boardA // [(position, Just depth)] in if isSolved boardB then Just boardB else listToMaybe $ mapMaybe (solve boardB $ depth + 1) $ validMoves boardB position tourExA :: [String] tourExA = [ " 000 " , " 0 00 " , " 0000000" , "000 0 0" , "0 0 000" , "1000000 " , " 00 0 " , " 000 " ] tourExB :: [String] tourExB = [ " , " , " , " , " , "00000 , " , "00000 , " , " , " , " , " ] main :: IO () main = forM_ [tourExA, tourExB] (\board -> case solveKnightTour $ toBoard board of Nothing -> putStrLn "No solution.\n" Just solution -> putStrLn $ showBoard solution ++ "\n")
256Solve a Holy Knight's tour
8haskell
nekie
null
253SOAP
11kotlin
vzf21
use strict; use warnings; $_ = do { local $/; <DATA> }; s/./$&$&/g; my $w = /\n/ && $-[0]; my $wd = 3 * $w + 1; my $wr = 2 * $w + 8; my $wl = 2 * $w - 8; place($_, '00'); die "No solution\n"; sub place { (local $_, my $last) = @_; (my $new = $last)++; /$last.{10}(?=00)/g and place( s/\G00/$new/r, $new ); /(?=00.{10}$last)/g and place( s/\G00/$new/r, $new ); /$last.{$wd}(?=00)/gs and place( s/\G00/$new/r, $new ); /(?=00.{$wd}$last)/gs and place( s/\G00/$new/r, $new ); /$last.{$wr}(?=00)/gs and place( s/\G00/$new/r, $new ); /(?=00.{$wr}$last)/gs and place( s/\G00/$new/r, $new ); /$last.{$wl}(?=00)/gs and place( s/\G00/$new/r, $new ); /(?=00.{$wl}$last)/gs and place( s/\G00/$new/r, $new ); /00/ and return; print "Solution\n\n", s/ / /gr =~ s/0\B/ /gr; exit; } __DATA__ . 0 0 . 0 0 . 0 0 0 0 0 0 0 0 0 0 0 0 0 0 . 0 0 0 0 0 . . . 0 0 0 . . . . . 0 . . .
250Solve a Hopido puzzle
2perl
yoi6u
package main import ( "fmt" "strings" ) func main() { p, tests, swaps := Solution() fmt.Println(p) fmt.Println("Tested", tests, "positions and did", swaps, "swaps.") }
251Solve the no connection puzzle
0go
qhhxz
from sys import stdout neighbours = [[-1, 0], [0, -1], [1, 0], [0, 1]] exists = [] lastNumber = 0 wid = 0 hei = 0 def find_next(pa, x, y, z): for i in range(4): a = x + neighbours[i][0] b = y + neighbours[i][1] if wid > a > -1 and hei > b > -1: if pa[a][b] == z: return a, b return -1, -1 def find_solution(pa, x, y, z): if z > lastNumber: return 1 if exists[z] == 1: s = find_next(pa, x, y, z) if s[0] < 0: return 0 return find_solution(pa, s[0], s[1], z + 1) for i in range(4): a = x + neighbours[i][0] b = y + neighbours[i][1] if wid > a > -1 and hei > b > -1: if pa[a][b] == 0: pa[a][b] = z r = find_solution(pa, a, b, z + 1) if r == 1: return 1 pa[a][b] = 0 return 0 def solve(pz, w, h): global lastNumber, wid, hei, exists lastNumber = w * h wid = w hei = h exists = [0 for j in range(lastNumber + 1)] pa = [[0 for j in range(h)] for i in range(w)] st = pz.split() idx = 0 for j in range(h): for i in range(w): if st[idx] == : idx += 1 else: pa[i][j] = int(st[idx]) exists[pa[i][j]] = 1 idx += 1 x = 0 y = 0 t = w * h + 1 for j in range(h): for i in range(w): if pa[i][j] != 0 and pa[i][j] < t: t = pa[i][j] x = i y = j return find_solution(pa, x, y, t + 1), pa def show_result(r): if r[0] == 1: for j in range(hei): for i in range(wid): stdout.write(.format(r[1][i][j], 2)) print() else: stdout.write() print() r = solve( , 9, 9) show_result(r) r = solve( , 9, 9) show_result(r) r = solve( , 9, 9) show_result(r)
249Solve a Numbrix puzzle
3python
qhbxi
local OIDs = { "1.3.6.1.4.1.11.2.17.19.3.4.0.10", "1.3.6.1.4.1.11.2.17.5.2.0.79", "1.3.6.1.4.1.11.2.17.19.3.4.0.4", "1.3.6.1.4.1.11150.3.4.0.1", "1.3.6.1.4.1.11.2.17.19.3.4.0.1", "1.3.6.1.4.1.11150.3.4.0" } function compare (a, b) local aList, bList, Na, Nb = {}, {} for num in a:gmatch("%d+") do table.insert(aList, num) end for num in b:gmatch("%d+") do table.insert(bList, num) end for i = 1, math.max(#aList, #bList) do Na, Nb = tonumber(aList[i]) or 0, tonumber(bList[i]) or 0 if Na ~= Nb then return Na < Nb end end end table.sort(OIDs, compare) for _, oid in pairs(OIDs) do print(oid) end
248Sort a list of object identifiers
1lua
jlu71
import Control.Monad import qualified Data.Array as A import Data.Array.IArray import Data.Array.ST import Data.List import Data.List.Utils disSort1 :: (Ord a, Num a, Enum a, Ord b) => [b] -> [a] -> [b] disSort1 xs is = let is_ = sort is (sub, rest) = partition ((`elem` is_) . fst) $ zip [0 ..] xs in map snd . merge rest . zip is_ . sort $ map snd sub disSort2 :: (Ord a) => [a] -> [Int] -> [a] disSort2 xs is = let as = A.listArray (0, length xs - 1) xs sub = zip (sort is) . sort $ map (as !) is in elems $ as // sub disSort3 :: [Int] -> [Int] -> [Int] disSort3 xs is = elems . runSTUArray $ do as <- newListArray (0, length xs - 1) xs sub <- (zip (sort is) . sort) Control.Applicative.<$> mapM (readArray as) is mapM_ (uncurry (writeArray as)) sub return as main :: IO () main = do let xs = [7, 6, 5, 4, 3, 2, 1, 0] is = [6, 1, 7] print $ disSort1 xs is print $ disSort2 xs is print $ disSort3 xs is
247Sort disjoint sublist
8haskell
erkai
extern crate rand; use rand::Rng; fn bogosort_by<T,F>(order: F, coll: &mut [T]) where F: Fn(&T, &T) -> bool { let mut rng = rand::thread_rng(); while!is_sorted_by(&order, coll) { rng.shuffle(coll); } } #[inline] fn is_sorted_by<T,F>(order: F, coll: &[T]) -> bool where F: Fn(&T,&T) -> bool, { coll[..].iter().zip(&coll[1..]).all(|(x,y)| order(x,y)) } fn main() { let mut testlist = [1,55,88,24,990876,312,67,0,854,13,4,7]; bogosort_by(|x,y| x < y, &mut testlist); println!("{:?}", testlist); bogosort_by(|x,y| x > y, &mut testlist); println!("{:?}", testlist); }
236Sorting algorithms/Bogosort
15rust
oa383
def isSorted(l: List[Int]) = l.iterator sliding 2 forall (s => s.head <= s.last) def bogosort(l: List[Int]): List[Int] = if (isSorted(l)) l else bogosort(scala.util.Random.shuffle(l))
236Sorting algorithms/Bogosort
16scala
dxmng
use SOAP::Lite; print SOAP::Lite -> service('http://example.com/soap/wsdl') -> soapFunc("hello"); print SOAP::Lite -> service('http://example.com/soap/wsdl') -> anotherSoapFunc(34234);
253SOAP
2perl
0bhs4
import java.util.stream.Collectors import java.util.stream.IntStream class NoConnection {
251Solve the no connection puzzle
7groovy
144p6
a= raw_input().strip() b=raw_input().strip() c=raw_input().strip() if a>b: a,b = b,a if a>c: a,c = c,a if b>c: b,c = c,b print(str(a)++str(b)++str(c))
242Sort three variables
3python
j2h7p
<?php $client = new SoapClient(); $result = $client->soapFunc(); $result = $client->anotherSoapFunc(34234); $client = new SoapClient(); print_r($client->__getTypes()); print_r($client->__getFunctions()); ?>
253SOAP
12php
56zus
from SOAPpy import WSDL proxy = WSDL.Proxy() result = proxy.soapFunc() result = proxy.anotherSoapFunc(34234)
253SOAP
3python
8pk0o
import Data.List (permutations) solution :: [Int] solution@(a: b: c: d: e: f: g: h: _) = head $ filter isSolution (permutations [1 .. 8]) where isSolution :: [Int] -> Bool isSolution (a: b: c: d: e: f: g: h: _) = all ((> 1) . abs) $ zipWith (-) [a, c, g, e, a, c, g, e, b, d, h, f, b, d, h, f] [d, d, d, d, c, g, e, a, e, e, e, e, d, h, f, b] main :: IO () main = (putStrLn . unlines) $ unlines ( zipWith (\x y -> x: (" = " <> show y)) ['A' .. 'H'] solution ): ( rightShift . unwords . fmap show <$> [[], [a, b], [c, d, e, f], [g, h]] ) where rightShift s | length s > 3 = s | otherwise = " " <> s
251Solve the no connection puzzle
8haskell
miiyf
my @OIDs = qw( 1.3.6.1.4.1.11.2.17.19.3.4.0.10 1.3.6.1.4.1.11.2.17.5.2.0.79 1.3.6.1.4.1.11.2.17.19.3.4.0.4 1.3.6.1.4.1.11150.3.4.0.1 1.3.6.1.4.1.11.2.17.19.3.4.0.1 1.3.6.1.4.1.11150.3.4.0 ); my @sorted = map { $_->[0] } sort { $a->[1] cmp $b->[1] } map { [$_, join '', map { sprintf "%8d", $_ } split /\./, $_] } @OIDs; print "$_\n" for @sorted;
248Sort a list of object identifiers
2perl
fx0d7
assignVec <- Vectorize("assign", c("x", "value")) `%<<-%` <- function(x, value) invisible(assignVec(x, value, envir = .GlobalEnv))
242Sort three variables
13r
4mg5y
const char *msg = ; int main() { int i, sock, len, slen; struct addrinfo hints, *addrs; memset(&hints, 0, sizeof(struct addrinfo)); hints.ai_family = AF_UNSPEC; hints.ai_socktype = SOCK_STREAM; if (0 == getaddrinfo(, , &hints, &addrs)) { sock = socket(addrs->ai_family, addrs->ai_socktype, addrs->ai_protocol); if ( sock >= 0 ) { if ( connect(sock, addrs->ai_addr, addrs->ai_addrlen) >= 0 ) { const char *pm = msg; do { len = strlen(pm); slen = send(sock, pm, len, 0); pm += slen; } while ((0 <= slen) && (slen < len)); } close(sock); } freeaddrinfo(addrs); } }
258Sockets
5c
lfscy
typedef uint32_t integer; integer next_prime_digit_number(integer n) { if (n == 0) return 2; switch (n % 10) { case 2: return n + 1; case 3: case 5: return n + 2; default: return 2 + next_prime_digit_number(n/10) * 10; } } bool is_prime(integer n) { if (n < 2) return false; if (n % 2 == 0) return n == 2; if (n % 3 == 0) return n == 3; if (n % 5 == 0) return n == 5; static const integer wheel[] = { 4,2,4,2,4,6,2,6 }; integer p = 7; for (;;) { for (int i = 0; i < 8; ++i) { if (p * p > n) return true; if (n % p == 0) return false; p += wheel[i]; } } } int main() { setlocale(LC_ALL, ); const integer limit = 1000000000; integer n = 0, max = 0; printf(); for (int i = 0; n < limit; ) { n = next_prime_digit_number(n); if (!is_prime(n)) continue; if (i < 25) { if (i > 0) printf(); printf(, n); } else if (i == 25) printf(); ++i; if (i == 100) printf(, n); else if (i == 1000) printf(, n); else if (i == 10000) printf(, n); max = n; } printf(, limit, max); return 0; }
259Smarandache prime-digital sequence
5c
7cfrg
import java.util.*; public class HolyKnightsTour { final static String[] board = { " xxx ", " x xx ", " xxxxxxx", "xxx x x", "x x xxx", "1xxxxxx ", " xx x ", " xxx "}; private final static int base = 12; private final static int[][] moves = {{1, -2}, {2, -1}, {2, 1}, {1, 2}, {-1, 2}, {-2, 1}, {-2, -1}, {-1, -2}}; private static int[][] grid; private static int total = 2; public static void main(String[] args) { int row = 0, col = 0; grid = new int[base][base]; for (int r = 0; r < base; r++) { Arrays.fill(grid[r], -1); for (int c = 2; c < base - 2; c++) { if (r >= 2 && r < base - 2) { if (board[r - 2].charAt(c - 2) == 'x') { grid[r][c] = 0; total++; } if (board[r - 2].charAt(c - 2) == '1') { row = r; col = c; } } } } grid[row][col] = 1; if (solve(row, col, 2)) printResult(); } private static boolean solve(int r, int c, int count) { if (count == total) return true; List<int[]> nbrs = neighbors(r, c); if (nbrs.isEmpty() && count != total) return false; Collections.sort(nbrs, (a, b) -> a[2] - b[2]); for (int[] nb : nbrs) { r = nb[0]; c = nb[1]; grid[r][c] = count; if (solve(r, c, count + 1)) return true; grid[r][c] = 0; } return false; } private static List<int[]> neighbors(int r, int c) { List<int[]> nbrs = new ArrayList<>(); for (int[] m : moves) { int x = m[0]; int y = m[1]; if (grid[r + y][c + x] == 0) { int num = countNeighbors(r + y, c + x) - 1; nbrs.add(new int[]{r + y, c + x, num}); } } return nbrs; } private static int countNeighbors(int r, int c) { int num = 0; for (int[] m : moves) if (grid[r + m[1]][c + m[0]] == 0) num++; return num; } private static void printResult() { for (int[] row : grid) { for (int i : row) { if (i == -1) System.out.printf("%2s ", ' '); else System.out.printf("%2d ", i); } System.out.println(); } } }
256Solve a Holy Knight's tour
9java
qh4xa
require 'soap/wsdlDriver' wsdl = SOAP::WSDLDriverFactory.new() soap = wsdl.create_rpc_driver response1 = soap.soapFunc(:elementName => ) puts response1.soapFuncReturn response2 = soap.anotherSoapFunc(:aNumber => 42) puts response2.anotherSoapFuncReturn
253SOAP
14ruby
iapoh
from sys import stdout neighbours = [[2, 2], [-2, 2], [2, -2], [-2, -2], [3, 0], [0, 3], [-3, 0], [0, -3]] cnt = 0 pWid = 0 pHei = 0 def is_valid(a, b): return -1 < a < pWid and -1 < b < pHei def iterate(pa, x, y, v): if v > cnt: return 1 for i in range(len(neighbours)): a = x + neighbours[i][0] b = y + neighbours[i][1] if is_valid(a, b) and pa[a][b] == 0: pa[a][b] = v r = iterate(pa, a, b, v + 1) if r == 1: return r pa[a][b] = 0 return 0 def solve(pz, w, h): global cnt, pWid, pHei pa = [[-1 for j in range(h)] for i in range(w)] f = 0 pWid = w pHei = h for j in range(h): for i in range(w): if pz[f] == : pa[i][j] = 0 cnt += 1 f += 1 for y in range(h): for x in range(w): if pa[x][y] == 0: pa[x][y] = 1 if 1 == iterate(pa, x, y, 2): return 1, pa pa[x][y] = 0 return 0, pa r = solve(, 7, 6) if r[0] == 1: for j in range(6): for i in range(7): if r[1][i][j] == -1: stdout.write() else: stdout.write(.format(r[1][i][j], 2)) print() else: stdout.write()
250Solve a Hopido puzzle
3python
minyh
require 'HLPsolver' ADJACENT = [[-1, 0], [0, -1], [0, 1], [1, 0]] board1 = <<EOS 0 0 0 0 0 0 0 0 0 0 0 46 45 0 55 74 0 0 0 38 0 0 43 0 0 78 0 0 35 0 0 0 0 0 71 0 0 0 33 0 0 0 59 0 0 0 17 0 0 0 0 0 67 0 0 18 0 0 11 0 0 64 0 0 0 24 21 0 1 2 0 0 0 0 0 0 0 0 0 0 0 EOS HLPsolver.new(board1).solve board2 = <<EOS 0 0 0 0 0 0 0 0 0 0 11 12 15 18 21 62 61 0 0 6 0 0 0 0 0 60 0 0 33 0 0 0 0 0 57 0 0 32 0 0 0 0 0 56 0 0 37 0 1 0 0 0 73 0 0 38 0 0 0 0 0 72 0 0 43 44 47 48 51 76 77 0 0 0 0 0 0 0 0 0 0 EOS HLPsolver.new(board2).solve
249Solve a Numbrix puzzle
14ruby
0b1su
import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; public class Disjoint { public static <T extends Comparable<? super T>> void sortDisjoint( List<T> array, int[] idxs) { Arrays.sort(idxs); List<T> disjoint = new ArrayList<T>(); for (int idx: idxs) { disjoint.add(array.get(idx)); } Collections.sort(disjoint); int i = 0; for (int idx: idxs) { array.set(idx, disjoint.get(i++)); } } public static void main(String[] args) { List<Integer> list = Arrays.asList(7, 6, 5, 4, 3, 2, 1, 0); int[] indices = {6, 1, 7}; System.out.println(list); sortDisjoint(list, indices); System.out.println(list); } }
247Sort disjoint sublist
9java
h24jm
package main import ( "fmt" "strings" ) func main() { level := ` ####### # # # # #. # # #. $$ # #.$$ # #.# @# #######` fmt.Printf("level:%s\n", level) fmt.Printf("solution:\n%s\n", solve(level)) } func solve(board string) string { buffer = make([]byte, len(board)) width := strings.Index(board[1:], "\n") + 1 dirs := []struct { move, push string dPos int }{ {"u", "U", -width}, {"r", "R", 1}, {"d", "D", width}, {"l", "L", -1}, } visited := map[string]bool{board: true} open := []state{state{board, "", strings.Index(board, "@")}} for len(open) > 0 { s1 := &open[0] open = open[1:] for _, dir := range dirs { var newBoard, newSol string newPos := s1.pos + dir.dPos switch s1.board[newPos] { case '$', '*': newBoard = s1.push(dir.dPos) if newBoard == "" || visited[newBoard] { continue } newSol = s1.cSol + dir.push if strings.IndexAny(newBoard, ".+") < 0 { return newSol } case ' ', '.': newBoard = s1.move(dir.dPos) if visited[newBoard] { continue } newSol = s1.cSol + dir.move default: continue } open = append(open, state{newBoard, newSol, newPos}) visited[newBoard] = true } } return "No solution" } type state struct { board string cSol string pos int } var buffer []byte func (s *state) move(dPos int) string { copy(buffer, s.board) if buffer[s.pos] == '@' { buffer[s.pos] = ' ' } else { buffer[s.pos] = '.' } newPos := s.pos + dPos if buffer[newPos] == ' ' { buffer[newPos] = '@' } else { buffer[newPos] = '+' } return string(buffer) } func (s *state) push(dPos int) string { newPos := s.pos + dPos boxPos := newPos + dPos switch s.board[boxPos] { case ' ', '.': default: return "" } copy(buffer, s.board) if buffer[s.pos] == '@' { buffer[s.pos] = ' ' } else { buffer[s.pos] = '.' } if buffer[newPos] == '$' { buffer[newPos] = '@' } else { buffer[newPos] = '+' } if buffer[boxPos] == ' ' { buffer[boxPos] = '$' } else { buffer[boxPos] = '*' } return string(buffer) }
257Sokoban
0go
p59bg
(() => { 'use strict';
256Solve a Holy Knight's tour
10javascript
iahol
import static java.lang.Math.abs; import java.util.*; import static java.util.stream.Collectors.toList; import static java.util.stream.IntStream.range; public class NoConnection {
251Solve the no connection puzzle
9java
fxxdv
function sort_disjoint(values, indices) { var sublist = []; indices.sort(function(a, b) { return a > b; }); for (var i = 0; i < indices.length; i += 1) { sublist.push(values[indices[i]]); } sublist.sort(function(a, b) { return a < b; }); for (var i = 0; i < indices.length; i += 1) { values[indices[i]] = sublist.pop(); } return values; }
247Sort disjoint sublist
10javascript
agh10
(ns socket-example (:import (java.net Socket) (java.io PrintWriter))) (defn send-data [host msg] (with-open [sock (Socket. host 256) printer (PrintWriter. (.getOutputStream sock))] (.println printer msg))) (send-data "localhost" "hello socket world")
258Sockets
6clojure
4yn5o
package main import ( "fmt" "math/rand" "rcu" "time" ) func sleepingBeauty(reps int) float64 { wakings := 0 heads := 0 for i := 0; i < reps; i++ { coin := rand.Intn(2)
260Sleeping Beauty problem
0go
jlf7d
import Control.Monad (liftM) import Data.Array import Data.List (transpose) import Data.Maybe (mapMaybe) import qualified Data.Sequence as Seq import qualified Data.Set as Set import Prelude hiding (Left, Right) data Field = Space | Wall | Goal deriving (Eq) data Action = Up | Down | Left | Right | PushUp | PushDown | PushLeft | PushRight instance Show Action where show Up = "u" show Down = "d" show Left = "l" show Right = "r" show PushUp = "U" show PushDown = "D" show PushLeft = "L" show PushRight = "R" type Index = (Int, Int) type FieldArray = Array Index Field type BoxArray = Array Index Bool type PlayerPos = Index type GameState = (BoxArray, PlayerPos) type Game = (FieldArray, GameState) toField :: Char -> Field toField '#' = Wall toField ' ' = Space toField '@' = Space toField '$' = Space toField '.' = Goal toField '+' = Goal toField '*' = Goal toPush :: Action -> Action toPush Up = PushUp toPush Down = PushDown toPush Left = PushLeft toPush Right = PushRight toPush n = n toMove :: Action -> Index toMove PushUp = ( 0, -1) toMove PushDown = ( 0, 1) toMove PushLeft = (-1, 0) toMove PushRight = ( 1, 0) toMove n = toMove $ toPush n parseGame :: [String] -> Game parseGame fieldStrs = (field, (boxes, player)) where width = length $ head fieldStrs height = length fieldStrs bound = ((0, 0), (width - 1, height - 1)) flatField = concat $ transpose fieldStrs charField = listArray bound flatField field = fmap toField charField boxes = fmap (`elem` "$*") charField player = fst $ head $ filter (flip elem "@+" . snd) $ assocs charField add :: (Num a, Num b) => (a, b) -> (a, b) -> (a, b) add (a, b) (x, y) = (a + x, b + y) tryAction :: Game -> Action -> Maybe (Game, Action) tryAction (field, (boxes, player)) action | field ! vec == Wall = Nothing | boxes ! vec = if boxes ! vecB || field ! vecB == Wall then Nothing else Just ((field, (boxes // [(vec, False), (vecB, True)], vec)), toPush action) | otherwise = Just ((field, (boxes, vec)), action) where actionVec = toMove action vec = player `add` actionVec vecB = vec `add` actionVec solveGame :: Game -> Maybe [Action] solveGame (field, initState) = liftM reverse $ bfs (Seq.singleton (initState, [])) (Set.singleton initState) where goals = map fst $ filter ((== Goal) . snd) $ assocs field isSolved st = all (st !) goals possibleActions = [Up, Down, Left, Right] bfs :: Seq.Seq (GameState, [Action]) -> Set.Set GameState -> Maybe [Action] bfs queue visited = case Seq.viewl queue of Seq.EmptyL -> Nothing (game@(boxes, _), actions) Seq.:< queueB -> if isSolved boxes then Just actions else let newMoves = filter (flip Set.notMember visited . fst) $ map (\((_, g), a) -> (g, a)) $ mapMaybe (tryAction (field, game)) possibleActions visitedB = foldl (flip Set.insert) visited $ map fst newMoves queueC = foldl (Seq.|>) queueB $ map (\(g, a) -> (g, a:actions)) newMoves in bfs queueC visitedB exampleA :: [String] exampleA = ["#######" ,"# #" ,"# #" ,"#. # #" ,"#. $$ #" ,"#.$$ #" ,"#.# @#" ,"#######"] main :: IO () main = case solveGame $ parseGame exampleA of Nothing -> putStrLn "Unsolvable" Just solution -> do mapM_ putStrLn exampleA putStrLn "" putStrLn $ concatMap show solution
257Sokoban
8haskell
fxbd1
(() => { 'use strict';
251Solve the no connection puzzle
10javascript
yoo6r
data = [ '1.3.6.1.4.1.11.2.17.19.3.4.0.10', '1.3.6.1.4.1.11.2.17.5.2.0.79', '1.3.6.1.4.1.11.2.17.19.3.4.0.4', '1.3.6.1.4.1.11150.3.4.0.1', '1.3.6.1.4.1.11.2.17.19.3.4.0.1', '1.3.6.1.4.1.11150.3.4.0' ] for s in sorted(data, key=lambda x: list(map(int, x.split('.')))): print(s)
248Sort a list of object identifiers
3python
tq8fw
x = 'lions, tigers, and' y = 'bears, oh my!' z = '(from the )' x, y, z = [x, y, z].sort puts x, y, z x, y, z = 7.7444e4, -12, 18/2r x, y, z = [x, y, z].sort puts x, y, z
242Sort three variables
14ruby
kubhg
import Darwin func shuffle<T>(inout array: [T]) { for i in 1..<array.count { let j = Int(arc4random_uniform(UInt32(i))) (array[i], array[j]) = (array[j], array[i]) } } func issorted<T:Comparable>(ary: [T]) -> Bool { for i in 0..<(ary.count-1) { if ary[i] > ary[i+1] { return false } } return true } func bogosort<T:Comparable>(inout ary: [T]) { while!issorted(ary) { shuffle(&ary) } }
236Sorting algorithms/Bogosort
17swift
0pts6
import Data.Monoid (Sum(..)) import System.Random (randomIO) import Control.Monad (replicateM) import Data.Bool (bool) data Toss = Heads | Tails deriving Show anExperiment toss = moreWakenings <> case toss of Heads -> headsOnWaking Tails -> moreWakenings where moreWakenings = (1,0) headsOnWaking = (0,1) main = do tosses <- map (bool Heads Tails) <$> replicateM 1000000 randomIO let (Sum w, Sum h) = foldMap anExperiment tosses let ratio = fromIntegral h / fromIntegral w putStrLn $ "Ratio: " ++ show ratio
260Sleeping Beauty problem
8haskell
o148p
int *board, *flood, *known, top = 0, w, h; static inline int idx(int y, int x) { return y * w + x; } int neighbors(int c, int *p) { int i, j, n = 0; int y = c / w, x = c % w; for (i = y - 1; i <= y + 1; i++) { if (i < 0 || i >= h) continue; for (j = x - 1; j <= x + 1; j++) if (!(j < 0 || j >= w || (j == x && i == y) || board[ p[n] = idx(i,j) ] == -1)) n++; } return n; } void flood_fill(int c) { int i, n[8], nei; nei = neighbors(c, n); for (i = 0; i < nei; i++) { if (board[n[i]] || flood[n[i]]) continue; flood[n[i]] = 1; flood_fill(n[i]); } } int check_connectity(int lowerbound) { int c; memset(flood, 0, sizeof(flood[0]) * w * h); for (c = lowerbound + 1; c <= top; c++) if (known[c]) flood_fill(known[c]); for (c = 0; c < w * h; c++) if (!board[c] && !flood[c]) return 0; return 1; } void make_board(int x, int y, const char *s) { int i; w = x, h = y; top = 0; x = w * h; known = calloc(x + 1, sizeof(int)); board = calloc(x, sizeof(int)); flood = calloc(x, sizeof(int)); while (x--) board[x] = -1; for (y = 0; y < h; y++) for (x = 0; x < w; x++) { i = idx(y, x); while (isspace(*s)) s++; switch (*s) { case '_': board[i] = 0; case '.': break; default: known[ board[i] = strtol(s, 0, 10) ] = i; if (board[i] > top) top = board[i]; } while (*s && !isspace(*s)) s++; } } void show_board(const char *s) { int i, j, c; printf(, s); for (i = 0; i < h; i++, putchar('\n')) for (j = 0; j < w; j++) { c = board[ idx(i, j) ]; printf(!c ? : c == -1 ? : , c); } } int fill(int c, int n) { int i, nei, p[8], ko, bo; if ((board[c] && board[c] != n) || (known[n] && known[n] != c)) return 0; if (n == top) return 1; ko = known[n]; bo = board[c]; board[c] = n; if (check_connectity(n)) { nei = neighbors(c, p); for (i = 0; i < nei; i++) if (fill(p[i], n + 1)) return 1; } board[c] = bo; known[n] = ko; return 0; } int main() { make_board( 8,8, 3, 3, 50, 3, ); show_board(); fill(known[1], 1); show_board(); return 0; }
261Solve a Hidato puzzle
5c
0bvst
import java.util.*; public class Sokoban { String destBoard, currBoard; int playerX, playerY, nCols; Sokoban(String[] board) { nCols = board[0].length(); StringBuilder destBuf = new StringBuilder(); StringBuilder currBuf = new StringBuilder(); for (int r = 0; r < board.length; r++) { for (int c = 0; c < nCols; c++) { char ch = board[r].charAt(c); destBuf.append(ch != '$' && ch != '@' ? ch : ' '); currBuf.append(ch != '.' ? ch : ' '); if (ch == '@') { this.playerX = c; this.playerY = r; } } } destBoard = destBuf.toString(); currBoard = currBuf.toString(); } String move(int x, int y, int dx, int dy, String trialBoard) { int newPlayerPos = (y + dy) * nCols + x + dx; if (trialBoard.charAt(newPlayerPos) != ' ') return null; char[] trial = trialBoard.toCharArray(); trial[y * nCols + x] = ' '; trial[newPlayerPos] = '@'; return new String(trial); } String push(int x, int y, int dx, int dy, String trialBoard) { int newBoxPos = (y + 2 * dy) * nCols + x + 2 * dx; if (trialBoard.charAt(newBoxPos) != ' ') return null; char[] trial = trialBoard.toCharArray(); trial[y * nCols + x] = ' '; trial[(y + dy) * nCols + x + dx] = '@'; trial[newBoxPos] = '$'; return new String(trial); } boolean isSolved(String trialBoard) { for (int i = 0; i < trialBoard.length(); i++) if ((destBoard.charAt(i) == '.') != (trialBoard.charAt(i) == '$')) return false; return true; } String solve() { class Board { String cur, sol; int x, y; Board(String s1, String s2, int px, int py) { cur = s1; sol = s2; x = px; y = py; } } char[][] dirLabels = {{'u', 'U'}, {'r', 'R'}, {'d', 'D'}, {'l', 'L'}}; int[][] dirs = {{0, -1}, {1, 0}, {0, 1}, {-1, 0}}; Set<String> history = new HashSet<>(); LinkedList<Board> open = new LinkedList<>(); history.add(currBoard); open.add(new Board(currBoard, "", playerX, playerY)); while (!open.isEmpty()) { Board item = open.poll(); String cur = item.cur; String sol = item.sol; int x = item.x; int y = item.y; for (int i = 0; i < dirs.length; i++) { String trial = cur; int dx = dirs[i][0]; int dy = dirs[i][1];
257Sokoban
9java
0bgse
null
256Solve a Holy Knight's tour
11kotlin
14lpd
require 'HLPsolver' ADJACENT = [[-3, 0], [0, -3], [0, 3], [3, 0], [-2, -2], [-2, 2], [2, -2], [2, 2]] board1 = <<EOS . 0 0 . 0 0 . 0 0 0 0 0 0 0 0 0 0 0 0 0 0 . 0 0 0 0 0 . . . 0 0 0 . . . . . 1 . . . EOS t0 = Time.now HLPsolver.new(board1).solve puts
250Solve a Hopido puzzle
14ruby
cdf9k
null
247Sort disjoint sublist
11kotlin
4yl57
fn main() { let mut array = [5, 1, 3]; array.sort(); println!("Sorted: {:?}", array); array.sort_by(|a, b| b.cmp(a)); println!("Reverse sorted: {:?}", array); }
242Sort three variables
15rust
b5pkx
$ include "seed7_05.s7i"; const proc: genSort3 (in type: elemType) is func begin global const proc: doSort3 (in var elemType: x, in var elemType: y, in var elemType: z) is func local var array elemType: sorted is 0 times elemType.value; begin writeln("BEFORE: x=[" <& x <& "]; y=[" <& y <& "]; z=[" <& z <& "]"); sorted:= sort([](x, y, z)); x:= sorted[1]; y:= sorted[2]; z:= sorted[3]; writeln("AFTER: x=[" <& x <& "]; y=[" <& y <& "]; z=[" <& z <& "]"); end func; end global; end func; genSort3(integer); genSort3(string); const proc: main is func begin doSort3(77444, -12, 0); doSort3("lions, tigers, and", "bears, oh my!", "(from the \"Wizard of OZ\")"); end func;
242Sort three variables
16scala
are1n
use strict; sub gnome_sort { my @a = @_; my $size = scalar(@a); my $i = 1; my $j = 2; while($i < $size) { if ( $a[$i-1] <= $a[$i] ) { $i = $j; $j++; } else { @a[$i, $i-1] = @a[$i-1, $i]; $i--; if ($i == 0) { $i = $j; $j++; } } } return @a; }
238Sorting algorithms/Gnome sort
2perl
g9k4e
use strict; use warnings; sub sleeping_beauty { my($trials) = @_; my($gotheadsonwaking,$wakenings); $wakenings++ and rand > .5 ? $gotheadsonwaking++ : $wakenings++ for 1..$trials; $wakenings, $gotheadsonwaking/$wakenings } my $trials = 1_000_000; printf "Wakenings over $trials experiments:%d\nSleeping Beauty should estimate a credence of:%.4f\n", sleeping_beauty($trials);
260Sleeping Beauty problem
2perl
68p36
null
257Sokoban
11kotlin
er2a4
local p1, p1W = ".xxx.....x.xx....xxxxxxxxxx..x.xx.x..xxxsxxxxxx...xx.x.....xxx..", 8 local p2, p2W = ".....s.x..........x.x.........xxxxx.........xxx.......x..x.x..x..xxxxx...xxxxx..xx.....xx..xxxxx...xxxxx..x..x.x..x.......xxx.........xxxxx.........x.x..........x.x.....", 13 local puzzle, movesCnt, wid = {}, 0, 0 local moves = { { -1, -2 }, { 1, -2 }, { -1, 2 }, { 1, 2 }, { -2, -1 }, { -2, 1 }, { 2, -1 }, { 2, 1 } } function isValid( x, y ) return( x > 0 and x <= wid and y > 0 and y <= wid and puzzle[x + y * wid - wid] == 0 ) end function solve( x, y, s ) if s > movesCnt then return true end local test, a, b for i = 1, #moves do test = false a = x + moves[i][1]; b = y + moves[i][2] if isValid( a, b ) then puzzle[a + b * wid - wid] = s if solve( a, b, s + 1 ) then return true end puzzle[a + b * wid - wid] = 0 end end return false end function printSolution() local lp for j = 1, wid do for i = 1, wid do lp = puzzle[i + j * wid - wid] if lp == -1 then io.write( " " ) else io.write( string.format( "%.2d", lp ) ) end end print() end print( "\n" ) end local sx, sy function fill( pz, w ) puzzle = {}; wid = w; movesCnt = #pz local lp for i = 1, #pz do lp = pz:sub( i, i ) if lp == "x" then table.insert( puzzle, 0 ) elseif lp == "." then table.insert( puzzle, -1 ); movesCnt = movesCnt - 1 else table.insert( puzzle, 1 ) sx = 1 + ( i - 1 ) % wid; sy = math.floor( ( i + wid - 1 ) / wid ) end end end
256Solve a Holy Knight's tour
1lua
ag21v
null
251Solve the no connection puzzle
11kotlin
8pp0q
values = { 7, 6, 5, 4, 3, 2, 1, 0 } indices = { 6, 1, 7 } i = 1
247Sort disjoint sublist
1lua
gm24j
from random import choice def sleeping_beauty_experiment(repetitions): gotheadsonwaking = 0 wakenings = 0 for _ in range(repetitions): coin_result = choice([, ]) wakenings += 1 if coin_result == : gotheadsonwaking += 1 if coin_result == : wakenings += 1 if coin_result == : gotheadsonwaking += 1 print(, repetitions, , wakenings) return gotheadsonwaking / wakenings CREDENCE = sleeping_beauty_experiment(1_000_000) print(, CREDENCE)
260Sleeping Beauty problem
3python
yo16q
package main import ( "fmt" "math/big" ) var b = new(big.Int) func isSPDSPrime(n uint64) bool { nn := n for nn > 0 { r := nn % 10 if r != 2 && r != 3 && r != 5 && r != 7 { return false } nn /= 10 } b.SetUint64(n) if b.ProbablyPrime(0) {
259Smarandache prime-digital sequence
0go
dwjne
%w[ 1.3.6.1.4.1.11.2.17.19.3.4.0.10 1.3.6.1.4.1.11.2.17.5.2.0.79 1.3.6.1.4.1.11.2.17.19.3.4.0.4 1.3.6.1.4.1.11150.3.4.0.1 1.3.6.1.4.1.11.2.17.19.3.4.0.1 1.3.6.1.4.1.11150.3.4.0 ] .sort_by{|oid| oid.split().map(&:to_i)} .each{|oid| puts oid}
248Sort a list of object identifiers
14ruby
30iz7
func varSort<T: Comparable>(_ x: inout T, _ y: inout T, _ z: inout T) { let res = [x, y, z].sorted() x = res[0] y = res[1] z = res[2] } var x = "lions, tigers, and" var y = "bears, oh my!" var z = "(from the \"Wizard of OZ\")" print("Before:") print("x = \(x)") print("y = \(y)") print("z = \(z)") print() varSort(&x, &y, &z) print("After:") print("x = \(x)") print("y = \(y)") print("z = \(z)")
242Sort three variables
17swift
hvkj0
function gnomeSort($arr){ $i = 1; $j = 2; while($i < count($arr)){ if ($arr[$i-1] <= $arr[$i]){ $i = $j; $j++; }else{ list($arr[$i],$arr[$i-1]) = array($arr[$i-1],$arr[$i]); $i--; if($i == 0){ $i = $j; $j++; } } } return $arr; } $arr = array(3,1,6,2,9,4,7,8,5); echo implode(',',gnomeSort($arr));
238Sorting algorithms/Gnome sort
12php
nw3ig
beautyProblem <- function(n) { wakeCount <- headCount <- 0 for(i in seq_len(n)) { wakeCount <- wakeCount + 1 if(sample(c("H", "T"), 1) == "H") headCount <- headCount + 1 else wakeCount <- wakeCount + 1 } headCount/wakeCount } print(beautyProblem(10000000))
260Sleeping Beauty problem
13r
tqhfz
import Control.Monad (guard) import Math.NumberTheory.Primes.Testing (isPrime) import Data.List.Split (chunksOf) import Data.List (intercalate) import Text.Printf (printf) smarandache :: [Integer] smarandache = [2,3,5,7] <> s [2,3,5,7] >>= \x -> guard (isPrime x) >> [x] where s xs = r <> s r where r = xs >>= \x -> [x*10+2, x*10+3, x*10+5, x*10+7] nextSPDSTerms :: [Int] -> [(String, String)] nextSPDSTerms = go 1 smarandache where go _ _ [] = [] go c (x:xs) terms | c `elem` terms = (commas c, commas x): go nextCount xs (tail terms) | otherwise = go nextCount xs terms where nextCount = succ c commas :: Show a => a -> String commas = reverse . intercalate "," . chunksOf 3 . reverse . show main :: IO () main = do printf "The first 25 SPDS:\n%s\n\n" $ f smarandache mapM_ (uncurry (printf "The%9sth SPDS:%15s\n")) $ nextSPDSTerms [100, 1_000, 10_000, 100_000, 1_000_000] where f = show . take 25
259Smarandache prime-digital sequence
8haskell
56oug
use strict; use warnings qw(FATAL all); my @initial = split /\n/, <<''; =for space is an empty square @ is the player $ is a box . is a goal + is the player on a goal * is a box on a goal =cut my $cols = length($initial[0]); my $initial = join '', @initial; my $size = length($initial); die unless $size == $cols * @initial; sub WALL() { 1 } sub PLAYER() { 2 } sub BOX() { 4 } sub GOAL() { 8 } my %input = ( ' ' => 0, ' '.' => GOAL, '+' => PLAYER|GOAL, '*' => BOX|GOAL, ); my %output = reverse(%input); sub packed_initial { my $ret = ''; vec( $ret, $_, 4 ) = $input{substr $initial, $_, 1} for( 0 .. $size-1 ); $ret; } sub printable_board { my $board = shift; my @c = @output{map vec($board, $_, 4), 0 .. $size-1}; my $ret = ''; while( my @row = splice @c, 0, $cols ) { $ret .= join '', @row, "\n"; } $ret; } my $packed = packed_initial(); my @udlr = qw(u d l r); my @UDLR = qw(U D L R); my @deltas = (-$cols, +$cols, -1, +1); my %fseen; INIT_FORWARD: { $initial =~ /(\@|\+)/ or die; use vars qw(@ftodo @fnext); @ftodo = (["", $packed, $-[0]]); $fseen{$packed} = ''; } my %rseen; INIT_REVERSE: { my $goal = $packed; vec($goal, $ftodo[0][2], 4) -= PLAYER; my @u = grep { my $t = vec($goal, $_, 4); $t & GOAL and not $t & BOX } 0 .. $size-1; my @b = grep { my $t = vec($goal, $_, 4); $t & BOX and not $t & GOAL } 0 .. $size-1; die unless @u == @b; vec($goal, $_, 4) += BOX for @u; vec($goal, $_, 4) -= BOX for @b; use vars qw(@rtodo @rnext); FINAL_PLACE: for my $player (0 .. $size-1) { next if vec($goal, $player, 4); FIND_GOAL: { vec($goal, $player + $_, 4) & GOAL and last FIND_GOAL for @deltas; next FINAL_PLACE; } my $a_goal = $goal; vec($a_goal, $player, 4) += PLAYER; push @rtodo, ["", $a_goal, $player ]; $rseen{$a_goal} = ''; } } my $movelen = -1; my ($solution); MAIN: while( @ftodo and @rtodo ) { FORWARD: { my ($moves, $level, $player) = @{pop @ftodo}; die unless vec($level, $player, 4) & PLAYER; for my $dir_num (0 .. 3) { my $delta = $deltas[$dir_num]; my @loc = map $player + $delta * $_, 0 .. 2; my @val = map vec($level, $_, 4), @loc; next if $val[1] & WALL or ($val[1] & BOX and $val[2] & (BOX|WALL)); my $new = $level; vec($new, $loc[0], 4) -= PLAYER; vec($new, $loc[1], 4) += PLAYER; my $nmoves; if( $val[1] & BOX ) { vec($new, $loc[1], 4) -= BOX; vec($new, $loc[2], 4) += BOX; $nmoves = $moves . $UDLR[$dir_num]; } else { $nmoves = $moves . $udlr[$dir_num]; } next if exists $fseen{$new}; $fseen{$new} = $nmoves; push @fnext, [ $nmoves, $new, $loc[1] ]; exists $rseen{$new} or next; $solution = $new; last MAIN; } last FORWARD if @ftodo; use vars qw(*ftodo *fnext); (*ftodo, *fnext) = (\@fnext, \@ftodo); } BACKWARD: { my ($moves, $level, $player) = @{pop @rtodo}; die "<$level>" unless vec($level, $player, 4) & PLAYER; for my $dir_num (0 .. 3) { my $delta = $deltas[$dir_num]; my @loc = map $player + $delta * $_, -1 .. 1; my @val = map vec($level, $_, 4), @loc; next if $val[0] & (WALL|BOX); my $new = $level; vec($new, $loc[0], 4) += PLAYER; vec($new, $loc[1], 4) -= PLAYER; if( $val[2] & BOX ) { my $pull = $new; vec($pull, $loc[2], 4) -= BOX; vec($pull, $loc[1], 4) += BOX; goto RWALK if exists $rseen{$pull}; my $pmoves = $UDLR[$dir_num] . $moves; $rseen{$pull} = $pmoves; push @rnext, [$pmoves, $pull, $loc[0]]; goto RWALK unless exists $fseen{$pull}; print "Doing pull\n"; $solution = $pull; last MAIN; } RWALK: next if exists $rseen{$new}; my $wmoves = $udlr[$dir_num] . $moves; $rseen{$new} = $wmoves; push @rnext, [$wmoves, $new, $loc[0]]; next unless exists $fseen{$new}; print "Rwalk\n"; $solution = $new; last MAIN; } last BACKWARD if @rtodo; use vars qw(*rtodo *rnext); (*rtodo, *rnext) = (\@rnext, \@rtodo); } } if( $solution ) { my $fmoves = $fseen{$solution}; my $rmoves = $rseen{$solution}; print "Solution found!\n"; print "Time: ", (time() - $^T), " seconds\n"; print "Moves: $fmoves $rmoves\n"; print "Move Length: ", length($fmoves . $rmoves), "\n"; print "Middle Board: \n", printable_board($solution); } else { print "No solution found!\n"; } __END__
257Sokoban
2perl
cds9a
fn split(s: &str) -> impl Iterator<Item = u64> + '_ { s.split('.').map(|x| x.parse().unwrap()) } fn main() { let mut oids = vec![ "1.3.6.1.4.1.11.2.17.19.3.4.0.10", "1.3.6.1.4.1.11.2.17.5.2.0.79", "1.3.6.1.4.1.11.2.17.19.3.4.0.4", "1.3.6.1.4.1.11150.3.4.0.1", "1.3.6.1.4.1.11.2.17.19.3.4.0.1", "1.3.6.1.4.1.11150.3.4.0", ]; oids.sort_by(|a, b| Iterator::cmp(split(a), split(b))); println!("{:#?}", oids); }
248Sort a list of object identifiers
15rust
68n3l
def sleeping_beauty_experiment(n) coin = [:heads, :tails] gotheadsonwaking = 0 wakenings = 0 n.times do wakenings += 1 coin.sample == :heads? gotheadsonwaking += 1: wakenings += 1 end puts gotheadsonwaking / wakenings.to_f end puts
260Sleeping Beauty problem
14ruby
9nemz
public class SmarandachePrimeDigitalSequence { public static void main(String[] args) { long s = getNextSmarandache(7); System.out.printf("First 25 Smarandache prime-digital sequence numbers:%n2 3 5 7 "); for ( int count = 1 ; count <= 21 ; s = getNextSmarandache(s) ) { if ( isPrime(s) ) { System.out.printf("%d ", s); count++; } } System.out.printf("%n%n"); for (int i = 2 ; i <=5 ; i++ ) { long n = (long) Math.pow(10, i); System.out.printf("%,dth Smarandache prime-digital sequence number =%d%n", n, getSmarandachePrime(n)); } } private static final long getSmarandachePrime(long n) { if ( n < 10 ) { switch ((int) n) { case 1: return 2; case 2: return 3; case 3: return 5; case 4: return 7; } } long s = getNextSmarandache(7); long result = 0; for ( int count = 1 ; count <= n-4 ; s = getNextSmarandache(s) ) { if ( isPrime(s) ) { count++; result = s; } } return result; } private static final boolean isPrime(long test) { if ( test % 2 == 0 ) return false; for ( long i = 3 ; i <= Math.sqrt(test) ; i += 2 ) { if ( test % i == 0 ) { return false; } } return true; } private static long getNextSmarandache(long n) {
259Smarandache prime-digital sequence
9java
9nwmu