code
stringlengths
1
46.1k
label
class label
1.18k classes
domain_label
class label
21 classes
index
stringlengths
4
5
char nonblocking_getch(); void positional_putch(int x, int y, char ch); void millisecond_sleep(int n); void init_screen(); void update_screen(); void close_screen(); char nonblocking_getch() { return getch(); } void positional_putch(int x, int y, char ch) { mvaddch(x, y, ch); } void millisecond_sleep(int n) { struct timespec t = { 0, n * 1000000 }; nanosleep(&t, 0); } void update_screen() { refresh(); } void init_screen() { initscr(); noecho(); cbreak(); nodelay(stdscr, TRUE); } void close_screen() { endwin(); } int board[w * h]; int head; enum Dir { N, E, S, W } dir; int quit; enum State { SPACE=0, FOOD=1, BORDER=2 }; void age() { int i; for(i = 0; i < w * h; ++i) if(board[i] < 0) ++board[i]; } void plant() { int r; do r = rand() % (w * h); while(board[r] != SPACE); board[r] = FOOD; } void start(void) { int i; for(i = 0; i < w; ++i) board[i] = board[i + (h - 1) * w] = BORDER; for(i = 0; i < h; ++i) board[i * w] = board[i * w + w - 1] = BORDER; head = w * (h - 1 - h % 2) / 2; board[head] = -5; dir = N; quit = 0; srand(time(0)); plant(); } void step() { int len = board[head]; switch(dir) { case N: head -= w; break; case S: head += w; break; case W: --head; break; case E: ++head; break; } switch(board[head]) { case SPACE: board[head] = len - 1; age(); break; case FOOD: board[head] = len - 1; plant(); break; default: quit = 1; } } void show() { const char * symbol = ; int i; for(i = 0; i < w * h; ++i) positional_putch(i / w, i % w, board[i] < 0 ? ' update_screen(); } int main (int argc, char * argv[]) { init_screen(); start(); do { show(); switch(nonblocking_getch()) { case 'i': dir = N; break; case 'j': dir = W; break; case 'k': dir = S; break; case 'l': dir = E; break; case 'q': quit = 1; break; } step(); millisecond_sleep(100); } while(!quit); millisecond_sleep(999); close_screen(); return 0; }
262Snake
5c
dwgnv
package KT_Locations; use strict; use overload '""' => "as_string"; use English; use Class::Tiny qw(N locations); use List::Util qw(all); sub BUILD { my $self = shift; $self->{N} //= 8; $self->{N} >= 3 or die "N must be at least 3"; all {ref($ARG) eq 'ARRAY' && scalar(@{$ARG}) == 2} @{$self->{locations}} or die "At least one element of 'locations' is invalid"; return; } sub as_string { my $self = shift; my %idxs; my $idx = 1; foreach my $loc (@{$self->locations}) { $idxs{join(q{K},@{$loc})} = $idx++; } my $str; { my $w = int(log(scalar(@{$self->locations}))/log(10.)) + 2; my $fmt = "%${w}d"; my $N = $self->N; my $non_tour = q{ } x ($w-1) . q{-}; for (my $r=0; $r<$N; $r++) { for (my $f=0; $f<$N; $f++) { my $k = join(q{K}, $r, $f); $str .= exists($idxs{$k}) ? sprintf($fmt, $idxs{$k}) : $non_tour; } $str .= "\n"; } } return $str; } sub as_idx_hash { my $self = shift; my $N = $self->N; my $result; foreach my $pair (@{$self->locations}) { my ($r, $f) = @{$pair}; $result->{$r * $N + $f}++; } return $result; } package KnightsTour; use strict; use Class::Tiny qw( N start_location locations_to_visit str legal_move_idxs ); use English; use Parallel::ForkManager; use Time::HiRes qw( gettimeofday tv_interval ); sub BUILD { my $self = shift; if ($self->{str}) { my ($n, $sl, $ltv) = _parse_input_string($self->{str}); $self->{N} = $n; $self->{start_location} = $sl; $self->{locations_to_visit} = $ltv; } $self->{N} //= 8; $self->{N} >= 3 or die "N must be at least 3"; exists($self->{start_location}) or die "Must supply start_location"; die "start_location is invalid" if ref($self->{start_location}) ne 'ARRAY' || scalar(@{$self->{start_location}}) != 2; exists($self->{locations_to_visit}) or die "Must supply locations_to_visit"; ref($self->{locations_to_visit}) eq 'KT_Locations' or die "locations_to_visit must be a KT_Locations instance"; $self->{N} == $self->{locations_to_visit}->N or die "locations_to_visit has mismatched board size"; $self->precompute_legal_moves(); return; } sub _parse_input_string { my @rows = split(/[\r\n]+/s, shift); my $N = scalar(@rows); my ($start_location, @to_visit); for (my $r=0; $r<$N; $r++) { my $row_r = $rows[$r]; for (my $f=0; $f<$N; $f++) { my $c = substr($row_r, $f, 1); if ($c eq '1') { $start_location = [$r, $f]; } elsif ($c eq '0') { push @to_visit, [$r, $f]; } } } $start_location or die "No starting location provided"; return ($N, $start_location, KT_Locations->new(N => $N, locations => \@to_visit)); } sub precompute_legal_moves { my $self = shift; my $N = $self->{N}; my $ktl_ixs = $self->{locations_to_visit}->as_idx_hash(); for (my $r=0; $r<$N; $r++) { for (my $f=0; $f<$N; $f++) { my $k = $r * $N + $f; $self->{legal_move_idxs}->{$k} = _precompute_legal_move_idxs($r, $f, $N, $ktl_ixs); } } return; } sub _precompute_legal_move_idxs { my ($r, $f, $N, $ktl_ixs) = @ARG; my $r_plus_1 = $r + 1; my $r_plus_2 = $r + 2; my $r_minus_1 = $r - 1; my $r_minus_2 = $r - 2; my $f_plus_1 = $f + 1; my $f_plus_2 = $f + 2; my $f_minus_1 = $f - 1; my $f_minus_2 = $f - 2; my @result = grep { exists($ktl_ixs->{$ARG}) } map { $ARG->[0] * $N + $ARG->[1] } grep {$ARG->[0] >= 0 && $ARG->[0] < $N && $ARG->[1] >= 0 && $ARG->[1] < $N} ([$r_plus_2, $f_minus_1], [$r_plus_2, $f_plus_1], [$r_minus_2, $f_minus_1], [$r_minus_2, $f_plus_1], [$r_plus_1, $f_plus_2], [$r_plus_1, $f_minus_2], [$r_minus_1, $f_plus_2], [$r_minus_1, $f_minus_2]); return \@result; } sub find_tour { my $self = shift; my $num_to_visit = scalar(@{$self->locations_to_visit->locations}); my $N = $self->N; my $start_loc_idx = $self->start_location->[0] * $N + $self->start_location->[1]; my $visited; for (my $i=0; $i<$N*$N; $i++) { vec($visited, $i, 1) = 0; } vec($visited, $start_loc_idx, 1) = 1; my @next_loc_idxs = @{$self->legal_move_idxs->{$start_loc_idx}}; my $pm = new Parallel::ForkManager(scalar(@next_loc_idxs)); foreach my $next_loc_idx (@next_loc_idxs) { $pm->start and next; my $t0 = [gettimeofday]; vec($visited, $next_loc_idx, 1) = 1; my $tour = _find_tour_helper($N, $num_to_visit - 1, $next_loc_idx, $visited, $self->legal_move_idxs); my $elapsed = tv_interval($t0); my ($r, $f) = _idx_to_rank_and_file($next_loc_idx, $N); if (defined $tour) { my @tour_locs = map { [_idx_to_rank_and_file($ARG, $N)] } ($start_loc_idx, $next_loc_idx, split(/\s+/s, $tour)); my $kt_locs = KT_Locations->new(N => $N, locations => \@tour_locs); print "Found a tour after first move ($r, $f) ", "in $elapsed seconds:\n", $kt_locs, "\n"; } else { print "No tour found after first move ($r, $f). ", "Took $elapsed seconds.\n"; } $pm->finish; } $pm->wait_all_children; return; } sub _idx_to_rank_and_file { my ($idx, $N) = @ARG; my $f = $idx % $N; my $r = ($idx - $f) / $N; return ($r, $f); } sub _find_tour_helper { my ($N, $num_to_visit, $current_loc_idx, $visited, $legal_move_idxs) = @ARG; local *inner_helper = sub { my ($num_to_visit, $current_loc_idx, $visited) = @ARG; if ($num_to_visit == 0) { return q{ }; } my @next_loc_idxs = @{$legal_move_idxs->{$current_loc_idx}}; my $num_to_visit2 = $num_to_visit - 1; foreach my $loc_idx2 (@next_loc_idxs) { next if vec($visited, $loc_idx2, 1); my $visited2 = $visited; vec($visited2, $loc_idx2, 1) = 1; my $recursion = inner_helper($num_to_visit2, $loc_idx2, $visited2); return $loc_idx2 . q{ } . $recursion if defined $recursion; } return; }; return inner_helper($num_to_visit, $current_loc_idx, $visited); } package main; use strict; solve_size_8_problem(); solve_size_13_problem(); exit 0; sub solve_size_8_problem { my $problem = <<"END_SIZE_8_PROBLEM"; --000--- --0-00-- -0000000 000--0-0 0-0--000 1000000- --00-0-- ---000-- END_SIZE_8_PROBLEM my $kt = KnightsTour->new(str => $problem); print "Finding a tour for an 8x8 problem...\n"; $kt->find_tour(); return; } sub solve_size_13_problem { my $problem = <<"END_SIZE_13_PROBLEM"; -----1-0----- -----0-0----- ----00000---- -----000----- --0--0-0--0-- 00000---00000 --00-----00-- 00000---00000 --0--0-0--0-- -----000----- ----00000---- -----0-0----- -----0-0----- END_SIZE_13_PROBLEM my $kt = KnightsTour->new(str => $problem); print "Finding a tour for a 13x13 problem...\n"; $kt->find_tour(); return; }
256Solve a Holy Knight's tour
2perl
miqyz
use strict; use warnings; my $gap = qr/.{3}/s; find( <<terminator ); -AB- CDEF -GH- terminator sub find { my $p = shift; $p =~ /(\d)$gap.{0,2}(\d)(??{abs $1 - $2 <= 1? '': '(*F)'})/ || $p =~ /^.*\n.*(\d)(\d)(??{abs $1 - $2 <= 1? '': '(*F)'})/ and return; if( $p =~ /[A-H]/ ) { find( $p =~ s/[A-H]/$_/r ) for grep $p !~ $_, 1 .. 8; } else { print $p =~ tr/-/ /r; exit; } }
251Solve the no connection puzzle
2perl
4yy5d
package main import "fmt" import "sort" func main() { nums := []int {2, 4, 3, 1, 2} sort.Ints(nums) fmt.Println(nums) }
252Sort an integer array
0go
6803p
import Foundation public struct OID { public var val: String public init(_ val: String) { self.val = val } } extension OID: CustomStringConvertible { public var description: String { return val } } extension OID: Comparable { public static func < (lhs: OID, rhs: OID) -> Bool { let split1 = lhs.val.components(separatedBy: ".").compactMap(Int.init) let split2 = rhs.val.components(separatedBy: ".").compactMap(Int.init) let minSize = min(split1.count, split2.count) for i in 0..<minSize { if split1[i] < split2[i] { return true } else if split1[i] > split2[i] { return false } } return split1.count < split2.count } public static func == (lhs: OID, rhs: OID) -> Bool { return lhs.val == rhs.val } } let ids = [ "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" ].map(OID.init) for id in ids.sorted() { print(id) }
248Sort a list of object identifiers
17swift
zsotu
package main import ( "fmt" "net" ) func main() { conn, err := net.Dial("tcp", "localhost:256") if err != nil { fmt.Println(err) return } defer conn.Close() _, err = conn.Write([]byte("hello socket world")) if err != nil { fmt.Println(err) } }
258Sockets
0go
xjvwf
s = new java.net.Socket("localhost", 256) s << "hello socket world" s.close()
258Sockets
7groovy
p5mbo
let experiments = 1000000 var heads = 0 var wakenings = 0 for _ in (1...experiments) { wakenings += 1 switch (Int.random(in: 0...1)) { case 0: heads += 1 default: wakenings += 1 } } print("Wakenings over \(experiments) experiments: \(wakenings)") print("Sleeping Beauty should estimate a credence of: \(Double(heads) / Double(wakenings))")
260Sleeping Beauty problem
17swift
miayk
null
259Smarandache prime-digital sequence
1lua
30pzo
from array import array from collections import deque import psyco data = [] nrows = 0 px = py = 0 sdata = ddata = def init(board): global data, nrows, sdata, ddata, px, py data = filter(None, board.splitlines()) nrows = max(len(r) for r in data) maps = {' ':' ', '.': '.', '@':' ', ' mapd = {' ':' ', '.': ' ', '@':'@', ' for r, row in enumerate(data): for c, ch in enumerate(row): sdata += maps[ch] ddata += mapd[ch] if ch == '@': px = c py = r def push(x, y, dx, dy, data): if sdata[(y+2*dy) * nrows + x+2*dx] == ' data[(y+2*dy) * nrows + x+2*dx] != ' ': return None data2 = array(, data) data2[y * nrows + x] = ' ' data2[(y+dy) * nrows + x+dx] = '@' data2[(y+2*dy) * nrows + x+2*dx] = '*' return data2.tostring() def is_solved(data): for i in xrange(len(data)): if (sdata[i] == '.') != (data[i] == '*'): return False return True def solve(): open = deque([(ddata, , px, py)]) visited = set([ddata]) dirs = ((0, -1, 'u', 'U'), ( 1, 0, 'r', 'R'), (0, 1, 'd', 'D'), (-1, 0, 'l', 'L')) lnrows = nrows while open: cur, csol, x, y = open.popleft() for di in dirs: temp = cur dx, dy = di[0], di[1] if temp[(y+dy) * lnrows + x+dx] == '*': temp = push(x, y, dx, dy, temp) if temp and temp not in visited: if is_solved(temp): return csol + di[3] open.append((temp, csol + di[3], x+dx, y+dy)) visited.add(temp) else: if sdata[(y+dy) * lnrows + x+dx] == ' temp[(y+dy) * lnrows + x+dx] != ' ': continue data2 = array(, temp) data2[y * lnrows + x] = ' ' data2[(y+dy) * lnrows + x+dx] = '@' temp = data2.tostring() if temp not in visited: if is_solved(temp): return csol + di[2] open.append((temp, csol + di[2], x+dx, y+dy)) visited.add(temp) return level = psyco.full() init(level) print level, , solve()
257Sokoban
3python
lf0cv
package main import ( "fmt" "sort" ) type pair struct { name, value string } type csArray []pair
255Sort an array of composite structures
0go
xj4wf
println ([2,4,0,3,1,2,-12].sort())
252Sort an integer array
7groovy
dwen3
use feature 'say'; @strings = qw/Here are some sample strings to be sorted/; sub mycmp { length $b <=> length $a || lc $a cmp lc $b } say join ' ', sort mycmp @strings; say join ' ', sort {length $b <=> length $a || lc $a cmp lc $b} @strings say join ' ', map { $_->[0] } sort { $b->[1] <=> $a->[1] || $a->[2] cmp $b->[2] } map { [ $_, length, lc ] } @strings;
243Sort using a custom comparator
2perl
oao8x
use strict; use warnings; use feature 'say'; sub cocktail_sort { my @a = @_; while (1) { my $swapped_forward = 0; for my $i (0..$ if ($a[$i] gt $a[$i+1]) { @a[$i, $i+1] = @a[$i+1, $i]; $swapped_forward = 1; } } last if not $swapped_forward; my $swapped_backward = 0; for my $i (reverse 0..$ if ($a[$i] gt $a[$i+1]) { @a[$i, $i+1] = @a[$i+1, $i]; $swapped_backward = 1; } } last if not $swapped_backward; } @a } say join ' ', cocktail_sort( <t h e q u i c k b r o w n f o x j u m p s o v e r t h e l a z y d o g> );
240Sorting algorithms/Cocktail sort
2perl
2z5lf
import Network main = withSocketsDo $ sendTo "localhost" (PortNumber $ toEnum 256) "hello socket world"
258Sockets
8haskell
yoe66
class Holiday { def date def name Holiday(dateStr, name) { this.name = name; this.date = format.parse(dateStr) } String toString() { "${format.format date}: ${name}" } static format = new java.text.SimpleDateFormat("yyyy-MM-dd") } def holidays = [ new Holiday("2009-12-25", "Christmas Day"), new Holiday("2009-04-22", "Earth Day"), new Holiday("2009-09-07", "Labor Day"), new Holiday("2009-07-04", "Independence Day"), new Holiday("2009-10-31", "Halloween"), new Holiday("2009-05-25", "Memorial Day"), new Holiday("2009-03-14", "PI Day"), new Holiday("2009-01-01", "New Year's Day"), new Holiday("2009-12-31", "New Year's Eve"), new Holiday("2009-11-26", "Thanksgiving"), new Holiday("2009-02-14", "St. Valentine's Day"), new Holiday("2009-03-17", "St. Patrick's Day"), new Holiday("2009-01-19", "Martin Luther King Day"), new Holiday("2009-02-16", "President's Day") ] holidays.sort { x, y -> x.date <=> y.date } holidays.each { println it }
255Sort an array of composite structures
7groovy
p5lbo
nums = [2,4,3,1,2] :: [Int] sorted = List.sort nums
252Sort an integer array
8haskell
jlc7g
package main import "fmt" func main() { list := []int{31, 41, 59, 26, 53, 58, 97, 93, 23, 84} fmt.Println("unsorted:", list) bubblesort(list) fmt.Println("sorted! ", list) } func bubblesort(a []int) { for itemCount := len(a) - 1; ; itemCount-- { hasChanged := false for index := 0; index < itemCount; index++ { if a[index] > a[index+1] { a[index], a[index+1] = a[index+1], a[index] hasChanged = true } } if hasChanged == false { break } } }
246Sorting algorithms/Bubble sort
0go
56lul
use strict; use warnings; use feature 'say'; use feature 'state'; use ntheory qw<is_prime>; use Lingua::EN::Numbers qw(num2en_ordinal); my @prime_digits = <2 3 5 7>; my @spds = grep { is_prime($_) && /^[@{[join '',@prime_digits]}]+$/ } 1..100; my @p = map { $_+3, $_+7 } map { 10*$_ } @prime_digits; while ($ state $o++; my $oom = 10**(1+$o); my @q; for my $l (@prime_digits) { push @q, map { $l*$oom + $_ } @p; } push @spds, grep { is_prime($_) } @p = @q; } say 'Smarandache prime-digitals:'; printf "%22s:%s\n", ucfirst(num2en_ordinal($_)), $spds[$_-1] for 1..25, 100, 1000, 10_000, 100_000;
259Smarandache prime-digital sequence
2perl
bu6k4
package main import ( "errors" "fmt" "log" "math/rand" "time" termbox "github.com/nsf/termbox-go" ) func main() { rand.Seed(time.Now().UnixNano()) score, err := playSnake() if err != nil { log.Fatal(err) } fmt.Println("Final score:", score) } type snake struct { body []position
262Snake
0go
7cir2
int numPrimeFactors(unsigned x) { unsigned p = 2; int pf = 0; if (x == 1) return 1; else { while (true) { if (!(x % p)) { pf++; x /= p; if (x == 1) return pf; } else ++p; } } } void primeFactors(unsigned x, unsigned* arr) { unsigned p = 2; int pf = 0; if (x == 1) arr[pf] = 1; else { while (true) { if (!(x % p)) { arr[pf++] = p; x /= p; if (x == 1) return; } else p++; } } } unsigned sumDigits(unsigned x) { unsigned sum = 0, y; while (x) { y = x % 10; sum += y; x /= 10; } return sum; } unsigned sumFactors(unsigned* arr, int size) { unsigned sum = 0; for (int a = 0; a < size; a++) sum += sumDigits(arr[a]); return sum; } void listAllSmithNumbers(unsigned x) { unsigned *arr; for (unsigned a = 4; a < x; a++) { int numfactors = numPrimeFactors(a); arr = (unsigned*)malloc(numfactors * sizeof(unsigned)); if (numfactors < 2) continue; primeFactors(a, arr); if (sumDigits(a) == sumFactors(arr,numfactors)) printf(,a); free(arr); } } int main(int argc, char* argv[]) { printf(); listAllSmithNumbers(10000); return 0; }
263Smith numbers
5c
er6av
package main import ( "fmt" "sort" "strconv" "strings" ) var board [][]int var start, given []int func setup(input []string) { puzzle := make([][]string, len(input)) for i := 0; i < len(input); i++ { puzzle[i] = strings.Fields(input[i]) } nCols := len(puzzle[0]) nRows := len(puzzle) list := make([]int, nRows*nCols) board = make([][]int, nRows+2) for i := 0; i < nRows+2; i++ { board[i] = make([]int, nCols+2) for j := 0; j < nCols+2; j++ { board[i][j] = -1 } } for r := 0; r < nRows; r++ { row := puzzle[r] for c := 0; c < nCols; c++ { switch cell := row[c]; cell { case "_": board[r+1][c+1] = 0 case ".": break default: val, _ := strconv.Atoi(cell) board[r+1][c+1] = val list = append(list, val) if val == 1 { start = append(start, r+1, c+1) } } } } sort.Ints(list) given = make([]int, len(list)) for i := 0; i < len(given); i++ { given[i] = list[i] } } func solve(r, c, n, next int) bool { if n > given[len(given)-1] { return true } back := board[r][c] if back != 0 && back != n { return false } if back == 0 && given[next] == n { return false } if back == n { next++ } board[r][c] = n for i := -1; i < 2; i++ { for j := -1; j < 2; j++ { if solve(r+i, c+j, n+1, next) { return true } } } board[r][c] = back return false } func printBoard() { for _, row := range board { for _, c := range row { switch { case c == -1: fmt.Print(" . ") case c > 0: fmt.Printf("%2d ", c) default: fmt.Print("__ ") } } fmt.Println() } } func main() { input := []string{ "_ 33 35 _ _ . . .", "_ _ 24 22 _ . . .", "_ _ _ 21 _ _ . .", "_ 26 _ 13 40 11 . .", "27 _ _ _ 9 _ 1 .", ". . _ _ 18 _ _ .", ". . . . _ 7 _ _", ". . . . . . 5 _", } setup(input) printBoard() fmt.Println("\nFound:") solve(start[0], start[1], 1, 0) printBoard() }
261Solve a Hidato puzzle
0go
u3svt
from sys import stdout moves = [ [-1, -2], [1, -2], [-1, 2], [1, 2], [-2, -1], [-2, 1], [2, -1], [2, 1] ] def solve(pz, sz, sx, sy, idx, cnt): if idx > cnt: return 1 for i in range(len(moves)): x = sx + moves[i][0] y = sy + moves[i][1] if sz > x > -1 and sz > y > -1 and pz[x][y] == 0: pz[x][y] = idx if 1 == solve(pz, sz, x, y, idx + 1, cnt): return 1 pz[x][y] = 0 return 0 def find_solution(pz, sz): p = [[-1 for j in range(sz)] for i in range(sz)] idx = x = y = cnt = 0 for j in range(sz): for i in range(sz): if pz[idx] == : p[i][j] = 0 cnt += 1 elif pz[idx] == : p[i][j] = 1 cnt += 1 x = i y = j idx += 1 if 1 == solve(p, sz, x, y, 2, cnt): for j in range(sz): for i in range(sz): if p[i][j] != -1: stdout.write(.format(p[i][j], 2)) else: stdout.write() print() else: print() find_solution(, 8) print() find_solution(, 13)
256Solve a Holy Knight's tour
3python
9nsmf
import Data.List import Data.Function (on) data Person = P String Int deriving (Eq) instance Show Person where show (P name val) = "Person " ++ name ++ " with value " ++ show val instance Ord Person where compare (P a _) (P b _) = compare a b pVal :: Person -> Int pVal (P _ x) = x people :: [Person] people = [P "Joe" 12, P "Bob" 8, P "Alice" 9, P "Harry" 2] main :: IO () main = do mapM_ print $ sort people putStrLn [] mapM_ print $ sortBy (on compare pVal) people
255Sort an array of composite structures
8haskell
yoq66
from __future__ import print_function from itertools import permutations from enum import Enum A, B, C, D, E, F, G, H = Enum('Peg', 'A, B, C, D, E, F, G, H') connections = ((A, C), (A, D), (A, E), (B, D), (B, E), (B, F), (G, C), (G, D), (G, E), (H, D), (H, E), (H, F), (C, D), (D, E), (E, F)) def ok(conn, perm): this, that = (c.value - 1 for c in conn) return abs(perm[this] - perm[that]) != 1 def solve(): return [perm for perm in permutations(range(1, 9)) if all(ok(conn, perm) for conn in connections)] if __name__ == '__main__': solutions = solve() print(, ', '.join(str(i) for i in solutions[0]))
251Solve the no connection puzzle
3python
gmm4h
<?php function mycmp($s1, $s2) { if ($d = strlen($s2) - strlen($s1)) return $d; return strcasecmp($s1, $s2); } $strings = array(, , , , , , , ); usort($strings, ); ?>
243Sort using a custom comparator
12php
g9g42
def makeSwap = { a, i, j = i+1 -> print "."; a[[i,j]] = a[[j,i]] } def checkSwap = { a, i, j = i+1 -> [(a[i] > a[j])].find { it }.each { makeSwap(a, i, j) } } def bubbleSort = { list -> boolean swapped = true while (swapped) { swapped = (1..<list.size()).any { checkSwap(list, it-1) } } list }
246Sorting algorithms/Bubble sort
7groovy
cd69i
function cocktailSort($arr){ if (is_string($arr)) $arr = str_split(preg_replace('/\s+/','',$arr)); do{ $swapped = false; for($i=0;$i<count($arr);$i++){ if(isset($arr[$i+1])){ if($arr[$i] > $arr[$i+1]){ list($arr[$i], $arr[$i+1]) = array($arr[$i+1], $arr[$i]); $swapped = true; } } } if ($swapped == false) break; $swapped = false; for($i=count($arr)-1;$i>=0;$i--){ if(isset($arr[$i-1])){ if($arr[$i] < $arr[$i-1]) { list($arr[$i],$arr[$i-1]) = array($arr[$i-1],$arr[$i]); $swapped = true; } } } }while($swapped); return $arr; } $arr = array(5, 1, 7, 3, 6, 4, 2); $arr2 = array(, , , , ); $strg = ; $arr = cocktailSort($arr); $arr2 = cocktailSort($arr2); $strg = cocktailSort($strg); echo implode(',',$arr) . '<br>'; echo implode(',',$arr2) . '<br>'; echo implode('',$strg) . '<br>';
240Sorting algorithms/Cocktail sort
12php
sboqs
import java.io.IOException; import java.net.*; public class SocketSend { public static void main(String args[]) throws IOException { sendData("localhost", "hello socket world"); } public static void sendData(String host, String msg) throws IOException { Socket sock = new Socket( host, 256 ); sock.getOutputStream().write(msg.getBytes()); sock.getOutputStream().flush(); sock.close(); } }
258Sockets
9java
dwhn9
import Control.Monad.Random (getRandomRs) import Graphics.Gloss.Interface.Pure.Game import Lens.Micro ((%~), (^.), (&), set) import Lens.Micro.TH (makeLenses) data Snake = Snake { _body :: [Point], _direction :: Point } makeLenses ''Snake data World = World { _snake :: Snake , _food :: [Point] , _score :: Int , _maxScore :: Int } makeLenses ''World moves (Snake b d) = Snake (step b d: init b) d eats (Snake b d) = Snake (step b d: b) d bites (Snake b _) = any (== head b) step ((x,y):_) (a,b) = (x+a, y+b) turn (x',y') (Snake b (x,y)) | (x+x',y+y') == (0,0) = Snake b (x,y) | otherwise = Snake b (x',y') createWorld = do xs <- map fromIntegral <$> getRandomRs (2, 38 :: Int) ys <- map fromIntegral <$> getRandomRs (2, 38 :: Int) return (Ok, World snake (zip xs ys) 0 0) where snake = Snake [(20, 20)] (1,0) data Status = Ok | Fail | Stop continue = \x -> (Ok, x) stop = \x -> (Stop, x) f >>> g = \x -> case f x of { (Ok, y) -> g y; b -> b } f <|> g = \x -> case f x of { (Fail, _) -> g x; b -> b } p ==> f = \x -> if p x then f x else (Fail, x) l .& f = continue . (l %~ f) l .= y = continue . set l y updateWorld _ = id >>> (snakeEats <|> snakeMoves) where snakeEats = (snakeFindsFood ==> (snake .& eats)) >>> (score .& (+1)) >>> (food .& tail) snakeMoves = (snakeBitesTail ==> stop) <|> (snakeHitsWall ==> stop) <|> (snake .& moves) snakeFindsFood w = (w^.snake & moves) `bites` (w^.food & take 1) snakeBitesTail w = (w^.snake) `bites` (w^.snake.body & tail) snakeHitsWall w = (w^.snake.body) & head & isOutside isOutside (x,y) = or [x <= 0, 40 <= x, y <= 0, 40 <= y] handleEvents e (s,w) = f w where f = case s of Ok -> case e of EventKey (SpecialKey k) _ _ _ -> case k of KeyRight -> snake .& turn (1,0) KeyLeft -> snake .& turn (-1,0) KeyUp -> snake .& turn (0,1) KeyDown -> snake .& turn (0,-1) _-> continue _-> continue _-> \w -> w & ((snake.body) .= [(20,20)]) >>> (maxScore .& max (w^.score)) >>> (score .= 0) renderWorld (s, w) = pictures [frame, color c drawSnake, drawFood, showScore] where c = case s of { Ok -> orange; _-> red } drawSnake = foldMap (rectangleSolid 10 10 `at`) (w^.snake.body) drawFood = color blue $ circleSolid 5 `at` (w^.food & head) frame = color black $ rectangleWire 400 400 showScore = color orange $ scale 0.2 0.2 $ txt `at` (-80,130) txt = Text $ mconcat ["Score: ", w^.score & show ," Maximal score: ", w^.maxScore & show] at p (x,y) = Translate (10*x-200) (10*y-200) p main = do world <- createWorld play inW white 7 world renderWorld handleEvents updateWorld where inW = InWindow "The Snake" (400, 400) (10, 10)
262Snake
8haskell
8pv0z
import qualified Data.IntMap as I import Data.IntMap (IntMap) import Data.List import Data.Maybe import Data.Time.Clock data BoardProblem = Board { cells :: IntMap (IntMap Int) , endVal :: Int , onePos :: (Int, Int) , givens :: [Int] } deriving (Show, Eq) tupIns x y v m = I.insert x (I.insert y v (I.findWithDefault I.empty x m)) m tupLookup x y m = I.lookup x m >>= I.lookup y makeBoard = (\x -> x { givens = dropWhile (<= 1) $ sort $ givens x }) . foldl' f (Board I.empty 0 (0, 0) []) . concatMap (zip [0 ..]) . zipWith (\y w -> map (y, ) $ words w) [0 ..] where f bd (x, (y, v)) = if v == "." then bd else Board (tupIns x y (read v) (cells bd)) (if read v > endVal bd then read v else endVal bd) (if v == "1" then (x, y) else onePos bd) (read v: givens bd) hidato brd = listToMaybe $ h 2 (cells brd) (onePos brd) (givens brd) where h nval pmap (x, y) gs | nval == endVal brd = [pmap] | nval == head gs = if null nvalAdj then [] else h (nval + 1) pmap (fst $ head nvalAdj) (tail gs) | not $ null nvalAdj = h (nval + 1) pmap (fst $ head nvalAdj) gs | otherwise = hEmptyAdj where around = [ (x - 1, y - 1) , (x, y - 1) , (x + 1, y - 1) , (x - 1, y) , (x + 1, y) , (x - 1, y + 1) , (x, y + 1) , (x + 1, y + 1) ] lkdUp = map (\(x, y) -> ((x, y), tupLookup x y pmap)) around nvalAdj = filter ((== Just nval) . snd) lkdUp hEmptyAdj = concatMap (\((nx, ny), _) -> h (nval + 1) (tupIns nx ny nval pmap) (nx, ny) gs) $ filter ((== Just 0) . snd) lkdUp printCellMap cellmap = putStrLn $ concat strings where maxPos = xyBy I.findMax maximum minPos = xyBy I.findMin minimum xyBy :: (forall a. IntMap a -> (Int, a)) -> ([Int] -> Int) -> (Int, Int) xyBy a b = (fst (a cellmap), b $ map (fst . a . snd) $ I.toList cellmap) strings = map f [ (x, y) | y <- [snd minPos .. snd maxPos] , x <- [fst minPos .. fst maxPos] ] f (x, y) = let z = if x == fst maxPos then "\n" else " " in case tupLookup x y cellmap of Nothing -> " " ++ z Just n -> (if n < 10 then ' ': show n else show n) ++ z main = do let sampleBoard = makeBoard sample printCellMap $ cells sampleBoard printCellMap $ fromJust $ hidato sampleBoard sample = [ " 0 33 35 0 0" , " 0 0 24 22 0" , " 0 0 0 21 0 0" , " 0 26 0 13 40 11" , "27 0 0 0 9 0 1" , ". . 0 0 18 0 0" , ". . . . 0 7 0 0" , ". . . . . . 5 0" ]
261Solve a Hidato puzzle
8haskell
w79ed
require 'set' class Sokoban def initialize(level) board = level.each_line.map(&:rstrip) @nrows = board.map(&:size).max board.map!{|line| line.ljust(@nrows)} board.each_with_index do |row, r| row.each_char.with_index do |ch, c| @px, @py = c, r if ch == '@' or ch == '+' end end @goal = board.join.tr(' .@ .each_char.with_index.select{|ch, c| ch == '.'} .map(&:last) @board = board.join.tr(' .@ end def pos(x, y) y * @nrows + x end def push(x, y, dx, dy, board) return if board[pos(x+2*dx, y+2*dy)]!= ' ' board[pos(x , y )] = ' ' board[pos(x + dx, y + dy)] = '@' board[pos(x+2*dx, y+2*dy)] = '$' end def solved?(board) @goal.all?{|i| board[i] == '$'} end DIRS = [[0, -1, 'u', 'U'], [ 1, 0, 'r', 'R'], [0, 1, 'd', 'D'], [-1, 0, 'l', 'L']] def solve queue = [[@board, , @px, @py]] visited = Set[@board] until queue.empty? current, csol, x, y = queue.shift for dx, dy, cmove, cpush in DIRS work = current.dup case work[pos(x+dx, y+dy)] when '$' next unless push(x, y, dx, dy, work) next unless visited.add?(work) return csol+cpush if solved?(work) queue << [work, csol+cpush, x+dx, y+dy] when ' ' work[pos(x, y)] = ' ' work[pos(x+dx, y+dy)] = '@' queue << [work, csol+cmove, x+dx, y+dy] if visited.add?(work) end end end end end
257Sokoban
14ruby
vzo2n
bsort :: Ord a => [a] -> [a] bsort s = case _bsort s of t | t == s -> t | otherwise -> bsort t where _bsort (x:x2:xs) | x > x2 = x2:(_bsort (x:xs)) | otherwise = x:(_bsort (x2:xs)) _bsort s = s
246Sorting algorithms/Bubble sort
8haskell
xj1w4
>>> def gnomesort(a): i,j,size = 1,2,len(a) while i < size: if a[i-1] <= a[i]: i,j = j, j+1 else: a[i-1],a[i] = a[i],a[i-1] i -= 1 if i == 0: i,j = j, j+1 return a >>> gnomesort([3,4,2,5,1,6]) [1, 2, 3, 4, 5, 6] >>>
238Sorting algorithms/Gnome sort
3python
rcbgq
null
258Sockets
11kotlin
0b4sf
def divisors(n): divs = [1] for ii in range(2, int(n ** 0.5) + 3): if n% ii == 0: divs.append(ii) divs.append(int(n / ii)) divs.append(n) return list(set(divs)) def is_prime(n): return len(divisors(n)) == 2 def digit_check(n): if len(str(n))<2: return True else: for digit in str(n): if not is_prime(int(digit)): return False return True def sequence(max_n=None): ii = 0 n = 0 while True: ii += 1 if is_prime(ii): if max_n is not None: if n>max_n: break if digit_check(ii): n += 1 yield ii if __name__ == '__main__': generator = sequence(100) for index, item in zip(range(1, 16), generator): print(index, item) for index, item in zip(range(16, 100), generator): pass print(100, generator.__next__())
259Smarandache prime-digital sequence
3python
p5ybm
import java.util.Arrays; import java.util.Comparator; public class SortComp { public static class Pair { public String name; public String value; public Pair(String n, String v) { name = n; value = v; } } public static void main(String[] args) { Pair[] pairs = {new Pair("06-07", "Ducks"), new Pair("00-01", "Avalanche"), new Pair("02-03", "Devils"), new Pair("01-02", "Red Wings"), new Pair("03-04", "Lightning"), new Pair("04-05", "lockout"), new Pair("05-06", "Hurricanes"), new Pair("99-00", "Devils"), new Pair("07-08", "Red Wings"), new Pair("08-09", "Penguins")}; sortByName(pairs); for (Pair p : pairs) { System.out.println(p.name + " " + p.value); } } public static void sortByName(Pair[] pairs) { Arrays.sort(pairs, new Comparator<Pair>() { public int compare(Pair p1, Pair p2) { return p1.name.compareTo(p2.name); } }); } }
255Sort an array of composite structures
9java
dwpn9
socket = require "socket" host, port = "127.0.0.1", 256 sid = socket.udp() sid:sendto( "hello socket world", host, port ) sid:close()
258Sockets
1lua
8pg0e
const L = 1, R = 2, D = 4, U = 8; var block = 24, wid = 30, hei = 20, frameR = 7, fruit, snake; function Snake() { this.length = 1; this.alive = true; this.pos = createVector( 1, 1 ); this.posArray = []; this.posArray.push( createVector( 1, 1 ) ); this.dir = R; this.draw = function() { fill( 130, 190, 0 ); var pos, i = this.posArray.length - 1, l = this.length; while( true ){ pos = this.posArray[i--]; rect( pos.x * block, pos.y * block, block, block ); if( --l == 0 ) break; } } this.eat = function( frut ) { var b = this.pos.x == frut.x && this.pos.y == frut.y; if( b ) this.length++; return b; } this.overlap = function() { var len = this.posArray.length - 1; for( var i = len; i > len - this.length; i-- ) { tp = this.posArray[i]; if( tp.x === this.pos.x && tp.y === this.pos.y ) return true; } return false; } this.update = function() { if( !this.alive ) return; switch( this.dir ) { case L: this.pos.x--; if( this.pos.x < 1 ) this.pos.x = wid - 2; break; case R: this.pos.x++; if( this.pos.x > wid - 2 ) this.pos.x = 1; break; case U: this.pos.y--; if( this.pos.y < 1 ) this.pos.y = hei - 2; break; case D: this.pos.y++; if( this.pos.y > hei - 2 ) this.pos.y = 1; break; } if( this.overlap() ) { this.alive = false; } else { this.posArray.push( createVector( this.pos.x, this.pos.y ) ); if( this.posArray.length > 5000 ) { this.posArray.splice( 0, 1 ); } } } } function Fruit() { this.fruitTime = true; this.pos = createVector(); this.draw = function() { fill( 200, 50, 20 ); rect( this.pos.x * block, this.pos.y * block, block, block ); } this.setFruit = function() { this.pos.x = floor( random( 1, wid - 1 ) ); this.pos.y = floor( random( 1, hei - 1 ) ); this.fruitTime = false; } } function setup() { createCanvas( block * wid, block * hei ); noStroke(); frameRate( frameR ); snake = new Snake();fruit = new Fruit(); } function keyPressed() { switch( keyCode ) { case LEFT_ARROW: snake.dir = L; break; case RIGHT_ARROW: snake.dir = R; break; case UP_ARROW: snake.dir = U; break; case DOWN_ARROW: snake.dir = D; } } function draw() { background( color( 0, 0x22, 0 ) ); fill( 20, 50, 120 ); for( var i = 0; i < wid; i++ ) { rect( i * block, 0, block, block ); rect( i * block, height - block, block, block ); } for( var i = 1; i < hei - 1; i++ ) { rect( 1, i * block, block, block ); rect( width - block, i * block, block, block ); } if( fruit.fruitTime ) { fruit.setFruit(); frameR += .2; frameRate( frameR ); } fruit.draw(); snake.update(); if( snake.eat( fruit.pos ) ) { fruit.fruitTime = true; } snake.draw(); fill( 200 ); textStyle( BOLD ); textAlign( RIGHT ); textSize( 120 ); text( ""+( snake.length - 1 ), 690, 440 ); if( !snake.alive ) text( "THE END", 630, 250 ); }
262Snake
9java
erya5
(defn divisible? [a b] (zero? (mod a b))) (defn prime? [n] (and (> n 1) (not-any? (partial divisible? n) (range 2 n)))) (defn prime-factors ([n] (prime-factors n 2 '())) ([n candidate acc] (cond (<= n 1) (reverse acc) (zero? (rem n candidate)) (recur (/ n candidate) candidate (cons candidate acc)) :else (recur n (inc candidate) acc)))) (defn sum-digits [n] (reduce + (map #(- (int %) (int \0)) (str n)))) (defn smith-number? [n] (and (not (prime? n)) (= (sum-digits n) (sum-digits (clojure.string/join "" (prime-factors n)))))) (filter smith-number? (range 1 10000))
263Smith numbers
6clojure
0blsj
import java.util.ArrayList; import java.util.Collections; import java.util.List; public class Hidato { private static int[][] board; private static int[] given, start; public static void main(String[] args) { String[] input = {"_ 33 35 _ _ . . .", "_ _ 24 22 _ . . .", "_ _ _ 21 _ _ . .", "_ 26 _ 13 40 11 . .", "27 _ _ _ 9 _ 1 .", ". . _ _ 18 _ _ .", ". . . . _ 7 _ _", ". . . . . . 5 _"}; setup(input); printBoard(); System.out.println("\nFound:"); solve(start[0], start[1], 1, 0); printBoard(); } private static void setup(String[] input) { String[][] puzzle = new String[input.length][]; for (int i = 0; i < input.length; i++) puzzle[i] = input[i].split(" "); int nCols = puzzle[0].length; int nRows = puzzle.length; List<Integer> list = new ArrayList<>(nRows * nCols); board = new int[nRows + 2][nCols + 2]; for (int[] row : board) for (int c = 0; c < nCols + 2; c++) row[c] = -1; for (int r = 0; r < nRows; r++) { String[] row = puzzle[r]; for (int c = 0; c < nCols; c++) { String cell = row[c]; switch (cell) { case "_": board[r + 1][c + 1] = 0; break; case ".": break; default: int val = Integer.parseInt(cell); board[r + 1][c + 1] = val; list.add(val); if (val == 1) start = new int[]{r + 1, c + 1}; } } } Collections.sort(list); given = new int[list.size()]; for (int i = 0; i < given.length; i++) given[i] = list.get(i); } private static boolean solve(int r, int c, int n, int next) { if (n > given[given.length - 1]) return true; if (board[r][c] != 0 && board[r][c] != n) return false; if (board[r][c] == 0 && given[next] == n) return false; int back = board[r][c]; if (back == n) next++; board[r][c] = n; for (int i = -1; i < 2; i++) for (int j = -1; j < 2; j++) if (solve(r + i, c + j, n + 1, next)) return true; board[r][c] = back; return false; } private static void printBoard() { for (int[] row : board) { for (int c : row) { if (c == -1) System.out.print(" . "); else System.out.printf(c > 0 ? "%2d " : "__ ", c); } System.out.println(); } } }
261Solve a Hidato puzzle
9java
kvthm
require 'HLPsolver' ADJACENT = [[-1,-2],[-2,-1],[-2,1],[-1,2],[1,2],[2,1],[2,-1],[1,-2]] boardy = <<EOS . . 0 0 0 . . 0 . 0 0 . 0 0 0 0 0 0 0 0 0 0 . . 0 . 0 0 . 0 . . 0 0 0 1 0 0 0 0 0 0 . . 0 0 . 0 . . . 0 0 0 EOS t0 = Time.now HLPsolver.new(boardy).solve puts
256Solve a Holy Knight's tour
14ruby
lf8cl
var arr = [ {id: 3, value: "foo"}, {id: 2, value: "bar"}, {id: 4, value: "baz"}, {id: 1, value: 42}, {id: 5, something: "another string"}
255Sort an array of composite structures
10javascript
68x38
require 'HLPSolver' ADJACENT = [[0,0]] A,B,C,D,E,F,G,H = [0,1],[0,2],[1,0],[1,1],[1,2],[1,3],[2,1],[2,2] board1 = <<EOS . 0 0 . 0 0 1 0 . 0 0 . EOS g = HLPsolver.new(board1) g.board[A[0]][A[1]].adj = [B,G,H,F] g.board[B[0]][B[1]].adj = [A,C,G,H] g.board[C[0]][C[1]].adj = [B,E,F,H] g.board[D[0]][D[1]].adj = [F] g.board[E[0]][E[1]].adj = [C] g.board[F[0]][F[1]].adj = [A,C,D,G] g.board[G[0]][G[1]].adj = [A,B,F,H] g.board[H[0]][H[1]].adj = [A,B,C,G] g.solve
251Solve the no connection puzzle
14ruby
7ccri
import java.util.Arrays; public class Example { public static void main(String[] args) { int[] nums = {2,4,3,1,2}; Arrays.sort(nums); } }
252Sort an integer array
9java
u3zvv
function int_arr(a, b) { return a - b; } var numbers = [20, 7, 65, 10, 3, 0, 8, -60]; numbers.sort(int_arr); document.write(numbers);
252Sort an integer array
10javascript
7c9rd
use strict ; sub disjointSort { my ( $values , @indices ) = @_ ; @{$values}[ sort @indices ] = sort @{$values}[ @indices ] ; } my @values = ( 7 , 6 , 5 , 4 , 3 , 2 , 1 , 0 ) ; my @indices = ( 6 , 1 , 7 ) ; disjointSort( \@values , @indices ) ; print "[@values]\n" ;
247Sort disjoint sublist
2perl
iaqo3
gnomesort <- function(x) { i <- 1 j <- 1 while(i < length(x)) { if(x[i] <= x[i+1]) { i <- j j <- j+1 } else { temp <- x[i] x[i] <- x[i+1] x[i+1] <- temp i <- i - 1 if(i == 0) { i <- j j <- j+1 } } } x } gnomesort(c(4, 65, 2, -31, 0, 99, 83, 782, 1))
238Sorting algorithms/Gnome sort
13r
u67vx
const L = 1, R = 2, D = 4, U = 8; var block = 24, wid = 30, hei = 20, frameR = 7, fruit, snake; function Snake() { this.length = 1; this.alive = true; this.pos = createVector( 1, 1 ); this.posArray = []; this.posArray.push( createVector( 1, 1 ) ); this.dir = R; this.draw = function() { fill( 130, 190, 0 ); var pos, i = this.posArray.length - 1, l = this.length; while( true ){ pos = this.posArray[i--]; rect( pos.x * block, pos.y * block, block, block ); if( --l == 0 ) break; } } this.eat = function( frut ) { var b = this.pos.x == frut.x && this.pos.y == frut.y; if( b ) this.length++; return b; } this.overlap = function() { var len = this.posArray.length - 1; for( var i = len; i > len - this.length; i-- ) { tp = this.posArray[i]; if( tp.x === this.pos.x && tp.y === this.pos.y ) return true; } return false; } this.update = function() { if( !this.alive ) return; switch( this.dir ) { case L: this.pos.x--; if( this.pos.x < 1 ) this.pos.x = wid - 2; break; case R: this.pos.x++; if( this.pos.x > wid - 2 ) this.pos.x = 1; break; case U: this.pos.y--; if( this.pos.y < 1 ) this.pos.y = hei - 2; break; case D: this.pos.y++; if( this.pos.y > hei - 2 ) this.pos.y = 1; break; } if( this.overlap() ) { this.alive = false; } else { this.posArray.push( createVector( this.pos.x, this.pos.y ) ); if( this.posArray.length > 5000 ) { this.posArray.splice( 0, 1 ); } } } } function Fruit() { this.fruitTime = true; this.pos = createVector(); this.draw = function() { fill( 200, 50, 20 ); rect( this.pos.x * block, this.pos.y * block, block, block ); } this.setFruit = function() { this.pos.x = floor( random( 1, wid - 1 ) ); this.pos.y = floor( random( 1, hei - 1 ) ); this.fruitTime = false; } } function setup() { createCanvas( block * wid, block * hei ); noStroke(); frameRate( frameR ); snake = new Snake();fruit = new Fruit(); } function keyPressed() { switch( keyCode ) { case LEFT_ARROW: snake.dir = L; break; case RIGHT_ARROW: snake.dir = R; break; case UP_ARROW: snake.dir = U; break; case DOWN_ARROW: snake.dir = D; } } function draw() { background( color( 0, 0x22, 0 ) ); fill( 20, 50, 120 ); for( var i = 0; i < wid; i++ ) { rect( i * block, 0, block, block ); rect( i * block, height - block, block, block ); } for( var i = 1; i < hei - 1; i++ ) { rect( 1, i * block, block, block ); rect( width - block, i * block, block, block ); } if( fruit.fruitTime ) { fruit.setFruit(); frameR += .2; frameRate( frameR ); } fruit.draw(); snake.update(); if( snake.eat( fruit.pos ) ) { fruit.fruitTime = true; } snake.draw(); fill( 200 ); textStyle( BOLD ); textAlign( RIGHT ); textSize( 120 ); text( ""+( snake.length - 1 ), 690, 440 ); if( !snake.alive ) text( "THE END", 630, 250 ); }
262Snake
10javascript
0b2sz
null
255Sort an array of composite structures
11kotlin
0b7sf
object NoConnection extends App { private def links = Seq( Seq(2, 3, 4),
251Solve the no connection puzzle
16scala
buuk6
strings = .split() def mykey(x): return -len(x), x.upper() print sorted(strings, key=mykey)
243Sort using a custom comparator
3python
ieiof
fn is_prime(n: u32) -> bool { 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; } let mut p = 7; const WHEEL: [u32; 8] = [4, 2, 4, 2, 4, 6, 2, 6]; loop { for w in &WHEEL { if p * p > n { return true; } if n% p == 0 { return false; } p += w; } } } fn next_prime_digit_number(n: u32) -> u32 { if n == 0 { return 2; } match n% 10 { 2 => n + 1, 3 | 5 => n + 2, _ => 2 + next_prime_digit_number(n / 10) * 10, } } fn smarandache_prime_digital_sequence() -> impl std::iter::Iterator<Item = u32> { let mut n = 0; std::iter::from_fn(move || { loop { n = next_prime_digit_number(n); if is_prime(n) { break; } } Some(n) }) } fn main() { let limit = 1000000000; let mut seq = smarandache_prime_digital_sequence().take_while(|x| *x < limit); println!("First 25 SPDS primes:"); for i in seq.by_ref().take(25) { print!("{} ", i); } println!(); if let Some(p) = seq.by_ref().nth(99 - 25) { println!("100th SPDS prime: {}", p); } if let Some(p) = seq.by_ref().nth(999 - 100) { println!("1000th SPDS prime: {}", p); } if let Some(p) = seq.by_ref().nth(9999 - 1000) { println!("10,000th SPDS prime: {}", p); } if let Some(p) = seq.last() { println!("Largest SPDS prime less than {}: {}", limit, p); } }
259Smarandache prime-digital sequence
15rust
ercaj
require smarandache = Enumerator.new do|y| prime_digits = [2,3,5,7] prime_digits.each{|pr| y << pr} (1..).each do |n| prime_digits.repeated_permutation(n).each do |perm| c = perm.join.to_i * 10 y << c + 3 if (c+3).prime? y << c + 7 if (c+7).prime? end end end seq = smarandache.take(100) p seq.first(25) p seq.last
259Smarandache prime-digital sequence
14ruby
ag91s
null
261Solve a Hidato puzzle
11kotlin
gmo4d
v = c("Here", "are", "some", "sample", "strings", "to", "be", "sorted") print(v[order(-nchar(v), tolower(v))])
243Sort using a custom comparator
13r
sbsqy
func isPrime(number: Int) -> Bool { if number < 2 { return false } if number% 2 == 0 { return number == 2 } if number% 3 == 0 { return number == 3 } if number% 5 == 0 { return number == 5 } var p = 7 let wheel = [4,2,4,2,4,6,2,6] while true { for w in wheel { if p * p > number { return true } if number% p == 0 { return false } p += w } } } func nextPrimeDigitNumber(number: Int) -> Int { if number == 0 { return 2 } switch number% 10 { case 2: return number + 1 case 3, 5: return number + 2 default: return 2 + nextPrimeDigitNumber(number: number/10) * 10 } } let limit = 1000000000 var n = 0 var max = 0 var count = 0 print("First 25 SPDS primes:") while n < limit { n = nextPrimeDigitNumber(number: n) if!isPrime(number: n) { continue } if count < 25 { print(n, terminator: " ") } else if count == 25 { print() } count += 1 if (count == 100) { print("Hundredth SPDS prime: \(n)") } else if (count == 1000) { print("Thousandth SPDS prime: \(n)") } else if (count == 10000) { print("Ten thousandth SPDS prime: \(n)") } max = n } print("Largest SPDS prime less than \(limit): \(max)")
259Smarandache prime-digital sequence
17swift
14mpt
null
262Snake
11kotlin
kvfh3
null
252Sort an integer array
11kotlin
9nimh
def cocktailSort(A): up = range(len(A)-1) while True: for indices in (up, reversed(up)): swapped = False for i in indices: if A[i] > A[i+1]: A[i], A[i+1] = A[i+1], A[i] swapped = True if not swapped: return
240Sorting algorithms/Cocktail sort
3python
v3429
UP, RIGHT, DOWN, LEFT = 1, 2, 3, 4 UpdateTime=0.200 Timer = 0 GridSize = 30 GridWidth, GridHeight = 20, 10 local directions = { [UP] = {x= 0, y=-1}, [RIGHT] = {x= 1, y= 0}, [DOWN] = {x= 0, y= 1}, [LEFT] = {x=-1, y= 0}, } local function isPositionInBody(x, y) for i = 1, #Body-3, 2 do
262Snake
1lua
butka
function sorting( a, b ) return a[1] < b[1] end tab = { {"C++", 1979}, {"Ada", 1983}, {"Ruby", 1995}, {"Eiffel", 1985} } table.sort( tab, sorting ) for _, v in ipairs( tab ) do print( unpack(v) ) end
255Sort an array of composite structures
1lua
8pj0e
cocktailSort <- function(A) { repeat { swapped <- FALSE for(i in seq_len(length(A) - 1)) { if(A[i] > A[i + 1]) { A[c(i, i + 1)] <- A[c(i + 1, i)] swapped <- TRUE } } if(!swapped) break swapped <- FALSE for(i in (length(A)-1):1) { if(A[i] > A[i + 1]) { A[c(i, i + 1)] <- A[c(i + 1, i)] swapped <- TRUE } } if(!swapped) break } A } ints <- c(1, 10, 2, 5, -1, 5, -19, 4, 23, 0) numerics <- c(1, -3.2, 5.2, 10.8, -5.7, 7.3, 3.5, 0, -4.1, -9.5) strings <- c("We", "hold", "these", "truths", "to", "be", "self-evident", "that", "all", "men", "are", "created", "equal")
240Sorting algorithms/Cocktail sort
13r
9d2mg
>>> def sort_disjoint_sublist(data, indices): indices = sorted(indices) values = sorted(data[i] for i in indices) for index, value in zip(indices, values): data[index] = value >>> d = [7, 6, 5, 4, 3, 2, 1, 0] >>> i = set([6, 1, 7]) >>> sort_disjoint_sublist(d, i) >>> d [7, 0, 5, 4, 3, 2, 1, 6] >>> >>> def sort_disjoint_sublist(data, indices): for index, value in zip(sorted(indices), sorted(data[i] for i in indices)): data[index] = value >>>
247Sort disjoint sublist
3python
nesiz
words = %w(Here are some sample strings to be sorted) p words.sort_by {|word| [-word.size, word.downcase]}
243Sort using a custom comparator
14ruby
dxdns
public static <E extends Comparable<? super E>> void bubbleSort(E[] comparable) { boolean changed = false; do { changed = false; for (int a = 0; a < comparable.length - 1; a++) { if (comparable[a].compareTo(comparable[a + 1]) > 0) { E tmp = comparable[a]; comparable[a] = comparable[a + 1]; comparable[a + 1] = tmp; changed = true; } } } while (changed); }
246Sorting algorithms/Bubble sort
9java
bu7k3
use strict; use List::Util 'max'; our (@grid, @known, $n); sub show_board { for my $r (@grid) { print map(!defined($_) ? ' ' : $_ ? sprintf("%3d", $_) : ' __' , @$r), "\n" } } sub parse_board { @grid = map{[map(/^_/ ? 0 : /^\./ ? undef: $_, split ' ')]} split "\n", shift(); for my $y (0 .. $ for my $x (0 .. $ $grid[$y][$x] > 0 and $known[$grid[$y][$x]] = "$y,$x"; } } $n = max(map { max @$_ } @grid); } sub neighbors { my ($y, $x) = @_; my @out; for ( [-1, -1], [-1, 0], [-1, 1], [ 0, -1], [ 0, 1], [ 1, -1], [ 1, 0], [ 1, 1]) { my $y1 = $y + $_->[0]; my $x1 = $x + $_->[1]; next if $x1 < 0 || $y1 < 0; next unless defined $grid[$y1][$x1]; push @out, "$y1,$x1"; } @out } sub try_fill { my ($v, $coord) = @_; return 1 if $v > $n; my ($y, $x) = split ',', $coord; my $old = $grid[$y][$x]; return if $old && $old != $v; return if exists $known[$v] and $known[$v] ne $coord; $grid[$y][$x] = $v; print "\033[0H"; show_board(); try_fill($v + 1, $_) && return 1 for neighbors($y, $x); $grid[$y][$x] = $old; return } parse_board "__ 33 35 __ __ .. .. .. . __ __ 24 22 __ .. .. .. . __ __ __ 21 __ __ .. .. . __ 26 __ 13 40 11 .. .. . 27 __ __ __ 9 __ 1 .. . . . __ __ 18 __ __ .. . . .. . . __ 7 __ __ . . .. .. .. . . 5 __ ."; print "\033[2J"; try_fill(1, $known[1]);
261Solve a Hidato puzzle
2perl
negiw
t = {4, 5, 2} table.sort(t) print(unpack(t))
252Sort an integer array
1lua
cdn92
values=c(7,6,5,4,3,2,1,0) indices=c(7,2,8) values[sort(indices)]=sort(values[indices]) print(values)
247Sort disjoint sublist
13r
0besg
fn main() { let mut words = ["Here", "are", "some", "sample", "strings", "to", "be", "sorted"]; words.sort_by(|l, r| Ord::cmp(&r.len(), &l.len()).then(Ord::cmp(l, r))); println!("{:?}", words); }
243Sort using a custom comparator
15rust
fqfd6
Array.prototype.bubblesort = function() { var done = false; while (!done) { done = true; for (var i = 1; i<this.length; i++) { if (this[i-1] > this[i]) { done = false; [this[i-1], this[i]] = [this[i], this[i-1]] } } } return this; }
246Sorting algorithms/Bubble sort
10javascript
w7pe2
class Array def gnomesort! i, j = 1, 2 while i < length if self[i-1] <= self[i] i, j = j, j+1 else self[i-1], self[i] = self[i], self[i-1] i -= 1 if i == 0 i, j = j, j+1 end end end self end end ary = [7,6,5,9,8,4,3,1,2,0] ary.gnomesort!
238Sorting algorithms/Gnome sort
14ruby
j217x
use utf8; use Time::HiRes qw(sleep); use Term::ANSIColor qw(colored); use Term::ReadKey qw(ReadMode ReadLine); binmode(STDOUT, ':utf8'); use constant { VOID => 0, HEAD => 1, BODY => 2, TAIL => 3, FOOD => 4, }; use constant { LEFT => [+0, -1], RIGHT => [+0, +1], UP => [-1, +0], DOWN => [+1, +0], }; use constant { BG_COLOR => "on_black", SLEEP_SEC => 0.05, }; use constant { SNAKE_COLOR => ('bold green' . ' ' . BG_COLOR), FOOD_COLOR => ('red' . ' ' . BG_COLOR), }; use constant { U_HEAD => colored('', SNAKE_COLOR), D_HEAD => colored('', SNAKE_COLOR), L_HEAD => colored('', SNAKE_COLOR), R_HEAD => colored('', SNAKE_COLOR), U_BODY => colored('', SNAKE_COLOR), D_BODY => colored('', SNAKE_COLOR), L_BODY => colored('', SNAKE_COLOR), R_BODY => colored('', SNAKE_COLOR), U_TAIL => colored('', SNAKE_COLOR), D_TAIL => colored('', SNAKE_COLOR), L_TAIL => colored('', SNAKE_COLOR), R_TAIL => colored('', SNAKE_COLOR), A_VOID => colored(' ', BG_COLOR), A_FOOD => colored('', FOOD_COLOR), }; local $| = 1; my $w = eval { `tput cols` } || 80; my $h = eval { `tput lines` } || 24; my $r = "\033[H"; my @grid = map { [map { [VOID] } 1 .. $w] } 1 .. $h; my $dir = LEFT; my @head_pos = ($h / 2, $w / 2); my @tail_pos = ($head_pos[0], $head_pos[1] + 1); $grid[$head_pos[0]][$head_pos[1]] = [HEAD, $dir]; $grid[$tail_pos[0]][$tail_pos[1]] = [TAIL, $dir]; sub create_food { my ($food_x, $food_y); do { $food_x = rand($w); $food_y = rand($h); } while ($grid[$food_y][$food_x][0] != VOID); $grid[$food_y][$food_x][0] = FOOD; } create_food(); sub display { my $i = 0; print $r, join("\n", map { join("", map { my $t = $_->[0]; if ($t != FOOD and $t != VOID) { my $p = $_->[1]; $i = $p eq UP ? 0 : $p eq DOWN ? 1 : $p eq LEFT ? 2 : 3; } $t == HEAD ? (U_HEAD, D_HEAD, L_HEAD, R_HEAD)[$i] : $t == BODY ? (U_BODY, D_BODY, L_BODY, R_BODY)[$i] : $t == TAIL ? (U_TAIL, D_TAIL, L_TAIL, R_TAIL)[$i] : $t == FOOD ? (A_FOOD) : (A_VOID); } @{$_} ) } @grid ); } sub move { my $grew = 0; { my ($y, $x) = @head_pos; my $new_y = ($y + $dir->[0]) % $h; my $new_x = ($x + $dir->[1]) % $w; my $cell = $grid[$new_y][$new_x]; my $t = $cell->[0]; if ($t == BODY or $t == TAIL) { die "Game over!\n"; } elsif ($t == FOOD) { create_food(); $grew = 1; } $grid[$new_y][$new_x] = [HEAD, $dir]; $grid[$y][$x] = [BODY, $dir]; @head_pos = ($new_y, $new_x); } if (not $grew) { my ($y, $x) = @tail_pos; my $pos = $grid[$y][$x][1]; my $new_y = ($y + $pos->[0]) % $h; my $new_x = ($x + $pos->[1]) % $w; $grid[$y][$x][0] = VOID; $grid[$new_y][$new_x][0] = TAIL; @tail_pos = ($new_y, $new_x); } } ReadMode(3); while (1) { my $key; until (defined($key = ReadLine(-1))) { move(); display(); sleep(SLEEP_SEC); } if ($key eq "\e[A" and $dir ne DOWN ) { $dir = UP } elsif ($key eq "\e[B" and $dir ne UP ) { $dir = DOWN } elsif ($key eq "\e[C" and $dir ne LEFT ) { $dir = RIGHT } elsif ($key eq "\e[D" and $dir ne RIGHT) { $dir = LEFT } }
262Snake
2perl
30hzs
List("Here", "are", "some", "sample", "strings", "to", "be", "sorted").sortWith{(a,b) => val cmp=a.size-b.size (if (cmp==0) -a.compareTo(b) else cmp) > 0 }
243Sort using a custom comparator
16scala
383zy
fn gnome_sort<T: PartialOrd>(a: &mut [T]) { let len = a.len(); let mut i: usize = 1; let mut j: usize = 2; while i < len { if a[i - 1] <= a[i] {
238Sorting algorithms/Gnome sort
15rust
hvaj2
package main import "fmt" func numPrimeFactors(x uint) int { var p uint = 2 var pf int if x == 1 { return 1 } for { if (x % p) == 0 { pf++ x /= p if x == 1 { return pf } } else { p++ } } } func primeFactors(x uint, arr []uint) { var p uint = 2 var pf int if x == 1 { arr[pf] = 1 return } for { if (x % p) == 0 { arr[pf] = p pf++ x /= p if x == 1 { return } } else { p++ } } } func sumDigits(x uint) uint { var sum uint for x != 0 { sum += x % 10 x /= 10 } return sum } func sumFactors(arr []uint, size int) uint { var sum uint for a := 0; a < size; a++ { sum += sumDigits(arr[a]) } return sum } func listAllSmithNumbers(maxSmith uint) { var arr []uint var a uint for a = 4; a < maxSmith; a++ { numfactors := numPrimeFactors(a) arr = make([]uint, numfactors) if numfactors < 2 { continue } primeFactors(a, arr) if sumDigits(a) == sumFactors(arr, numfactors) { fmt.Printf("%4d ", a) } } } func main() { const maxSmith = 10000 fmt.Printf("All the Smith Numbers less than%d are:\n", maxSmith) listAllSmithNumbers(maxSmith) fmt.Println() }
263Smith numbers
0go
9npmt
object GnomeSort { def gnomeSort(a: Array[Int]): Unit = { var (i, j) = (1, 2) while ( i < a.length) if (a(i - 1) <= a(i)) { i = j; j += 1 } else { val tmp = a(i - 1) a(i - 1) = a(i) a({i -= 1; i + 1}) = tmp i = if (i == 0) {j += 1; j - 1} else i } } }
238Sorting algorithms/Gnome sort
16scala
p4xbj
use Socket; $host = gethostbyname('localhost'); $in = sockaddr_in(256, $host); $proto = getprotobyname('tcp'); socket(Socket_Handle, AF_INET, SOCK_STREAM, $proto); connect(Socket_Handle, $in); send(Socket_Handle, 'hello socket world', 0, $in); close(Socket_Handle);
258Sockets
2perl
56iu2
from __future__ import annotations import itertools import random from enum import Enum from typing import Any from typing import Tuple import pygame as pg from pygame import Color from pygame import Rect from pygame.surface import Surface from pygame.sprite import AbstractGroup from pygame.sprite import Group from pygame.sprite import RenderUpdates from pygame.sprite import Sprite class Direction(Enum): UP = (0, -1) DOWN = (0, 1) LEFT = (-1, 0) RIGHT = (1, 0) def opposite(self, other: Direction): return (self[0] + other[0], self[1] + other[1]) == (0, 0) def __getitem__(self, i: int): return self.value[i] class SnakeHead(Sprite): def __init__( self, size: int, position: Tuple[int, int], facing: Direction, bounds: Rect, ) -> None: super().__init__() self.image = Surface((size, size)) self.image.fill(Color()) self.rect = self.image.get_rect() self.rect.center = position self.facing = facing self.size = size self.speed = size self.bounds = bounds def update(self, *args: Any, **kwargs: Any) -> None: self.rect.move_ip( ( self.facing[0] * self.speed, self.facing[1] * self.speed, ) ) if self.rect.right > self.bounds.right: self.rect.left = 0 elif self.rect.left < 0: self.rect.right = self.bounds.right if self.rect.bottom > self.bounds.bottom: self.rect.top = 0 elif self.rect.top < 0: self.rect.bottom = self.bounds.bottom def change_direction(self, direction: Direction): if not self.facing == direction and not direction.opposite(self.facing): self.facing = direction class SnakeBody(Sprite): def __init__( self, size: int, position: Tuple[int, int], colour: str = , ) -> None: super().__init__() self.image = Surface((size, size)) self.image.fill(Color(colour)) self.rect = self.image.get_rect() self.rect.center = position class Snake(RenderUpdates): def __init__(self, game: Game) -> None: self.segment_size = game.segment_size self.colours = itertools.cycle([, ]) self.head = SnakeHead( size=self.segment_size, position=game.rect.center, facing=Direction.RIGHT, bounds=game.rect, ) neck = [ SnakeBody( size=self.segment_size, position=game.rect.center, colour=next(self.colours), ) for _ in range(2) ] super().__init__(*[self.head, *neck]) self.body = Group() self.tail = neck[-1] def update(self, *args: Any, **kwargs: Any) -> None: self.head.update() segments = self.sprites() for i in range(len(segments) - 1, 0, -1): segments[i].rect.center = segments[i - 1].rect.center def change_direction(self, direction: Direction): self.head.change_direction(direction) def grow(self): tail = SnakeBody( size=self.segment_size, position=self.tail.rect.center, colour=next(self.colours), ) self.tail = tail self.add(self.tail) self.body.add(self.tail) class SnakeFood(Sprite): def __init__(self, game: Game, size: int, *groups: AbstractGroup) -> None: super().__init__(*groups) self.image = Surface((size, size)) self.image.fill(Color()) self.rect = self.image.get_rect() self.rect.topleft = ( random.randint(0, game.rect.width), random.randint(0, game.rect.height), ) self.rect.clamp_ip(game.rect) while pg.sprite.spritecollideany(self, game.snake): self.rect.topleft = ( random.randint(0, game.rect.width), random.randint(0, game.rect.height), ) self.rect.clamp_ip(game.rect) class Game: def __init__(self) -> None: self.rect = Rect(0, 0, 640, 480) self.background = Surface(self.rect.size) self.background.fill(Color()) self.score = 0 self.framerate = 16 self.segment_size = 10 self.snake = Snake(self) self.food_group = RenderUpdates(SnakeFood(game=self, size=self.segment_size)) pg.init() def _init_display(self) -> Surface: bestdepth = pg.display.mode_ok(self.rect.size, 0, 32) screen = pg.display.set_mode(self.rect.size, 0, bestdepth) pg.display.set_caption() pg.mouse.set_visible(False) screen.blit(self.background, (0, 0)) pg.display.flip() return screen def draw(self, screen: Surface): dirty = self.snake.draw(screen) pg.display.update(dirty) dirty = self.food_group.draw(screen) pg.display.update(dirty) def update(self, screen): self.food_group.clear(screen, self.background) self.food_group.update() self.snake.clear(screen, self.background) self.snake.update() def main(self) -> int: screen = self._init_display() clock = pg.time.Clock() while self.snake.head.alive(): for event in pg.event.get(): if event.type == pg.QUIT or ( event.type == pg.KEYDOWN and event.key in (pg.K_ESCAPE, pg.K_q) ): return self.score keystate = pg.key.get_pressed() if keystate[pg.K_RIGHT]: self.snake.change_direction(Direction.RIGHT) elif keystate[pg.K_LEFT]: self.snake.change_direction(Direction.LEFT) elif keystate[pg.K_UP]: self.snake.change_direction(Direction.UP) elif keystate[pg.K_DOWN]: self.snake.change_direction(Direction.DOWN) self.update(screen) for food in pg.sprite.spritecollide( self.snake.head, self.food_group, dokill=False ): food.kill() self.snake.grow() self.score += 1 if self.score% 5 == 0: self.framerate += 1 self.food_group.add(SnakeFood(self, self.segment_size)) if pg.sprite.spritecollideany(self.snake.head, self.snake.body): self.snake.head.kill() self.draw(screen) clock.tick(self.framerate) return self.score if __name__ == : game = Game() score = game.main() print(score)
262Snake
3python
68k3w
import Data.Numbers.Primes (primeFactors) import Data.List (unfoldr) import Data.Tuple (swap) import Data.Bool (bool) isSmith :: Int -> Bool isSmith n = pfs /= [n] && sumDigits n == foldr ((+) . sumDigits) 0 pfs where sumDigits = sum . baseDigits 10 pfs = primeFactors n baseDigits :: Int -> Int -> [Int] baseDigits base = unfoldr remQuot where remQuot 0 = Nothing remQuot x = Just (swap (quotRem x base)) lowSmiths :: [Int] lowSmiths = filter isSmith [2 .. 9999] lowSmithCount :: Int lowSmithCount = length lowSmiths main :: IO () main = mapM_ putStrLn [ "Count of Smith Numbers below 10k:" , show lowSmithCount , "\nFirst 15 Smith Numbers:" , unwords (show <$> take 15 lowSmiths) , "\nLast 12 Smith Numbers below 10k:" , unwords (show <$> drop (lowSmithCount - 12) lowSmiths) ]
263Smith numbers
8haskell
bufk2
def sort_disjoint_sublist!(ar, indices) values = ar.values_at(*indices).sort indices.sort.zip(values).each{ |i,v| ar[i] = v } ar end values = [7, 6, 5, 4, 3, 2, 1, 0] indices = [6, 1, 7] p sort_disjoint_sublist!(values, indices)
247Sort disjoint sublist
14ruby
fx8dr
import java.util.Comparator fun <T> bubbleSort(a: Array<T>, c: Comparator<T>) { var changed: Boolean do { changed = false for (i in 0..a.size - 2) { if (c.compare(a[i], a[i + 1]) > 0) { val tmp = a[i] a[i] = a[i + 1] a[i + 1] = tmp changed = true } } } while (changed) }
246Sorting algorithms/Bubble sort
11kotlin
r9ugo
class Array def cocktailsort! begin swapped = false 0.upto(length - 2) do |i| if self[i] > self[i + 1] self[i], self[i + 1] = self[i + 1], self[i] swapped = true end end break unless swapped swapped = false (length - 2).downto(0) do |i| if self[i] > self[i + 1] self[i], self[i + 1] = self[i + 1], self[i] swapped = true end end end while swapped self end end
240Sorting algorithms/Cocktail sort
14ruby
5yruj
$socket = fsockopen('localhost', 256); fputs($socket, 'hello socket world'); fclose($socket);
258Sockets
12php
o1r85
import java.util.*; public class SmithNumbers { public static void main(String[] args) { for (int n = 1; n < 10_000; n++) { List<Integer> factors = primeFactors(n); if (factors.size() > 1) { int sum = sumDigits(n); for (int f : factors) sum -= sumDigits(f); if (sum == 0) System.out.println(n); } } } static List<Integer> primeFactors(int n) { List<Integer> result = new ArrayList<>(); for (int i = 2; n % i == 0; n /= i) result.add(i); for (int i = 3; i * i <= n; i += 2) { while (n % i == 0) { result.add(i); n /= i; } } if (n != 1) result.add(n); return result; } static int sumDigits(int n) { int sum = 0; while (n > 0) { sum += (n % 10); n /= 10; } return sum; } }
263Smith numbers
9java
gm04m
use std::collections::BTreeSet; fn disjoint_sort(array: &mut [impl Ord], indices: &[usize]) { let mut sorted = indices.to_owned(); sorted.sort_unstable_by_key(|k| &array[*k]); indices .iter() .zip(sorted.iter()) .map(|(&a, &b)| if a > b { (b, a) } else { (a, b) }) .collect::<BTreeSet<_>>() .iter() .for_each(|(a, b)| array.swap(*a, *b)) } fn main() { let mut array = [7, 6, 5, 4, 3, 2, 1, 0]; let indices = [6, 1, 7]; disjoint_sort(&mut array, &indices); println!("{:?}", array); }
247Sort disjoint sublist
15rust
tqofd
import Foundation var list = ["this", "is", "a", "set", "of", "strings", "to", "sort", "This", "Is", "A", "Set", "Of", "Strings", "To", "Sort"] list.sortInPlace {lhs, rhs in let lhsCount = lhs.characters.count let rhsCount = rhs.characters.count let result = rhsCount - lhsCount if result == 0 { return lhs.lowercaseString > rhs.lowercaseString } return lhsCount > rhsCount }
243Sort using a custom comparator
17swift
nwnil
#![windows_subsystem = "windows"] use rand::Rng; use std::{cell::RefCell, rc::Rc}; use winsafe::{co, gui, prelude::*, COLORREF, HBRUSH, HPEN, SIZE}; const STEP: i32 = 3;
262Snake
15rust
9n1mm
(() => { 'use strict';
263Smith numbers
10javascript
kvdhq
board = [] given = [] start = None def setup(s): global board, given, start lines = s.splitlines() ncols = len(lines[0].split()) nrows = len(lines) board = [[-1] * (ncols + 2) for _ in xrange(nrows + 2)] for r, row in enumerate(lines): for c, cell in enumerate(row.split()): if cell == : board[r + 1][c + 1] = 0 continue elif cell == : continue else: val = int(cell) board[r + 1][c + 1] = val given.append(val) if val == 1: start = (r + 1, c + 1) given.sort() def solve(r, c, n, next=0): if n > given[-1]: return True if board[r][c] and board[r][c] != n: return False if board[r][c] == 0 and given[next] == n: return False back = 0 if board[r][c] == n: next += 1 back = n board[r][c] = n for i in xrange(-1, 2): for j in xrange(-1, 2): if solve(r + i, c + j, n + 1, next): return True board[r][c] = back return False def print_board(): d = {-1: , 0: } bmax = max(max(r) for r in board) form = + str(len(str(bmax)) + 1) + for r in board[1:-1]: print .join(form% d.get(c, str(c)) for c in r[1:-1]) hi = setup(hi) print_board() solve(start[0], start[1], 1) print print_board()
261Solve a Hidato puzzle
3python
dwrn1
import scala.compat.Platform object SortedDisjointSubList extends App { val (list, subListIndex) = (List(7, 6, 5, 4, 3, 2, 1, 0), List(6, 1, 7)) def sortSubList[T: Ordering](indexList: List[Int], list: List[T]) = { val subListIndex = indexList.sorted val sortedSubListMap = subListIndex.zip(subListIndex.map(list(_)).sorted).toMap list.zipWithIndex.map { case (value, index) => if (sortedSubListMap.isDefinedAt(index)) sortedSubListMap(index) else value } } assert(sortSubList(subListIndex, list) == List(7, 0, 5, 4, 3, 2, 1, 6), "Incorrect sort") println(s"List in sorted order.\nSuccessfully completed without errors. [total ${Platform.currentTime - executionStart} ms]") }
247Sort disjoint sublist
16scala
68d31
fn cocktail_sort<T: PartialOrd>(a: &mut [T]) { let len = a.len(); loop { let mut swapped = false; let mut i = 0; while i + 1 < len { if a[i] > a[i + 1] { a.swap(i, i + 1); swapped = true; } i += 1; } if swapped { swapped = false; i = len - 1; while i > 0 { if a[i - 1] > a[i] { a.swap(i - 1, i); swapped = true; } i -= 1; } } if!swapped { break; } } } fn main() { let mut v = vec![10, 8, 4, 3, 1, 9, 0, 2, 7, 5, 6]; println!("before: {:?}", v); cocktail_sort(&mut v); println!("after: {:?}", v); }
240Sorting algorithms/Cocktail sort
15rust
4m75u
import socket sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.connect((, 256)) sock.sendall() sock.close()
258Sockets
3python
4yn5k
object CocktailSort extends App { def sort(arr: Array[Int]) = { var swapped = false do { def swap(i: Int) { val temp = arr(i) arr(i) = arr(i + 1) arr(i + 1) = temp swapped = true } swapped = false for (i <- 0 to (arr.length - 2)) if (arr(i) > arr(i + 1)) swap(i) if (swapped) { swapped = false for (j <- arr.length - 2 to 0 by -1) if (arr(j) > arr(j + 1)) swap(j)
240Sorting algorithms/Cocktail sort
16scala
7lkr9
s <- make.socket(port = 256) write.socket(s, "hello socket world") close.socket(s)
258Sockets
13r
2t0lg
null
263Smith numbers
11kotlin
2teli
function bubbleSort(A) local itemCount=#A local hasChanged repeat hasChanged = false itemCount=itemCount - 1 for i = 1, itemCount do if A[i] > A[i + 1] then A[i], A[i + 1] = A[i + 1], A[i] hasChanged = true end end until hasChanged == false end
246Sorting algorithms/Bubble sort
1lua
7c5ru
func gnomeSort<T: Comparable>(_ a: inout [T]) { var i = 1 var j = 2 while i < a.count { if a[i - 1] <= a[i] { i = j j += 1 } else { a.swapAt(i - 1, i) i -= 1 if i == 0 { i = j j += 1 } } } } var array = [10, 8, 4, 3, 1, 9, 0, 2, 7, 5, 6] print("before: \(array)") gnomeSort(&array) print(" after: \(array)")
238Sorting algorithms/Gnome sort
17swift
7lprq
null
263Smith numbers
1lua
vzw2x
@people = (['joe', 120], ['foo', 31], ['bar', 51]); @people = sort { $a->[0] cmp $b->[0] } @people;
255Sort an array of composite structures
2perl
56fu2